#!/bin/sh
#
#    Copyright (c) 2007-2010 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    File name:   sshutil
#    Module name: fabos/src/security/sshutil.sh
#
#    This script enables ssh public key authentication and manage keys.
#
export PATH=/fabos/sbin:/fabos/bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/cliexec:/fabos/libexec:

# Commands
GREP=/bin/grep
SED=/bin/sed
CAT=/bin/cat
ECHO=/bin/echo
RM=/bin/rm
AWK=/bin/awk
PS=/bin/ps
WC=/usr/bin/wc

KEY_IMPORT=importpubkey
KEY_EXPORT=exportpubkey
PUBKEY_DEL=delpubkeys
PRIVKEY_DEL=delprivkey
KNOWNHOST_DEL=delknownhost
KNOWN_HOST_DIR=/root/.ssh
KNOWN_HOST_FILE=known_hosts
KNOWN_HOST_TEMP=known_hosts_tmp
KEY_GEN=genkey
GENKEY_RSA="-rsa"
GENKEY_DSA="-dsa"
GENKEY_ECDSA="-ecdsa"
ALLOW_USER=allowuser
SHOW_USER=showuser
HELP=help
SHOW_PUB=showpubkeys
IMPORT_PUBKEY_DIR=/fabos/users/admin/.ssh
IMPORT_PUBKEY_FILE=authorized_keys
MNT_IMPORT_PUBKEY_DIR=/mnt/fabos/users/admin/.ssh
SSHD_CONFIG=/etc/sshd_config
EXPORT_PUBKEY_DIR=/root/.ssh
EXPORT_PUBKEY_FILE=
EXPORT_PUBKEY_FILE_DSA=id_dsa.pub
EXPORT_PUBKEY_FILE_RSA=id_rsa.pub
EXPORT_PUBKEY_FILE_ECDSA=id_ecdsa.pub
REMOTE_PUBKEY_FILE_PREFIX=out_going
PRIVKEY_FILE_DSA=id_dsa
PRIVKEY_FILE_RSA=id_rsa
PRIVKEY_FILE_ECDSA=id_ecdsa
PRIVKEY_TYPE=
PRIVKEY_FILE=
PRIVKEY_DIR=/root/.ssh
PASSWD_FILE=/etc/passwd
PUB_SUFFIX=.pub
INFINITE_LOOP=1
ADMIN_GROUPID=600
SSHD=/usr/sbin/sshd
UPDATE_HOSTKEY=updatehostkey
SSH_KEYGEN=/usr/bin/ssh-keygen
SSH_KEYSCAN=/usr/bin/ssh-keyscan
CHOWN=/bin/chown
CHMOD=/bin/chmod
SSHUTIL=/fabos/cliexec/sshutil
KNOWN_HOST_DIR=/root/.ssh
KNOWN_HOST_FILE=known_hosts
KNOWN_HOST_TEMP=tmp
KEYFILE=keyfile
DEL_USR_PUBKEY=delusrpubkey
UPDATE_ALLOWED_LOGIN=updateallowedlogin
HOST_KEY_DIR=/etc
HOST_DSA_KEY=ssh_host_dsa_key
HOST_RSA_KEY=ssh_host_rsa_key
HOST_ECDSA_KEY=ssh_host_ecdsa_key
LOG_FILE=/var/log/sshutil.log
restCaller=`echo $GEPS_APP_NAME`
if [[ -z $restCaller ]]; then
	curlogin=`echo $SWLOGNAME`
else
	curlogin=`echo $LOGIN_ID`
