#!/usr/bin/bash

if [ $(/usr/bin/id -u) != 0 ]; then echo "only root can do that"; exit 2; fi

#***************************************************************************
# This file is part of the CRYPTO BONE
# File     : initialkeysetup (external cryptobone)
# Version  : 2.0 
# License  : BSD-3.Clause
# Date     : 26 May 2025
# Contact  : Please send enquiries and bug-reports to innovation@senderek.ie
#
#
# Copyright (c) 2015-2025
#	Ralf Senderek, Ireland.  All rights reserved. (https://senderek.ie)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. All advertising materials mentioning features or use of this software
#    must display the following acknowledgement:
#	   This product includes software developed by Ralf Senderek.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND  ANY EXPRESS OR 
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  IMPLIED WARRANTIES 
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
# POSSIBILITY OF SUCH DAMAGE.
#****************************************************************************

# This script generates all necessary secrets that are needed to establish a secure
# connection between a client machine (in EXTERNAL mode) and an external device.
#
# The secrets that have to be transferred to the client machine for use by the GUI
# are generated inside the ramdisk /dev/shm/BOOT on the external device.

# Let's assume you have a ssh shell to the external device as root.
# When this script has finished, you'll find the secrets in /dev/shm/BOOT on the
# external device.
# Log into your client device (as the ordinary user) and do the following to transfer the secets:
#
#     cd /dev/shm; mkdir BOOT; cd BOOT
#     scp root@externaldevice:/dev/shm/BOOT/secrets.tgz .
#     tar xvpzf secrets.tgz
# make sure the BOOT directory and its files are readable by the GUI under the user's UID.

# Start the GUI and press the "Copy EXT Secrets" button (in SETUP) in order to save the secrets
# in the client's encrypted database.
# Delete the directory /dev/shm/BOOT on the client machine and reboot your computer.
# During the next boot process of your client machine the master key is being uploaded to
# your external device to the external daemon that is waiting for the master key all the time.
# Once the master key reaches the external device for the first time, the daemon will decrypt 
# its encrypted database and will go into "active" mode. The external device is now operational.

# Note that the masterkey is never stored on the external device. The external database can only be 
# decrypted when the masterkey arrives via the secure ssh tunnel from the client machine.

function generate_login_secret
{
     # secret (local.key) used for cryptobone sudo and to protect the ssh private key
     echo -n $(/bin/dd if=/dev/urandom bs=1 count=20 2> /dev/null | /usr/bin/sha256sum | /usr/bin/cut -c-40)
}

SECRET=$(generate_login_secret)
BOOT="/dev/shm/BOOT"

/bin/mkdir -p $BOOT
chmod 700 $BOOT
echo "Using $BOOT to store external keys"


