#!/bin/sh
#
#    Copyright (c) 2006-2008 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    File name:   secInternalScript
#    Module name: fabos/src/security/ecInternalScript.sh
#
#    This script contains the internal options for various script/binaries.
#
export PATH=/fabos/sbin:/fabos/bin:/bin:/usr/bin:/sbin:/fabos/cliexec
export OPENSSL_CONF=/etc/fabos/openssl.cnf

############################
# commands
############################
MV="/bin/mv"
MKDIR="/bin/mkdir"
TOUCH="/bin/touch"
CP="/bin/cp"
RM=/bin/rm
LS=/bin/ls
LL="/bin/ls -l"
CUT="/usr/bin/cut"
EXPR="/fabos/bin/expr"
HOSTNAME="/bin/hostname"
WWN="/fabos/bin/wwn"
SED="/bin/sed"
AWK="/bin/awk"
GREP="/bin/grep"
OPENSSL_CMD=/usr/bin/openssl
SSHD=/usr/sbin/sshd
GREP=/fabos/bin/grep
HASHOW=/fabos/sbin/hashow

###########################
#Variables
###########################
switchIPv6=0
# File locations and suffixes
ROOT_DIR=/etc/fabos
CERT_DIR=$ROOT_DIR/certs/sw0
CMM_DIR=$ROOT_DIR/certs/cmm
CSR_SUFFIX=.csr
PSK_SUFFIX=.psk
CAP_PPH_SUFFIX=.pp 
PVT_KEY=pvt_key 
PVT_KEY_FILE=$CERT_DIR/$PVT_KEY
CONFIG_FILE=$ROOT_DIR/openssl.cnf
CSR_GEN_INFO=/tmp/csr_gen_info
DSA_PARAMS_FILE=dsaparam.pem

##############################
# Internal Command options
##############################
CERT_FIPS_COMPL=fips_compl
UPDATE_ALLOWED_LOGIN=updateallowedlogin
DEL_USR_PUBKEY=delusrpubkey
DEL_HOST_KEY=deletehostkey
SSH_HOSTKEY_SIZE_CHECK=hostkeysizecheck
ZEROIZE_KNOWN_HOST=zeroizeknownhost

PRIVKEY_DIR=/root/.ssh
PRIVKEY_FILE_OLD=id_dsa
PRIVKEY_FILE=id_rsa
IMPORT_PUBKEY_DIR=/fabos/users/admin/.ssh
IMPORT_PUBKEY_FILE=authorized_keys

HOST_KEY_DIR=/etc
MNT_HOST_KEY_DIR=/mnt/etc
HOST_DSA_KEY=ssh_host_dsa_key
HOST_RSA_KEY=ssh_host_rsa_key
HOST_ECDSA_KEY=ssh_host_ecdsa_key
PUB_SUFFIX=.pub

#SSHD config file
SSHD_CONFIG=/etc/sshd_config
SSHD=/usr/sbin/sshd

# local variables for convenience
CERT_FILE=certificate
CSR_FILE=CSR
CSR_FILE_PATH=$CERT_DIR/$switchIp$CSR_SUFFIX
FILE_NAME="file_name"
fileType=
userInput=
response=
country=
state=
cn=
cmmCertFile=
userName=
password1=
WEBDHANDLER=/fabos/libexec/webdcfghandler
HTTPCONFIG=http.ssl.enabled
CERTCONFIG=ssl.certfile
ROOTCERTCONFIG=ssl.root.certfile
DEFAULTROOTCERTCONFIG="none"

# LDAP definitions
LDAP_DIR=$ROOT_DIR/certs/ldap
LDAP_CACERT_FILE="swLdapca.pem"
LDAP_SWCERT_FILE="swLdapcert.pem"

#RADIUS definitions
RADIUS_DIR=$ROOT_DIR/certs/radius
RADIUS_CACERT_FILE="swRadca.pem"
RADIUS_SWCERT_FILE="swRadcert.pem"

# To be changed based on what password to use or to read from file
# instead of stdin
RANDOM_NUMBER=`$OPENSSL_CMD rand -base64 16`

# FCAP definations
FCAP_DIR=$ROOT_DIR/pki/tp
FCAP_CACERT_FILE="switch.0.rootcrt"
FCAP_SWCERT_FILE="switch.0.crt"

# SYSLOG CA definitions
SYSLOG_DIR=/etc/syslog-ng/ca.d
SYSLOG_CACERT_FILE="ca.pem"
SYSLOG_SWCERT_FILE="syslogswcert.pem"