fi
inputFile=
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}`
DEL_HOST_KEY=delhostkey
GEN_HOST_KEY=genhostkey
SHOW_HOST_KEY=showhostkey
ADD_REKEY_INTERVAL=rekeyinterval
SHOW_REKEY=showrekey
MD5=/usr/bin/md5sum
SHOW_ALL=showall
SHOW_PUBKEY_USER=showpubkeyusers

# Validate the user input parameters. 
validateParam() {
	while [ $INFINITE_LOOP ]
	do
     	echo -n $1
		read paramVal 
		if [ -z "$paramVal" ]; then
			echo "Input must not be NULL"
			if [[ -z $restCaller ]]; then
				continue
			else
				break
			fi
		fi

		return 0
	done
}

# Validate the user's public key file name input. 
validateFile() {
	while [ $INFINITE_LOOP ]
	do
		if [[ -z $restCaller ]]; then
		     	echo -n $1
			read inputFile
		else
			inputFile=$1
		fi
		if [ -z "$inputFile" ]; then
			echo "Input must not be NULL"
			if [[ -z $restCaller ]]; then
				continue
			else
				break
			fi
		fi

		# Validate the length and suffix of public key file name
		cLen=`expr length "$inputFile"`
		if  [ "$cLen" -lt 5 ]; then
			echo "Invalid name: file name must have .pub suffix"
			if [[ -z $restCaller ]]; then
				continue
			else
				break
			fi
		fi

		let dotIndex="$cLen"-3
		fileSuffix=`expr substr "$inputFile" $dotIndex $cLen`
		if [ "$fileSuffix" != "$PUB_SUFFIX" ]; then
			echo "Invalid name: file name must have .pub suffix"
			if [[ -z $restCaller ]]; then
				continue
			else
				break
			fi
		fi

		$ECHO "$inputFile" | $GREP -v "[~\`!@#$%^&*()+=|\\}{\"\':,?;><\[]" | $GREP -v "]" > /dev/null 2>&1
		if [ $? -ne 0 ]; then
			$ECHO "Invalid name: file name must not have unsupported characters."
			if [[ -z $restCaller ]]; then
				continue
			else
				break
			fi
		fi
		
		return 0
	done
}

#Check for FIPS mode
checkFipsMode() {
    	# "config get" for fips mode returns value only if called from
   	# default VF. So, temporarily set FABOS_SWITCHNO to 0 and then
    	# revert it back to its original value after "config get"
    	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
    	FABOS_SWITCHNO=0
    	retVal1=`/fabos/cliexec/config get fips.mode 2`
    	retVal2=`/fabos/cliexec/config get fips.simulate 2`
    	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
	retVal=0

	if [ $retVal1 -eq 1 ]; then
		return $retVal1
	elif [ $retVal2 -eq 1 ];  then
		return $retVal2
	else 
		return $retVal
	fi

}

#Validate that DSA keys are not being imported in FIPS mode.
validateFips() {
	checkFipsMode
	if [ $? -eq 1 ]; then 
		grep -q ssh-dss $1
		if [ $? -eq 0 ]; then
			return 1
		fi

	type=`/usr/bin/ssh-keygen -lf $1 | grep -ci ecdsa`
	
        var=`/usr/bin/ssh-keygen -lf $1 | cut -c 1-4`
	if [ $type -eq 1 ]; then
		if [ $var -lt 2048 ]; then
			return 0 
		fi
	fi
        if [ $var -lt 2048 ]; then
            return 2
        fi
	fi
	return 0
}

# Usage information for sshutil.
usage() {
	echo
	echo "Usage: sshutil"
	echo "sshutil importpubkey:  Imports the public key from user's machine to the switch"
	echo "sshutil exportpubkey:  Exports the public key from switch to user machine"
	checkFipsMode
	if [ $? -eq 1 ]; then
		echo "sshutil genkey [ -rsa | -ecdsa ]:"
		echo "                     Generates rsa/ecdsa key pair in the switch"
	else
		echo "sshutil genkey [ -rsa | -dsa | -ecdsa ]:"
		echo "                     Generates rsa/dsa/ecdsa key pair in the switch"
	fi	
	echo "sshutil delpubkeys:  Deletes all the ssh public keys associated to a user"
	echo "sshutil delprivkey:  Deletes the ssh private key related to out going connection"
   	echo "sshutil delknownhost [-all]:  Deletes the known host name/ip from the .ssh/known_hosts"
	echo "sshutil allowuser <user name>:  Allows the user to generate key pair, "
	echo "                                export public key and delete the private key"
	echo "sshutil showpubkeys:  Shows the user's public keys" 
	echo "sshutil showuser:  Shows the allowed user"
	echo "sshutil delhostkey [ -rsa | -dsa | -ecdsa ]:  Deletes ssh host keys"
	echo "sshutil genhostkey [ -rsa | -dsa | -ecdsa ]:  Generates ssh host keys" 	 	 	 
	echo "sshutil showhostkey:  Shows ssh host keys"
	echo "sshutil rekeyinterval <0 | 900-3600> : Configure the time interval in seconds for rekeying."
	echo "sshutil showrekey : display the configured rekey duration"
    echo "sshutil help:  Shows the usage"
}

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() {

	if [ ! -e $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.$2 ] && [ ! -s $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.$2 ]; then
		if [[ -z $restCaller ]]; then
                	echo "Public Key for $2 does not exist"
		else
                	echo -n "Public Key for $2 does not exist"
		fi
		exit 1
	fi
	# 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

}


# Skipping RBAC check for rest calls
if [[ -z $restCaller ]]; then
	# check for RBAC permission.
	if [ "$1" == "" ]; then
		# "sshutil" w/o any option
		/fabos/libexec/rbac_check `/bin/basename $0`
		# in the following check, as "DEL_USR_PUBKEY" is called from userconfig code
		# the rbac checks will be already done there for this case.
	elif [ "$1" != "$DEL_USR_PUBKEY" ] && [ "$1" != "$UPDATE_ALLOWED_LOGIN" ] ; then
		/fabos/libexec/rbac_check -opt `/bin/basename $0` $1
	fi

	ret=`echo $?`
	# Return value of 2 indicates wrong options were passed.
	if [ $ret -ne 0 -a $ret -ne 2 ]; then
		exit 127
	fi
fi

# convert option to all lower case
cmd_option=`echo $1 | tr "[:upper:]" "[:lower:]"`

case "$cmd_option" in

# Generate a key pair(public, private).
"$KEY_GEN" )
	# Verify whether user is allowed to execute this option.
	if [ "$2" != "snmpdRSA" ] && [ "$curlogin" != "$allowlogin" ]; then
		echo "Permission denied to perform this operation."
		exit 1
	fi

	# This is for Pharos requirement to execute the script from snmpd with 
	# non-interactive mode

	if [ $# -eq "2" ] && [ "$2" == "snmpdRSA" ]; then 
		if [ -f $PRIVKEY_DIR/$PRIVKEY_FILE_RSA ] || [ -f $PRIVKEY_DIR/$PRIVKEY_FILE_DSA ] || [ -f $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA ]; then
			exit 1
		fi
		PRIVKEY_TYPE=rsa
		PRIVKEY_FILE=$PRIVKEY_FILE_RSA
		ssh-keygen -N '' -P '' -qt $PRIVKEY_TYPE -f $PRIVKEY_DIR/$PRIVKEY_FILE
		exit 1
	fi	

	# Verify  the no of input arguments before processing
	if [[ -z $restCaller ]]; then
        	if [ $# -ne 2 ]; then
        		usage
			exit 1
		fi
	fi
	
	option=$2
	key_exists=0
		
	if [ "$option" == "$GENKEY_RSA" ]
	then
		PRIVKEY_TYPE=rsa
		PRIVKEY_FILE=$PRIVKEY_FILE_RSA
		EXPORT_PUBKEY_FILE=$EXPORT_PUBKEY_FILE_RSA
		if [ -f $PRIVKEY_DIR/$PRIVKEY_FILE_RSA ]; then
			key_exists=1
		fi
		
	elif [ "$option" == "$GENKEY_ECDSA" ]
	then
		PRIVKEY_TYPE=ecdsa
		PRIVKEY_FILE=$PRIVKEY_FILE_ECDSA
		EXPORT_PUBKEY_FILE=$EXPORT_PUBKEY_FILE_ECDSA
		if [ -f $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA ]; then
			key_exists=1
		fi

	elif [ "$option" == "$GENKEY_DSA" ]
	then
		checkFipsMode
		if [ $? -eq 1 ]; then
			usage
			exit 1
		else
			PRIVKEY_TYPE=dsa
			PRIVKEY_FILE=$PRIVKEY_FILE_DSA
			EXPORT_PUBKEY_FILE=$EXPORT_PUBKEY_FILE_DSA
			if [ -f $PRIVKEY_DIR/$PRIVKEY_FILE_DSA ]; then
				key_exists=1
			fi
		fi
		
	else
		usage
		exit 1
			
	fi

	input=yes	
	if [ $key_exists -eq 1 ]; then
		if [[ -z $restCaller ]]; then
			echo  "A private key file of this algorithm type already exists and will be overwritten."
			echo -n	"Do you want to proceed(yes, y, no, n)[no]?"
			read input

			input=`echo $input | tr "[:upper:]" "[:lower:]"`
			if [ -z "$input" ]; then
				input="no"
			elif [ "$input" != "yes" ] && [ "$input" != "no" ] \
				&& [ "$input" != "y" ] && [ "$input" != "n" ]; then
				echo "input should be either yes or no"
				exit 1
			fi
		else
			input=yes
			# Always yes for rest calls
		fi

		if [ "$input" == "yes" ] || [ "$input" == "y" ]; then
			if [ "$option" == "$GENKEY_RSA" ]; then
				if [ -f $PRIVKEY_DIR/$PRIVKEY_FILE_RSA ]; then
					rm $PRIVKEY_DIR/$PRIVKEY_FILE_RSA
					rm $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_RSA
					/fabos/cliexec/config save $PRIVKEY_DIR/$PRIVKEY_FILE_RSA
					/fabos/cliexec/config save $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_RSA
				fi;
			elif [ "$option" == "$GENKEY_DSA" ]; then	
				if [ -f $PRIVKEY_DIR/$PRIVKEY_FILE_DSA ]; then
					rm $PRIVKEY_DIR/$PRIVKEY_FILE_DSA
					rm $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_DSA
					/fabos/cliexec/config save $PRIVKEY_DIR/$PRIVKEY_FILE_DSA
					/fabos/cliexec/config save $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_DSA
				fi;
			elif [ "$option" == "$GENKEY_ECDSA" ]; then	
				if [ -f $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA ]; then
					rm $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA
					rm $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_ECDSA
					/fabos/cliexec/config save $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA
					/fabos/cliexec/config save $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_ECDSA
				fi;
			fi;	
		fi;
	fi;

	# Generate the key pair for user
	if [ "$input" == "yes" ] || [ "$input" == "y" ]; then 
		if [[ -z $restCaller ]]; then
			ssh-keygen -qt $PRIVKEY_TYPE -f $PRIVKEY_DIR/$PRIVKEY_FILE
		else
			if [[ -z $3 ]] ; then
				ssh-keygen -qt $PRIVKEY_TYPE -f $PRIVKEY_DIR/$PRIVKEY_FILE
			else
				echo -e 'y' | ssh-keygen -qt $PRIVKEY_TYPE -f $PRIVKEY_DIR/$PRIVKEY_FILE -N $3
			fi
		fi
		if [ $? != 0 ]; then
			echo "Failed to generate key pair."
		else
			/fabos/cliexec/config save $PRIVKEY_DIR/$PRIVKEY_FILE
			/fabos/cliexec/config save $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE
			sshutil_notify genkey
			echo "Key pair generated successfully."
		fi
	else
		echo "Operation Cancelled."
	fi
;;

# Import public key to switch.
"$KEY_IMPORT" )
        # Verify whether user is allowed to execute this option.
        # Permission will be handled through RBAC so commenting the code
        # if [ $curlogin != $allowlogin ]; then
        #       echo "Permission denied to perform this operation."
        #       exit 1
        # fi

	if [[ -z $restCaller ]]; then
		# Verify  the no of input arguments before processing
		if [ $# -ne 1 ]; then
			usage
			exit 1
		fi
	else
		# Arguments are importpubkey, user name for whom key is imported, IP,
		# remote dir, pub key name(.pub), login, password
		if [ $# -ne 7 ]; then
			usage
			exit 1
		fi
	fi

	if [[ -z $restCaller ]]; then
	# Ask the user's input to import his public key. 
        validateParam "Enter user name for whom key is imported:"
        swUser=$paramVal
		if [ $swUser == "root" ]; then
			echo "This operation is not supported for "root" user"
			exit 1
		fi
		validateParam "Enter IP address:"
		ipAddr=$paramVal
		validateParam "Enter remote directory:"
		remoteDir=$paramVal
		$ECHO "$remoteDir" | $GREP -v "[\`!@#$%^&*()+=|\\}{\"\':,?;>< \[]" | $GREP -v "]" > /dev/null 2>&1
		if [ $? -ne 0 ]; then
			$ECHO "Invalid remote directory: directory name must not have unsupported characters."
			exit 1
		fi
		validateFile "Enter public key name(must have ".pub" suffix):"
		validateParam "Enter login name:"
		userName=$paramVal
		$ECHO "$userName" | $GREP -v "[~\`!#$%^&*()+=|}{\"\':?;,>< \[]" | $GREP -v "]" > /dev/null 2>&1
		if [ $? -ne 0 ]; then
			$ECHO "Invalid username: username must not have unsupported characters."
			exit 1
		fi
	else
		swUser=$2
		ipAddr=$3
		remoteDir=$4
		validateFile $5
		userName=$6
		userPass=$7
	fi

        # Verify whether the user name exists or not
        opt=`echo $swUser | tr "[:upper:]" "[:lower:]"`
        cat $PASSWD_FILE|grep -qi "^$opt:"
        if [ $? -ne 0 ]; then
                echo "Named user does not exist"
		if [[ -z $restCaller ]]; then
                	exit 1;
		else
			exit 2;
		fi
        fi

	if [[ -z $restCaller ]]; then
		# Perform import and append it.
		/usr/bin/scp -q -oStrictHostKeyChecking=no  \
		$userName@\[$ipAddr\]:$remoteDir/$inputFile $IMPORT_PUBKEY_DIR 2> /dev/null
	else
		/usr/bin/scp -q -oStrictHostKeyChecking=no -oSSHPassword=$userPass \
		$userName@\[$ipAddr\]:$remoteDir/$inputFile $IMPORT_PUBKEY_DIR 2> /dev/null

	fi
	if [ $? != 0 ]; then
		echo "Failed to import public key."
		exit 3;
	else	
                cd  $IMPORT_PUBKEY_DIR
		validateFips "$inputFile"
		retFips=$?
		if [ $retFips -eq 1 ]; then
			echo "DSA keys are not allowed in FIPS mode."
			cat /dev/null > $inputFile
			rm $inputFile
			if [[ -z $restCaller ]]; then
				exit 1;
			else
				exit 4;
			fi
		elif [ $retFips -eq 2 ]; then
			echo "Key size not allowed in FIPS MODE."
			cat /dev/null > $inputFile
			rm $inputFile
			if [[ -z $restCaller ]]; then
				exit 1;
			else
				exit 5;
			fi
		fi
		cat $inputFile >> $IMPORT_PUBKEY_FILE.$swUser
		$CHOWN $swUser $IMPORT_PUBKEY_FILE.$swUser
		# copy this file to secondary partition of active

		cp -f $IMPORT_PUBKEY_FILE.$swUser $MNT_IMPORT_PUBKEY_DIR/
		if [ "$swUser" == "$allowlogin" ]
		then
			cat $inputFile >> $IMPORT_PUBKEY_FILE
			$CHOWN $swUser $IMPORT_PUBKEY_FILE
			config save $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE
		fi
		cat /dev/null > $inputFile
		rm $inputFile
                tar -cf authorizedKeys.tar $IMPORT_PUBKEY_FILE.*
                cd -
		config save $IMPORT_PUBKEY_DIR/authorizedKeys.tar
		sshutil_notify importpubkey $ipAddr
		echo "public key is imported successfully."
	fi
;;

# Export public key to host.
"$KEY_EXPORT" )
	# Verify whether user is allowed to execute this option.
	if [ "$curlogin" != "$allowlogin" ]
	then
		echo "Permission denied to perform this operation."
		if [[ -z $restCaller ]]; then
			exit 1
		else
			exit 2
		fi
	fi
	
	if [[ -z $restCaller ]]; then
		# Verify  the no of input arguments before processing
		if [ $# -ne 1 ]; then
			usage
			exit 1
		fi
		# Get the inputs from the user to export public key. 
		validateParam "Enter IP address:"
		ipAddr=$paramVal
		validateParam "Enter remote directory:"
		remoteDir=$paramVal
		#validateFile "Enter public key name(must have ".pub" suffix):"
		$ECHO "$remoteDir" | $GREP -v "[\`!@#$%^&*()+=|\\}{\"\':,?;><\[]" | $GREP -v "]" > /dev/null 2>&1
		if [ $? -ne 0 ]; then
			$ECHO "Invalid remote directory: directory name must not have unsupported characters."
			exit 1
		fi
		validateParam "Enter login name:"
		userName=$paramVal
		$ECHO "$userName" | $GREP -v "[~\`!#$%^&*()+=|}{\"\':?;,><\[]" | $GREP -v "]" > /dev/null 2>&1
		if [ $? -ne 0 ]; then
			$ECHO "Invalid username: username must not have unsupported characters."
			exit 1
		fi
	else
		if [ $# -ne 6 ]; then
			usage
			exit 1
		fi
		if [ "$2" == "$GENKEY_RSA" ]; then
			if [ -f $EXPORT_PUBKEY_DIR/$EXPORT_PUBKEY_FILE_RSA ]; then
				EXPORT_PUBKEY_FILE=$EXPORT_PUBKEY_FILE_RSA
			fi
		elif [ "$2" == "$GENKEY_DSA" ]; then
			if  [ -f $EXPORT_PUBKEY_DIR/$EXPORT_PUBKEY_FILE_DSA ]; then
				EXPORT_PUBKEY_FILE=$EXPORT_PUBKEY_FILE_DSA	
			fi
		elif [ "$2" == "$GENKEY_ECDSA" ]; then
			if  [ -f $EXPORT_PUBKEY_DIR/$EXPORT_PUBKEY_FILE_ECDSA ]; then
				EXPORT_PUBKEY_FILE=$EXPORT_PUBKEY_FILE_ECDSA	
			fi
		else
			echo "Invalid algorithm type."
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit 3
			fi
		fi
		if [[ -z $EXPORT_PUBKEY_FILE ]]; then
			echo "Public key doesn't exist."
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit 4
			fi
		fi
		ipAddr=$3
		remoteDir=$4
		userName=$5
		userPass=$6
	fi

	# Export the public key to the users machine. Exported file 
	# will have name out_going_<chassisname>.pub

	# check for RBAC permission.
	/fabos/libexec/rbac_check chassisname > /dev/null 2>&1
	ret=`echo $?`
	# Return value of 2 indicates wrong options were passed.
	if [ $ret -ne 0 ]; then
		chassisName=""
	else
		chassisName=_`chassisname`
	fi

	if [[ -z $restCaller ]]; then
		if [ -f $EXPORT_PUBKEY_DIR/$EXPORT_PUBKEY_FILE_RSA ]; then
			EXPORT_PUBKEY_FILE=$EXPORT_PUBKEY_FILE_RSA
		elif  [ -f $EXPORT_PUBKEY_DIR/$EXPORT_PUBKEY_FILE_DSA ]; then
			EXPORT_PUBKEY_FILE=$EXPORT_PUBKEY_FILE_DSA	
		elif  [ -f $EXPORT_PUBKEY_DIR/$EXPORT_PUBKEY_FILE_ECDSA ]; then
			EXPORT_PUBKEY_FILE=$EXPORT_PUBKEY_FILE_ECDSA	
		else
			echo "Public key doesn't exist."
			if [[ -z $EXPORT_PUBKEY_FILE ]]; then
				exit 1
			else
				exit 4
			fi
		fi

		/usr/bin/scp -q -oStrictHostKeyChecking=no  \
		$EXPORT_PUBKEY_DIR/$EXPORT_PUBKEY_FILE  \
		$userName@\[$ipAddr\]:$remoteDir/$REMOTE_PUBKEY_FILE_PREFIX$chassisName.pub  2> /dev/null
	else
		/usr/bin/scp -q -oStrictHostKeyChecking=no -oSSHPassword=$userPass \
		$EXPORT_PUBKEY_DIR/$EXPORT_PUBKEY_FILE  \
		$userName@\[$ipAddr\]:$remoteDir/$REMOTE_PUBKEY_FILE_PREFIX$chassisName.pub  2> /dev/null
	fi
	rc=$?
	if [ $rc != 0 ]; then
		echo "Failed to export public key."$rc
		exit 1
	else
		sshutil_notify exportpubkey out_going.pub $ipAddr
		echo "public key $REMOTE_PUBKEY_FILE_PREFIX$chassisName.pub is exported successfully."
	fi
;;

# Deleting all the public keys.
"$PUBKEY_DEL" )
	# Verify whether user is allowed to execute this option.
	# if [ "$curlogin" != "$allowlogin" ]; then
	#	echo "Permission denied to perform this operation."
	#	exit 1
	# fi

	if [[ -z $restCaller ]]; then
		# Verify  the no of input arguments before processing
		if [ $# -ne 1 ]
		then
			usage
			exit 1
		fi
 	       # Ask the user name whose public key needs to be deleted.
        	validateParam "Enter user name for whom ssh public key is to be deleted or \"all\" for all users:"
	        swUser=$paramVal

		# Make sure whether user is ready to delete.
		echo -n "WARNING: It deletes all the ssh public keys for user."\
		"Do you want to proceed(yes, y, no, n)[no]?"
		read input;
		input=`echo $input | tr "[:upper:]" "[:lower:]"`
		if [ -z "$input" ]; then
			input="no"
		elif [ "$input" != "yes" ] && [ "$input" != "no" ] \
			&& [ "$input" != "y" ] && [ "$input" != "n" ]; then
			echo "input should be either yes or no"
			exit 1
		fi
	else
		# Arguments are delpubkeys and user name/all
		if [ $# -ne 2 ]
		then
			usage
			exit 1
		fi
		swUser=$2
		input="yes"
	fi

if [ $input == "no" ] || [ $input == "n" ]; then
                echo "Operation Cancelled."
        else
		# Before removing the files, nullify the contents of the file.
		# This is needed for FIPS compliance.

                # Verify whether the user name exists or not
                opt=`echo $swUser | tr "[:upper:]" "[:lower:]"`
                # delete for all the users
                if [ $opt == "all" ]; then
			cd $IMPORT_PUBKEY_DIR
                        for authfile in `ls $IMPORT_PUBKEY_FILE.* 2> /dev/null` ; do
                                cat /dev/null > $authfile
                                rm -f $authfile
                        done
			cd -
			cd $MNT_IMPORT_PUBKEY_DIR
			# handle this for secondary partition of active
                        for authfile in `ls $IMPORT_PUBKEY_FILE.* 2> /dev/null` ; do
                                cat /dev/null > $authfile
                                rm -f $authfile
			done
			cd -

			if [ -f $IMPORT_PUBKEY_DIR/authorizedKeys.tar ]; then
                        	cat /dev/null > $IMPORT_PUBKEY_DIR/authorizedKeys.tar
				config save $IMPORT_PUBKEY_DIR/authorizedKeys.tar
			fi
			cat /dev/null > $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE
	                config save $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE
			swUser="all users"
                else
			cat $PASSWD_FILE|grep -qi "^$opt:"
			if [ $? -ne 0 ]; then
				echo "Named user does not exist"
				exit 1;
			fi
			delUsrPubKeyFile PUBKEY_DEL $swUser
                fi
                sshutil_notify delpubkeys $swUser
                echo "ssh public keys associated to $swUser are deleted."
        fi
;;

# Deleting the private key.
"$PRIVKEY_DEL" )
	if [[ ! -z $restCaller ]]; then
		if [ "$2" != "$GENKEY_RSA" ] && [ "$2" != "$GENKEY_DSA" ] && \
				[ "$2" != "$GENKEY_ECDSA" ] && [ "$2" != "fips" ]; then
			echo "Invalid algorithm type."
			exit 1
		fi
	fi
	skip_user_check=0
	if [ $# -gt 1 ]; then
		if [ $2 == "fips" ]; then
			skip_user_check=1
		fi
	fi
	if [ $skip_user_check -ne 1 ]; then
		# Verify whether user is allowed to execute this option.
		if [ "$curlogin" != "$allowlogin" ]; then
			echo "Permission denied to perform this operation."
			exit 1
		fi
	fi

	# Verify  the no of input arguments before processing
	if [[ -z $restCaller ]]; then
		if [ $# -ne 1 ] && [ $skip_user_check -ne 1 ]
		then
			usage
			exit 1
		fi
	else
		deleted=0
		if [ $# -ne 2 ] 
		then
			echo "Invalid Command."
			exit 1
		fi
	fi

	# Delete the private key if it exists.
	if [ -e $PRIVKEY_DIR/$PRIVKEY_FILE_RSA ] || [ -e $PRIVKEY_DIR/$PRIVKEY_FILE_DSA ] || [ -e $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA ]; then
		# Starting from Dagobah release, RSA/DSA/ECDSA keys are generated. 
		if [ -e $PRIVKEY_DIR/$PRIVKEY_FILE_RSA ]; then
			if [[ -z $restCaller ]] || [[ ! -z $restCaller && "$2" == "$GENKEY_RSA" ]]; then
				size=`/bin/ls -la $PRIVKEY_DIR/$PRIVKEY_FILE_RSA | $AWK ' { print $5 } '`
				/bin/dd if=/dev/zero of=$PRIVKEY_DIR/$PRIVKEY_FILE_RSA bs=1 count=$size 2> /dev/null
				rm $PRIVKEY_DIR/$PRIVKEY_FILE_RSA
				rm $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_RSA
				/fabos/cliexec/config save $PRIVKEY_DIR/$PRIVKEY_FILE_RSA
				/fabos/cliexec/config save $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_RSA
				deleted=1
			fi
		fi
		if [ -e $PRIVKEY_DIR/$PRIVKEY_FILE_DSA ]; then
			if [[ -z $restCaller ]] || [[ ! -z $restCaller && "$2" == "$GENKEY_DSA" ]]; then
				size=`/bin/ls -la $PRIVKEY_DIR/$PRIVKEY_FILE_DSA | $AWK ' { print $5 } '`
				/bin/dd if=/dev/zero of=$PRIVKEY_DIR/$PRIVKEY_FILE_DSA bs=1 count=$size 2> /dev/null
				rm $PRIVKEY_DIR/$PRIVKEY_FILE_DSA
				rm $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_DSA
				/fabos/cliexec/config save $PRIVKEY_DIR/$PRIVKEY_FILE_DSA
				/fabos/cliexec/config save $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_DSA
				deleted=1
			fi
		fi
		if [ -e $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA ]; then
			if [[ -z $restCaller ]] || [[ ! -z $restCaller && "$2" == "$GENKEY_ECDSA" ]]; then
				size=`/bin/ls -la $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA | $AWK ' { print $5 } '`
				/bin/dd if=/dev/zero of=$PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA bs=1 count=$size 2> /dev/null
				rm $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA
				rm $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_ECDSA
				/fabos/cliexec/config save $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA
				/fabos/cliexec/config save $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_ECDSA
				deleted=1
			fi
		fi
		if [[ ! -z $restCaller && $deleted -eq 0 ]]; then
			echo -n "private key doesn't exist."
			exit 1
		fi
		/fabos/cliexec/config save $PRIVKEY_DIR

		sshutil_notify delprivkey
		echo "private key is deleted successfully."
	else
		if [[ -z $restCaller ]]; then
			echo "private key doesn't exist."
		else
			echo -n "private key doesn't exist."
		fi
	fi
;;


# Deleting the known host name/ip
"$KNOWNHOST_DEL" )

    	# Check for chassis permission.
  	sshutil_notify validateuser $opt > /tmp/chassis_perm
   	chassis_perm=`cat /tmp/chassis_perm|grep "No chassis permission"`
    	if [ "$chassis_perm" ]; then
        	echo "Named user doesn't have chassis permission"
    		rm /tmp/chassis_perm
        	exit 1;
    	fi
    	$RM /tmp/chassis_perm


	#Verify whether user is allowed to execute this option.
	if [ "$curlogin" != "$allowlogin" ]; then
		$ECHO "Permission denied for this user to perform this operation"
		exit 1;
	fi

	if [ $# -gt 2 ]; then
        	usage
        	exit 1
	fi
    
	if [[ ! -z $2 && $2 != "-all" ]]; then
		if [[ ! -z $restCaller ]]; then
			hostname=$2
		else
			usage
			exit 1
		fi
   	fi


	if [ "$2" == "-all" ]; then
		if [[ -z $restCaller ]]; then
			echo "This Command will delete all the known host keys."
			echo -n "Please Confirm with Yes(Y,y), No(N,n) [N]: "
	        	read input

        input=`echo $input | tr "[:upper:]" "[:lower:]"`
        if [ -z "$input" ]; then
            input="no"
        elif [ "$input" != "yes" ] && [ "$input" != "no" ] \
            && [ "$input" != "y" ] && [ "$input" != "n" ]; then
            echo "Input should be either Yes or No"
            exit 1
        fi
		else
			input="yes"
		fi

        if [ "$input" == "yes" ] || [ "$input" == "y" ]; then
	    	if [ -s $KNOWN_HOST_DIR/$KNOWN_HOST_FILE ]; then
				size=`/bin/ls -la $KNOWN_HOST_DIR/$KNOWN_HOST_FILE | $AWK ' { print $5 } '`
        		/bin/dd if=/dev/zero of=$KNOWN_HOST_DIR/$KNOWN_HOST_FILE bs=1 count=$size 2> /dev/null
				rm $KNOWN_HOST_DIR/$KNOWN_HOST_FILE
        		config save $KNOWN_HOST_DIR/$KNOWN_HOST_FILE
	        	sshutil_notify $KNOWNHOST_DEL "All"
    	    	$ECHO "All Known Host(s) deleted Successfully."
        		exit 0;
    	    			/bin/dd if=/dev/zero of=$KNOWN_HOST_DIR/$KNOWN_HOST_FILE bs=1 count=$size 2> /dev/null
				$RM -rf $KNOWN_HOST_DIR/$KNOWN_HOST_FILE
        			config save $KNOWN_HOST_DIR/$KNOWN_HOST_FILE
	 		       	sshutil_notify $KNOWNHOST_DEL "All"
    	 		   	$ECHO "All Known Host(s) deleted successfully."
        			exit 0;
			else
				$ECHO "Known Host(s) does not exist."
				exit 1;
	    	fi
		else
			echo "Operation Cancelled."
			exit 1;
		fi
	else
		if [[ -z $restCaller ]]; then
			validateParam "IP Address/Hostname to be deleted:"
			hostname=$paramVal
		else
			hostname=$2
		fi
	fi

    if [ -e $KNOWN_HOST_DIR/$KNOWN_HOST_FILE ]; then
    	val=`$CAT $KNOWN_HOST_DIR/$KNOWN_HOST_FILE | $GREP $hostname | wc -l`
        if [ $val -eq 0 ]; then
        	$ECHO "Known Host does not exist."
			exit 1;
        fi
    fi

    # Delete the host name key if it exists.
    if [ -e $KNOWN_HOST_DIR/$KNOWN_HOST_FILE ]; then
        $AWK -v hName="$hostname" '$1 !~ hName' $KNOWN_HOST_DIR/$KNOWN_HOST_FILE > "$KNOWN_HOST_DIR/$KNOWN_HOST_TEMP"
        /bin/mv $KNOWN_HOST_DIR/$KNOWN_HOST_TEMP $KNOWN_HOST_DIR/$KNOWN_HOST_FILE
        config save $KNOWN_HOST_DIR/$KNOWN_HOST_FILE
    fi

	if [ -e $KNOWN_HOST_DIR/$KNOWN_HOST_FILE ]; then
		val2=`$CAT $KNOWN_HOST_DIR/$KNOWN_HOST_FILE | $GREP $hostname | wc -l`
		if [ $val2 -ne 0 ]; then 
			$ECHO "Failed to delete Known Host"
		else
			sshutil_notify $KNOWNHOST_DEL "$hostname"
			$ECHO "Known Host deleted successfully."
			exit 0;
		fi		
	fi
;;

#Allow admin
"$ALLOW_USER" )
	# Verify whether user is allowed to execute this option.
	if [ $curlogin != admin ]; then
		echo "Permission denied. Only admin can choose the allowed user."
		exit 1
	fi

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

	# Get the option.
	opt=`echo $2`
	# Finds out whether this user exists or not.
        groupid=`cat $PASSWD_FILE|grep "^$opt:" | \
                cut -d":" -f4`
        if [ -z "$groupid" ]; then
      		echo "Named account does not exist"
		exit 1;
	fi

	# Finds out whether this user is admin or not.
	if [ $groupid -ne $ADMIN_GROUPID ]; then
		echo "Permission denied to perform this operation."
		exit 1;
	fi

	sshutil_notify validateuser $opt > /tmp/chassis_perm
	chassis_perm=`cat /tmp/chassis_perm|grep "No chassis permission"`
	if [ "$chassis_perm" ]; then 
		echo "Named user doesn't have chassis permission"
		rm /tmp/chassis_perm
		exit 1;
	fi
	rm /tmp/chassis_perm
	# Make sure whether user is ready to delete.
	# echo -n "WARNING: It supports only single user at a time."\
	# "So the previous user's public keys will be lost and"\
	# " he cannot authenticate. Do you want to proceed(yes, y, no, n)"\
	# "[no]?"
	# read input;
	# input=`echo $input | tr "[:upper:]" "[:lower:]"`
	# if [ -z "$input" ]; then
	#	input="no"
	#elif [ "$input" != "yes" ] && [ "$input" != "no" ] \
	#	&& [ "$input" != "y" ] && [ "$input" != "n" ]; then
	#	echo "input should be either yes or no"
	#	exit 1
	# fi

	# if [ $input == "no" ] || [ $input == "n" ]; then
	#	echo "Operation Cancelled."
	#	exit 1
	# fi

	# Change the AllowedLogin.
	if [ "$allowlogin" == "$opt" ]; then
		echo "Named allowed user already exists"
		exit 1 
	fi

	# Need to delete the existing authorized_keys file.
	cat /dev/null > $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE
	if [ -f $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.$opt ]; then
		cp $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.$opt $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE
	fi
	config save $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE

	# update user in sshd_config
	sshdAllowUserUpdate $opt

	sshutil_notify allowuser $opt
	echo "Allowed user has been successfully changed to: $opt."
;;

"$SHOW_PUB" )
	# Verify whether user is allowed to execute this option.
	# if [ "$curlogin" != "$allowlogin" ]; then
	#	echo "Permission denied to perform this operation."
	#	exit 1
	# fi

	if [[ -z $restCaller ]]; then
		# Verify  the no of input arguments before processing
		if [ $# -ne 1 ]
		then
			usage
			exit 1
		fi

	        # Ask the user name whose public key needs to be deleted.
        	validateParam "Enter user name whose ssh public key is to be displayed:"
	        swUser=$paramVal
	else
		if [ $# -ne 2 ]
		then
			usage
			exit 1
		fi
		swUser=$2
	fi

        # Verify whether the user name exists or not
        opt=`echo $swUser | tr "[:upper:]" "[:lower:]"`

	cat $PASSWD_FILE|grep -qi "^$opt:"
	if [ $? -ne 0 ]; then
		echo "Named user does not exist"
		exit 1;
	fi

	if [ -f $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.$swUser ]; then
		if [[ -z $restCaller ]]; then
			echo "user's public keys"
		fi
		cat $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.$swUser
	fi
;;

"$SHOW_USER" )
	# Verify whether user is allowed to execute this option.
	if [ $curlogin != admin ]; then
		echo "Permission denied to perform this operation."
		exit 1
	fi

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

	allowlogin=`cat $SSHD_CONFIG|grep -i "AllowedLogin" | \
        grep -v "#" | cut -d" " -f2`
	echo $allowlogin
;;

"$UPDATE_ALLOWED_LOGIN" )
sshdAllowUserUpdate admin
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

;;

"$UPDATE_HOSTKEY" )

if [ $# -ne 3 ]; then
 exit 0
fi

KNOWN_HOST_IP=$2
INPUT_FINGERPRINT=$3

DATE=`date` 2> /dev/null
echo "######################################" >> $LOG_FILE
echo "Date:  $DATE" >> $LOG_FILE

echo "IP Address:       $KNOWN_HOST_IP" >> $LOG_FILE
echo "MD5 Fingerprint:  $INPUT_FINGERPRINT" >> $LOG_FILE

$SSH_KEYSCAN -t rsa,dsa,rsa1 $KNOWN_HOST_IP 2> /dev/null |
while read RSA_KEY    
do
    echo $RSA_KEY > $KEYFILE   
    SCANNED_HOST_FINGERPRINT=`$SSH_KEYGEN -lf $KEYFILE | cut -d " " -f 2`

	#For Debugging 

    echo "RSA_KEY  = $RSA_KEY" >> $LOG_FILE
	echo "HOST_FINGERPRINT    =  $SCANNED_HOST_FINGERPRINT" >> $LOG_FILE

    if [ $SCANNED_HOST_FINGERPRINT == $INPUT_FINGERPRINT ]; then

        # Update the host name key if it exists.
        if [ -e $KNOWN_HOST_DIR/$KNOWN_HOST_FILE ]; then
            $AWK -v hName="$KNOWN_HOST_IP" '$1 !~ hName' $KNOWN_HOST_DIR/$KNOWN_HOST_FILE > "$KNOWN_HOST_DIR/$KNOWN_HOST_TEMP"
            /bin/mv $KNOWN_HOST_DIR/$KNOWN_HOST_TEMP $KNOWN_HOST_DIR/$KNOWN_HOST_FILE
            echo $RSA_KEY >> $KNOWN_HOST_DIR/$KNOWN_HOST_FILE
            config save $KNOWN_HOST_DIR/$KNOWN_HOST_FILE
			echo "Updated the known_Hosts file" >> $LOG_FILE
        fi

        # Remove the temporary key  file
        if [ -f $KNOWN_HOST_DIR/$KEYFILE ]; then
            rm $KNOWN_HOST_DIR/$KEYFILE  2> /dev/null
        fi
		exit 127
    fi
done

#end  of hostkey update
;;

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

		keyexist=0
        option=$2
		totalhostkeys=`$SSHUTIL $SHOW_HOST_KEY | wc -l`

        if [ "$option" == "$GENKEY_DSA" ]
        then
		if [ -e $HOST_KEY_DIR/$HOST_DSA_KEY ]; then
            if [ $totalhostkeys -eq 1 -a "x$genhostkey_cmd_option_flag" != "x1" ]; then
                echo "Warning: Deleting the last host key. Kindly ensure that a new key is generated within the same session"
            fi

			size=`/bin/ls -la $HOST_KEY_DIR/$HOST_DSA_KEY | $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

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

			keyexist=1

       	fi
        elif [ "$option" == "$GENKEY_RSA" ]
        then
		if [ -e $HOST_KEY_DIR/$HOST_RSA_KEY ]; then
            if [ $totalhostkeys -eq 1 -a "x$genhostkey_cmd_option_flag" != "x1" ]; then
                echo "Warning: Deleting the last host key. Kindly ensure that a new key is generated within the same session"
            fi

			size=`/bin/ls -la $HOST_KEY_DIR/$HOST_RSA_KEY | $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

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

			keyexist=1

		fi
        elif [ "$option" == "$GENKEY_ECDSA" ]
        then
		if [ -e $HOST_KEY_DIR/$HOST_ECDSA_KEY ]; then
            if [ $totalhostkeys -eq 1 -a "x$genhostkey_cmd_option_flag" != "x1" ]; then
                echo "Warning: Deleting the last host key. Kindly ensure that a new key is generated within the same session"
            fi

			size=`/bin/ls -la $HOST_KEY_DIR/$HOST_ECDSA_KEY | $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

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

			keyexist=1

		fi
        else
		if [[ -z $restCaller ]]; then
       			usage
		else
			echo "Invalid algorithm type."
		fi
                exit 1
        fi
		
		if [ $keyexist -eq 1 ]; then
			sshutil_notify $DEL_HOST_KEY $option
		fi