if [[ ! -L /usr/lib/cryptobone/ext/masterkey ]]; then
          # the cryptoboneexternd is enabled 
          echo " Creating new masterkey ... "
	  PERM=$(getenforce)
	  setenforce Permissive
          RAMDIR="/dev/shm/EXRAM"
          mkdir $RAMDIR
          chmod 700 $RAMDIR
          /bin/dd if=/dev/urandom bs=1 count=20 2> /dev/null | /usr/bin/sha256sum | /usr/bin/cut -c-40 >  $RAMDIR/masterkey
          /bin/chmod 600 $RAMDIR/masterkey
	  # store a hash value of the masterkey in the external device
          echo -n $(cat $RAMDIR/masterkey) | /usr/bin/sha256sum | /usr/bin/cut -c-64 > /usr/lib/cryptobone/ext/masterkey.hash 
          /bin/chmod 600 /usr/lib/cryptobone/ext/masterkey.hash
	  # prepare sudo for cryptobone user
	  /bin/cp /usr/lib/cryptobone/ext/externalcryptobone /etc/sudoers.d

	  if [ -r $RAMDIR/masterkey ]
          then
               # on success create link in /usr/lib/cryptobone/ext
               /bin/ln -s $RAMDIR/masterkey /usr/lib/cryptobone/ext/masterkey
	       /bin/cp $RAMDIR/masterkey $BOOT/master.key
          fi

          # create cryptobone user account and setup authorized_keys for the ssh tunnel
	  if  ! /usr/bin/grep cryptobone /etc/passwd ; then
	       echo "Creating user cryptobone"
	       /bin/rm -f /usr/lib/cryptobone/ext/cryptobone 2>/dev/null
               /usr/sbin/useradd -m -b /usr/lib/cryptobone/ext -s /usr/lib/cryptobone/ext/cryptoboneshell cryptobone
	       # cryptobone needs access to its $HOME
	       chown cryptobone /usr/lib/cryptobone/ext/cryptobone
	       chmod 700 /usr/lib/cryptobone/ext/cryptobone 
	       /bin/chown cryptobone /usr/lib/cryptobone/ext /usr/lib/cryptobone /usr/lib/cryptobone/ext/cryptoboneshell
          fi
          /bin/chmod 700 /usr/lib/cryptobone/ext /usr/lib/cryptobone /usr/lib/cryptobone/ext/cryptoboneshell
          echo  "cryptobone:${SECRET}" | /usr/sbin/chpasswd 
          /bin/mkdir /usr/lib/cryptobone/ext/cryptobone/.ssh 2> /dev/null 
          /bin/chown cryptobone /usr/lib/cryptobone/ext/cryptobone/.ssh
	  /bin/chmod 700 /usr/lib/cryptobone/ext/cryptobone
	  /bin/chmod 700 /usr/lib/cryptobone/ext/cryptobone/.ssh

	  # generate a ssh key pair
          /bin/rm /usr/lib/cryptobone/ext/cryptobone/.ssh/cbb* 2> /dev/null
	  /usr/bin/ssh-keygen -N ${SECRET} -b 2048 -t rsa -f /usr/lib/cryptobone/ext/cryptobone/.ssh/cbb

	  # prepare the authorized_keys file for the cryptobone user
	  # everything should be processed by the cryptoboneshell
	  /bin/echo -n "command=\"/usr/lib/cryptobone/ext/cryptoboneshell\" " > /usr/lib/cryptobone/ext/cryptobone/.ssh/authorized_keys
	  /bin/cat /usr/lib/cryptobone/ext/cryptobone/.ssh/cbb.pub >> /usr/lib/cryptobone/ext/cryptobone/.ssh/authorized_keys
	  /bin/chmod 600 /usr/lib/cryptobone/ext/cryptobone/.ssh/authorized_keys
	  /bin/chown cryptobone /usr/lib/cryptobone/ext/cryptobone/.ssh/authorized_keys
          /bin/echo "Copy ssh private key to /dev/shm/BOOT"
	  /bin/cp /usr/lib/cryptobone/ext/cryptobone/.ssh/cbb $BOOT
	  # save the login secret as local.key in $BOOT
          /bin/echo -n ${SECRET} > $BOOT/local.key
	  # save a hash value of the local.key on the external device
          /bin/echo -n ${SECRET} | /usr/bin/sha256sum | /usr/bin/cut -c-64 > /usr/lib/cryptobone/ext/EXTERN.local.hash
	  
	  # generate a tarball of secrets for the client machine
	  cd $BOOT
	  tar cvpzf secrets.tgz cbb local.key master.key
	  chmod 600 secrets.tgz

	  SECRET="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
	  /bin/chown cryptobone /usr/lib/cryptobone/ext/EXTERN.local.hash
	  /bin/chmod 600 $BOOT/local.key /usr/lib/cryptobone/ext/EXTERN.local.hash
	  # delete the ssh private key, as it will be used in the client machine
	  # after the secrets have been transferred to the client machine.
	  /bin/rm -f /usr/lib/cryptobone/ext/cryptobone/.ssh/cbb
	  /bin/sync
          /bin/echo "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" > $RAMDIR/masterkey
	  /bin/rm -f $RAMDIR/masterkey

	  # start fetchmail process
	  systemctl enable cryptoboneexternd
	  systemctl enable cryptobone-fetch.timer
	  systemctl start cryptobone-fetch.timer
	  setenforce $PERM

	  exit 0
else
     echo "a link to /usr/lib/cryptobone/ext/masterkey exists already"
fi