# Known host defintions
KNOWN_HOST_DIR=.ssh
KNOWN_HOST_FILE=known_hosts

#Exit for trapped signals
trap 'exit 1' SIGINT


############################################
# Internal Functions and Processing
############################################
allowlogin=`cat $SSHD_CONFIG|grep -i "AllowedLogin" |\
         grep -v "#" |cut -d" " -f2`

spaces=${allowlogin##*[! ]} ## get the trailing blanks in var $spaces

allowlogin=`echo ${allowlogin#$spaces}`

sshdAllowUserUpdate() {
        sed "/AllowedLogin/s/$allowlogin/$1/" $SSHD_CONFIG > tmp
        cat tmp > $SSHD_CONFIG
        rm tmp
        config save $SSHD_CONFIG

        # Restart sshd.
        pid=`ps -ef | $GREP "sshd" | $GREP -v "sshd:" | \
                $GREP -v "sshd_config" | $GREP -v grep|$AWK '{print $2}'`
        if [ -n "$pid" ]; then
                kill $pid
        fi
        $SSHD
}

delUsrPubKeyFile() {

        # Delete all the public keys for the user.
        cat /dev/null > $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.$2
        rm -f $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.$2

        # Also on secondary partition of active
        cat /dev/null > $MNT_IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.$2
        rm -f $MNT_IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.$2

        if [ "$2" == "$allowlogin" ]; then
                cat /dev/null > $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE
                # if "userconfig" deleting the user, default the allowed user to admin
                if [ $1 == DEL_USR_PUBKEY ]; then
                        if [ -f $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.admin ]; then
                                cp $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.admin \
                                                 $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE
                        fi
                        sshdAllowUserUpdate admin
                fi
                config save $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE
        fi

        # if this was the last authorized_keys.*,
        # we set authorizedKeys.tar with blank
        ls $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.* 1> /dev/null 2> /dev/null
        if [ $? -eq 0 ]; then
                cd $IMPORT_PUBKEY_DIR
                tar -cf authorizedKeys.tar $IMPORT_PUBKEY_FILE.*
                cd -
        else
                if [ -f $IMPORT_PUBKEY_DIR/authorizedKeys.tar ]; then
                        cat /dev/null > $IMPORT_PUBKEY_DIR/authorizedKeys.tar
                fi
        fi

        config save $IMPORT_PUBKEY_DIR/authorizedKeys.tar

}

caCertComplTest() {
	i=1
	ret=0

	while read line
	do
		echo "$line" >> tmp_fips_$i
		echo $line | grep END > /dev/null 2>&1
		if [ $? = 0 ]; then
			i=`expr $i + 1`
		fi
	done < $1

	j=1
	while [ "$j" -lt "$i" ]
	do
		$OPENSSL_CMD x509 -in tmp_fips_$j -text -noout | \
			grep "Key" | grep 2048 > /dev/null 2>&1
		if [ $? != 0 ]; then
			echo "Key size of $2 is not 2048 bits"
			ret=1

		fi
		$OPENSSL_CMD x509 -in tmp_fips_$j -text -noout | \
			grep "Signature Algorithm" | grep sha256 > /dev/null 2>&1
		if [ $? != 0 ]; then
			echo "Signature Algorithm used in $2 is not Sha256"
			ret=1
		fi
		j=`expr $j + 1`
	done
	j=1
	while [ "$j" -lt "$i" ]
	do
		$RM -rf tmp_fips_$j > /dev/null
		j=`expr $j + 1`
	done
	return $ret
} 

################################################
#	MAIN EXECUTION AND CASE FOR COMMANDS 
################################################
# convert option to all lower case
cmd_option=`echo $1 | tr "[:upper:]" "[:lower:]"`
case "$cmd_option" in
$CERT_FIPS_COMPL )
	fips_compl_ret=0
	# check for ldap ca and switch certificate compliance
	if [ -e "$LDAP_DIR/$LDAP_CACERT_FILE" ]; then
		caCertComplTest "$LDAP_DIR/$LDAP_CACERT_FILE" \
			"LDAP CA certificate"
		temp=$?
		if [ $temp -ne 0 ];then
			fips_compl_ret=$temp
		fi
	fi

    if [ -e "$LDAP_DIR/$LDAP_SWCERT_FILE" ]; then
        caCertComplTest "$LDAP_DIR/$LDAP_SWCERT_FILE" \
            "LDAP switch certificate"
        temp=$?
        if [ $temp -ne 0 ];then
            fips_compl_ret=$temp
        fi
    fi

    # check for radius ca and sw certificate compliance
    if [ -e "$RADIUS_DIR/$RADIUS_CACERT_FILE" ]; then
        caCertComplTest "$RADIUS_DIR/$RADIUS_CACERT_FILE" \
            "RADIUS CA certificate"
        temp=$?
        if [ $temp -ne 0 ];then
            fips_compl_ret=$temp
        fi
    fi

    if [ -e "$RADIUS_DIR/$RADIUS_SWCERT_FILE" ]; then
        caCertComplTest "$RADIUS_DIR/$RADIUS_SWCERT_FILE" \
            "RADIUS switch certificate"
        temp=$?
        if [ $temp -ne 0 ];then
            fips_compl_ret=$temp
        fi
    fi


	# check for HTTPS switch and ca certificate compliance
	cacert=`config get $ROOTCERTCONFIG 5 2> /dev/null`
	if [ "$DEFAULTROOTCERTCONFIG" != "$cacert" ] &&
		[ ! -z "$cacert" ]; then
		caCertComplTest "$CERT_DIR/$cacert" "Switch CA certificate"
		temp=$?
		if [ $temp -ne 0 ];then
			fips_compl_ret=$temp
		fi
	fi

	httpSEnabled=`config get $HTTPCONFIG 1`
	if [ "$httpSEnabled" == 1 ]; then
		httpsCert=`config get $CERTCONFIG 5`
		caCertComplTest "$CERT_DIR/$httpsCert" "HTTPS certificate"
		temp=$?
		if [ $temp -ne 0 ];then
			fips_compl_ret=$temp
		fi
	fi

	# check for fcap switch and ca certificate compliance
	if [ -e "$FCAP_DIR/$FCAP_SWCERT_FILE" ]; then
		caCertComplTest "$FCAP_DIR/$FCAP_SWCERT_FILE" \
			"FCAP certificate"
		temp=$?
		if [ $temp -ne 0 ];then
			fips_compl_ret=$temp
		fi
	fi

	if [ -e "$FCAP_DIR/$FCAP_CACERT_FILE" ]; then
		caCertComplTest "$FCAP_DIR/$FCAP_CACERT_FILE" \
			"FCAP CA certificate"
		temp=$?
		if [ $temp -ne 0 ];then
			fips_compl_ret=$temp
		fi
	fi

	# check for syslog-ng ca and switch certificates compliance.
	if [ -e "$SYSLOG_DIR/$SYSLOG_CACERT_FILE" ]; then
       	caCertComplTest "$SYSLOG_DIR/$SYSLOG_CACERT_FILE" \
     	"SYSLOG-NG CA certificate"
      	temp=$?
       	if [ $temp -ne 0 ];then
         	fips_compl_ret=$temp
       	fi
	fi

    if [ -e "$SYSLOG_DIR/$SYSLOG_SWCERT_FILE" ]; then
        caCertComplTest "$SYSLOG_DIR/$SYSLOG_SWCERT_FILE" \
        "SYSLOG-NG switch certificate"
        temp=$?
        if [ $temp -ne 0 ];then
            fips_compl_ret=$temp
        fi
    fi

	exit $fips_compl_ret