;;
"$GEN_HOST_KEY" )
        # Verify  the no of input arguments before processing
        if [ $# -ne 2 ]; then
            usage
            exit 1
        fi
        option=$2
		input="yes"
		hostkeyfile="none"
		hostkey="none"
		keylen=2048

		if [ "$option" == "$GENKEY_RSA" ]; then
			hostkeyfile=$HOST_RSA_KEY
			hostkey="rsa"
		elif [ "$option" == "$GENKEY_DSA" ]; then
			hostkeyfile=$HOST_DSA_KEY
			hostkey="dsa"
			keylen=1024
		elif [ "$option" == "$GENKEY_ECDSA" ]; then
			hostkey="ecdsa"
			hostkeyfile=$HOST_ECDSA_KEY
			keylen=521
        else
            usage
            exit 1
        fi
        if [ -s $HOST_KEY_DIR/$hostkeyfile ]; then
		if [[ -z $restCaller ]]; then
	            echo "$hostkey host key already exists."
        	    echo -n "Do you want to proceed(yes, y, no, n)[no]?"
	            read input

        	    input=`echo $input | tr "[:upper:]" "[:lower:]"`
	            if [ -z "$input" ]; then
        	        exit 1
	            elif [ "$input" != "yes" ] && [ "$input" != "no" ] \
        	        && [ "$input" != "y" ] && [ "$input" != "n" ]; then
                	echo "input should be either yes or no"
	                exit 1
        	    fi
		else
			input="yes"
		fi

            if [ "$input" == "yes" ] || [ "$input" == "y" ]; then
		export genhostkey_cmd_option_flag=1
                $SSHUTIL $DEL_HOST_KEY $2
		unset genhostkey_cmd_option_flag
            fi
        elif [ -e $HOST_KEY_DIR/$hostkeyfile ]; then
            $SSHUTIL $DEL_HOST_KEY $2
        fi

        if [ "$input" == "yes" ] || [ "$input" == "y" ]; then
            /usr/bin/ssh-keygen -b $keylen -t $hostkey -f \
            $HOST_KEY_DIR/$hostkeyfile -N "" 1>/dev/null 2>/dev/null
            config save $HOST_KEY_DIR/$hostkeyfile
            config save $HOST_KEY_DIR/$hostkeyfile$PUB_SUFFIX
			sshutil_notify $GEN_HOST_KEY $option
			if [[ ! -z $restCaller ]]; then
				$ECHO "Host key generated successfully"
			fi
        fi

;;

"$SHOW_HOST_KEY" )
if [[ -z $restCaller ]]; then
        # Verify  the no of input arguments before processing
        if [ $# -ne 1 ]
        then
                usage
                exit 1
        fi

		if [ -e $HOST_KEY_DIR/$HOST_RSA_KEY ]; then
			$SSH_KEYGEN -lf $HOST_KEY_DIR/$HOST_RSA_KEY$PUB_SUFFIX | cut -d " " -f 1,2,5
		fi
		if [ -e $HOST_KEY_DIR/$HOST_ECDSA_KEY ]; then
			$SSH_KEYGEN -lf $HOST_KEY_DIR/$HOST_ECDSA_KEY$PUB_SUFFIX | cut -d " " -f 1,2,5
		fi
		if [ -e $HOST_KEY_DIR/$HOST_DSA_KEY ]; then
			$SSH_KEYGEN -lf $HOST_KEY_DIR/$HOST_DSA_KEY$PUB_SUFFIX | cut -d " " -f 1,2,5
		fi
else
        # Verify  the no of input arguments before processing
        if [ $# -ne 2 ]
        then
                usage
                exit 1
        fi
	if [ "$2" == "$GENKEY_RSA" ]; then
		if [ -e $HOST_KEY_DIR/$HOST_RSA_KEY ]; then
			$SSH_KEYGEN -lf $HOST_KEY_DIR/$HOST_RSA_KEY$PUB_SUFFIX | cut -d " " -f 1,2,5
		fi
	elif [ "$2" == "$GENKEY_ECDSA" ]; then
		if [ -e $HOST_KEY_DIR/$HOST_ECDSA_KEY ]; then
			$SSH_KEYGEN -lf $HOST_KEY_DIR/$HOST_ECDSA_KEY$PUB_SUFFIX | cut -d " " -f 1,2,5
		fi
	elif [ "$2" == "$GENKEY_DSA" ]; then
		if [ -e $HOST_KEY_DIR/$HOST_DSA_KEY ]; then
			$SSH_KEYGEN -lf $HOST_KEY_DIR/$HOST_DSA_KEY$PUB_SUFFIX | cut -d " " -f 1,2,5
		fi
	fi
fi
;;
"$ADD_REKEY_INTERVAL")
        # Verify  the no of input arguments before processing
        if [ $# -ne 2 ]
        then
                usage
                exit 1
        fi
	timeoption=$2
	# validate the option as integer
	if [ $timeoption -ne 0 -o $timeoption -eq 0 2>/dev/null ]; then


		if [ "$timeoption" == "0" -o "$timeoption" -ge "900" -a "$timeoption" -le "3600" ] ; then
		# check if configured time is equal to the input time to be configured
			rekeyintval=`$CAT /etc/sshd_config  | $GREP "#RekeyInterval"`
			if [ "$rekeyintval" != '' ]; then
				rekeyintval=0
			else 
				rekeyintval=`$CAT /etc/sshd_config  | $GREP "RekeyInterval" | $AWK '{print $2}'`
				if [ "$rekeyintval" == '' ]; then
					rekeyintval=0
				fi
			fi
			if [ $timeoption -eq $rekeyintval ]; then
				if [ $timeoption -eq "0" ]; then
					$ECHO "Rekey Time Interval is already disabled."
				else 
					$ECHO "Rekey Time Interval is same as the input."
				fi
				exit 1
			fi
			if [[ -z $restCaller ]]; then
				$ECHO "SSH daemon will be restarted and all SSH session will be terminated"
				$ECHO -n "Do you want to proceed(yes, y, no, n)[no]?"
				read input
				input=`$ECHO $input | /usr/bin/tr "[:upper:]" "[:lower:]"`
				if [ -z "$input" ]; then
					input="no"
				elif [ "$input" != "yes" ] && [ "$input" != "no" ] \
					&& [ "$input" != "y" ] && [ "$input" != "n" ]; then
					$ECHO "input should be either yes or no"
					exit 1
				fi
			else
				input="yes"
			fi		
		
            		if [ "$input" == "yes" ] || [ "$input" == "y" ]; then
				/fabos/sbin/sshdconfigupdate RekeyInterval $timeoption > /dev/null
				$ECHO	"Rekey Time Interval Configured to $timeoption seconds."
					#Restart sshd
					/fabos/rbin/cipherutil restartssh > /dev/null 2>&1
					if [[ $? -ne 0 ]];then
						$ECHO "Failed to restart ssh daemon"
						exit 1
					fi
					#Terminate all exisiting ssh connection
					/fabos/libexec/usrlogout -ssh > /dev/null 2>&1
					if [[ $? -ne 0 ]];then
						$ECHO "Failed to terminate ssh sessions"
						exit 1
					fi
			else
				$ECHO "Not Configured"
				exit 1
			fi
		else
			if [[ -z $restCaller ]]; then
				usage
			else
				$ECHO "Invalid Rekey Time Interval input."
			fi
			exit 1
		fi
	else
		usage
		exit 1
	fi
	
	

;;

"$SHOW_REKEY")
        # Verify  the no of input arguments before processing
        if [ $# -ne 1 ]
        then
                usage
                exit 1
        fi
rekeyintval=`$CAT /etc/sshd_config  | $GREP "#RekeyInterval"`
if [ "$rekeyintval" != '' ]; then
	$ECHO "Rekeying is not configured"
else 
	rekeyintval=`$CAT /etc/sshd_config  | $GREP "RekeyInterval" | $AWK '{print $2}'`
	if [ "$rekeyintval" != '' ]; then
		$ECHO	"Configured Interval : $rekeyintval seconds."
	else
		$ECHO "Rekeying is not configured."
	fi
fi

;;

"$SHOW_ALL")
	if [[ -z $restCaller ]]; then
		usage
		exit 1
	fi
	# Verify  the no of input arguments before processing
	if [ $# -ne 1 ]
	then
		usage
		exit 1
	fi
	rekeyintval=`$CAT /etc/sshd_config  | $GREP "#RekeyInterval"`
	if [ "$rekeyintval" != '' ]; then
		$ECHO "Rekeying is not configured"
	else 
		rekeyintval=`$CAT /etc/sshd_config  | $GREP "RekeyInterval" | $AWK '{print $2}'`
		if [ "$rekeyintval" != '' ]; then
			$ECHO	"Configured Interval : $rekeyintval seconds."
		else
			$ECHO "Rekeying is not configured."
		fi
	fi

	# Verify whether user is allowed to execute this option.
	if [ $curlogin != admin ]; then
		echo "Permission denied to get allowed user."
		exit 1
	fi

	allowlogin=`cat $SSHD_CONFIG|grep -i "AllowedLogin" | \
        grep -v "#" | cut -d" " -f2`
	echo -n $allowlogin
;;

"$SHOW_PUBKEY_USER")
	if [[ -z $restCaller ]]; then
		usage
		exit 1
	fi
	# Verify  the no of input arguments before processing
	if [ $# -ne 1 ]
	then
		usage
		exit 1
	fi

	count=0
	for line in $(ls $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.*); do
		if [[ ! -s $line ]]; then
			continue
		fi
		echo -n "username "
		echo $line | cut -d "." -f 3
		count=`expr $count + 1`
	done
	echo "count "$count
;;

"$HELP" )
usage
;;

 * )
usage
exit 1
;;

esac

