#!/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  : 1.1.2 
# License  : BSD
# Date     : Friday, 11 August 2017
# Contact  : Please send enquiries and bug-reports to innovation@senderek.ie
#
#
# Copyright (c) 2015-2017
#	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.
#****************************************************************************

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/sha1sum | /usr/bin/cut -c-40)
}

SECRET=$(generate_login_secret)

# check for a beagle bone partition
BOOT=$(df | grep boot | cut -f1 -d' ')
if [[ x$BOOT = "x/dev/mmcblk0p1" ]]; then
     echo "Found Beagle Bone boot partition"
else 
     echo "Searching for USB key ..."
     # check for a mounted USB key with label "BOOT"
     BOOT=$(df | grep BOOT | cut -f1 -d' ')
fi
if [[ x${BOOT} = "x" ]]; then
    # find unmounted USB media
    DEVLIST=$(ls /dev/sda[1-9] /dev/sdb[1-9] /dev/sdc[1-9] 2> /dev/null)
    for DEV in ${DEVLIST}
    do
         if [[ -b $DEV ]]; then
              LABEL=$(echo $(tune2fs -l $DEV 2>/dev/null | grep "volume name:" | cut -f2 -d':'))
	      if [[ x${LABEL} != "x" ]]; then
	           if [[ $LABEL = "BOOT" ]]; then
			BOOT=$DEV
		   fi
	      fi
         fi
    done
    if [[ x${BOOT} = "x" ]]; then
         echo "No USB key available."
         exit 2
    fi	 
fi

echo "Using $BOOT to store external keys"


if [[ ! -L /usr/lib/cryptobone/ext/masterkey ]]; then
          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/sha1sum | /usr/bin/cut -c-40 >  $RAMDIR/masterkey
          /bin/chmod 600 $RAMDIR/masterkey
          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/umount /mnt 2>/dev/null
	       if /bin/mount $BOOT /mnt ;  then
                    echo " Copy masterkey to DOS partition"
	            /bin/cp $RAMDIR/masterkey /mnt/master.key
	            /bin/sync
	       fi
          fi

          # create cryptobone user account and setup authorized_keys
	  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
	  /bin/chown cryptobone /usr/lib/cryptobone/ext/cbcontrol*
          /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
	  /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/echo " Copy ssh private key to DOS partition"
	  /bin/chmod 600 /usr/lib/cryptobone/ext/cryptobone/.ssh/authorized_keys
	  /bin/chown cryptobone /usr/lib/cryptobone/ext/cryptobone/.ssh/authorized_keys
	  /bin/cp /usr/lib/cryptobone/ext/cryptobone/.ssh/cbb /mnt
          /bin/echo -n ${SECRET} > /mnt/local.key
          /bin/echo -n ${SECRET} | /usr/bin/sha256sum | /usr/bin/cut -c-64 > /usr/lib/cryptobone/ext/EXTERN.local.hash
	  SECRET="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
	  /bin/chown cryptobone /usr/lib/cryptobone/ext/EXTERN.local.hash
	  /bin/chmod 600 /mnt/local.key /usr/lib/cryptobone/ext/EXTERN.local.hash
	  /bin/rm -f /usr/lib/cryptobone/ext/cryptobone/.ssh/cbb
	  /bin/sync
	  /bin/umount /mnt
          /bin/echo "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" > $RAMDIR/masterkey
	  /bin/rm -f $RAMDIR/masterkey

          # check postfix and exim 
          if [[ -x /usr/sbin/postfix ]]; then
               if ! systemctl is-enabled postfix; then
                    systemctl enable postfix
	            systemctl start postfix
	            echo "POSTFIX enabled."
               fi  
          else	  
               if [[ -x /usr/sbin/exim ]]; then
                    if ! systemctl is-enabled exim ; then
                         systemctl enable exim
                         systemctl start exim
	                 echo "EXIM enabled."
                    fi
               fi
          fi
	  # start fetchmail process
	  systemctl enable cryptoboneexternd
	  systemctl enable cryptobone-fetchmail.timer
	  systemctl start cryptobone-fetchmail.timer
	  setenforce $PERM

	  exit 0
fi