;;

$SSH_HOSTKEY_SIZE_CHECK )
	if [ -e $HOST_KEY_DIR/$HOST_RSA_KEY$PUB_SUFFIX ]; then
	        var=`/usr/bin/ssh-keygen -lf $HOST_KEY_DIR/$HOST_RSA_KEY$PUB_SUFFIX | cut -c 1-4`
        	if [ $var -lt 2048 ]; then
                	exit 1
	        fi
		exit 0	
	fi
;;

"$UPDATE_ALLOWED_LOGIN" )
sshdAllowUserUpdate admin
/fabos/libexec/sshutil_notify allowuser admin
;;

# defect: DEFECT000334381
"$DEL_USR_PUBKEY" )
        # Delete the public key (if any) of the user being deleted
        # this is invoked from "userconfig" code

        # Verify  the no of input arguments before processing
        if [ $# -ne 2 ]
        then
                exit 1
        fi

        delUsrPubKeyFile DEL_USR_PUBKEY $2

;;

"$ZEROIZE_KNOWN_HOST" )
	if [ -e $KNOWN_HOST_DIR/$KNOWN_HOST_FILE ]; then
                size=`/bin/ls -la $KNOWN_HOST_DIR/$KNOWN_HOST_FILE | /bin/awk ' { print $5 } '`
                /bin/dd if=/dev/zero of=$KNOWN_HOST_DIR/$KNOWN_HOST_FILE bs=1 count=$size 2> /dev/null	

		/fabos/cliexec/config save $KNOWN_HOST_DIR/$KNOWN_HOST_FILE
	fi
;;

"$DEL_HOST_KEY" )
        if [ -e $HOST_KEY_DIR/$HOST_DSA_KEY ]; then
                size=`/bin/ls -la $HOST_KEY_DIR/$HOST_DSA_KEY | /bin/awk ' { print $5 } '`
                /bin/dd if=/dev/zero of=$HOST_KEY_DIR/$HOST_DSA_KEY bs=1 count=$size 2> /dev/null

                /bin/rm -f $HOST_KEY_DIR/$HOST_DSA_KEY
                /bin/rm -f $HOST_KEY_DIR/$HOST_DSA_KEY$PUB_SUFFIX


                /bin/rm -f $MNT_HOST_KEY_DIR/$HOST_DSA_KEY
                /bin/rm -f $MNT_HOST_KEY_DIR/$HOST_DSA_KEY$PUB_SUFFIX

		standbyup=`$HASHOW | $GREP "Remote CP" | $GREP -c "Healthy"`
		singlecp=`$HASHOW | $GREP -c "Not supported"`	
		if [ $standbyup = 1 ]; then
        	        /fabos/cliexec/config save $HOST_KEY_DIR/$HOST_DSA_KEY
                	/fabos/cliexec/config save $HOST_KEY_DIR/$HOST_DSA_KEY$PUB_SUFFIX
		else
			if [ $singlecp = 0 ]; then
				echo "Standby CP not up. Failed to delete DSA keys."
			fi
		fi
		/bin/touch temp;
		/bin/chmod 600 temp;
                /bin/grep -v "$SSHD_HOST_KEY $HOST_KEY_DIR/$HOST_DSA_KEY" $SSHD_CONFIG > temp
                /bin/mv temp $SSHD_CONFIG
                /fabos/cliexec/config save $SSHD_CONFIG

        fi

        if [ -e $HOST_KEY_DIR/$HOST_RSA_KEY ]; then
                size=`/bin/ls -la $HOST_KEY_DIR/$HOST_RSA_KEY | /bin/awk ' { print $5 } '`
                /bin/dd if=/dev/zero of=$HOST_KEY_DIR/$HOST_RSA_KEY bs=1 count=$size 2> /dev/null

                /bin/rm -f $HOST_KEY_DIR/$HOST_RSA_KEY
                /bin/rm -f $HOST_KEY_DIR/$HOST_RSA_KEY$PUB_SUFFIX

        fi

        if [ -e $HOST_KEY_DIR/$HOST_ECDSA_KEY ]; then
                size=`/bin/ls -la $HOST_KEY_DIR/$HOST_ECDSA_KEY | /bin/awk ' { print $5 } '`
                /bin/dd if=/dev/zero of=$HOST_KEY_DIR/$HOST_ECDSA_KEY bs=1 count=$size 2> /dev/null
                /bin/rm -f $HOST_KEY_DIR/$HOST_ECDSA_KEY
                /bin/rm -f $HOST_KEY_DIR/$HOST_ECDSA_KEY$PUB_SUFFIX

        fi


                /usr/bin/ssh-keygen -b 2048 -t rsa -f \
                $HOST_KEY_DIR/$HOST_RSA_KEY -N "" 1>/dev/null 2>/dev/null
                /bin/chmod 600 $HOST_KEY_DIR/$HOST_RSA_KEY
                /bin/chmod 600 $HOST_KEY_DIR/$HOST_RSA_KEY$PUB_SUFFIX

                /fabos/cliexec/config save $HOST_KEY_DIR/$HOST_RSA_KEY
                /fabos/cliexec/config save $HOST_KEY_DIR/$HOST_RSA_KEY$PUB_SUFFIX

                /usr/bin/ssh-keygen -b 256 -t ecdsa -f \
                $HOST_KEY_DIR/$HOST_ECDSA_KEY -N "" 1>/dev/null 2>/dev/null
                /bin/chmod 600 $HOST_KEY_DIR/$HOST_ECDSA_KEY
                /bin/chmod 600 $HOST_KEY_DIR/$HOST_ECDSA_KEY$PUB_SUFFIX

                /fabos/cliexec/config save $HOST_KEY_DIR/$HOST_ECDSA_KEY
                /fabos/cliexec/config save $HOST_KEY_DIR/$HOST_ECDSA_KEY$PUB_SUFFIX

;;

esac

exit 0
