#!/bin/bash2

# author: K. M. Gheri
#         phion IT GmbH
#         Copyright 2001-2006
#         All rights reserved

if [ -f /etc/phion/phion.sh ]; then
	source /etc/phion/phion.sh
fi

if [ -f /etc/phion/options ]; then
	source /etc/phion/options
fi


if [ -f /etc/phion/functions ]; then
	source /etc/phion/functions
fi

[ -f /opt/phion/run/appliance.state ] && {
	TMPCONF=/tmp/appl.conf.rollout
	/etc/phion/bin/boxconf_rollout.net1 /opt/phion/run/appliance.state ${TMPCONF}
	source ${TMPCONF}
	rm ${TMPCONF}
}

[ _$H = _ ] && eval H=0
let H++
PREFIX=""
for ((k=1 ; H-k ; k++)); do
	PREFIX="${PREFIX} $(SUB)"
done
export H=$H
ARG0="${PREFIX} writeSSHdconf"
ARGB="writeSSHdconf"
ARGS=""
ARGLIST=$@
ARTROOTDIR="/boot/art"

N=0
ISBOOT=0

[ _$1 = _N ] && {
	#activation from within networking, i.e., make_box

	ROOUTFLE=$2
	shift 2
	N=1
}
[ "$1" = "-b" ] && {
	ISBOOT=1
	shift 1
}

PATH="/sbin:/bin:/usr/sbin:/usr/bin:/opt/phion/bin:/etc/phion/bin"

BINDIPS=""
BINDIPS=$@

DIRECT=0

[ _"$BINDIPS" = _ ] && {
	# backup approach in case no bind IPs have been handed over
	DIRECT=1
	BINDIPS=$(/etc/phion/bin/iplist -ip )
	BINDIPS="127.0.0.1 $BINDIPS"
}



PMODPATH="/opt/phion/modules/box/boxother/ssh"
[ -f ${PMODPATH}/moddefs.conf ] && source ${PMODPATH}/moddefs.conf
MYLOGFILE=${logfile_activate:-box_SSH_config}


logerror="LogError $MYLOGFILE"

# read in conf-file



SSHCONFDIR=/var/phion/preserve/ssh
[ ! -d ${SSHCONFDIR} ] && mkdir -p ${SSHCONFDIR}

SSHRUNDIR=/var/phion/run/ssh
[ ! -d ${SSHRUNDIR} ] && mkdir -p ${SSHRUNDIR}


function fEXIT {

	[ -f ${SSHRUNDIR}/ssh.conf.rollout.$$.tmp ] && rm -f ${SSHRUNDIR}/ssh.conf.rollout.$$.tmp
	[ -f ${SSHRUNDIR}/sshd_config.$$.tmp ] && rm -f ${SSHRUNDIR}/sshd_config.$$.tmp
	[ -f ${SSHRUNDIR}/ssh_config.$$.tmp ] && rm -f ${SSHRUNDIR}/ssh_config.$$.tmp
	[ -f ${SSHRUNDIR}/boxnet.conf.rollout.$$.tmp ] && rm -f ${SSHRUNDIR}/boxnet.conf.rollout.$$.tmp
	[ -f ${SSHRUNDIR}/boxkey.conf.rollout.$$.tmp ] && rm -f ${SSHRUNDIR}/boxkey.conf.rollout.$$.tmp

}

function readCONFs
	{

	local ARG0="${PREFIX} $(SUB1) readCONFs"
	local ARGS=""
	local LISTENIP
	local BINDIP
	local PHION_ROLLOUT_NET=${PHION_ROLLOUT}.net

	if [ ! -x "${PHION_ROLLOUT_NET}" ]; then
		$logerror "Error" "[0213007] ${ARG0}(${ARGS})->1: missing utility file $(MARK ${PHION_ROLLOUT})"
		return 1
	fi

	trap fEXIT EXIT

	[ ${N:-0} != 1 ] && {

		# TODO rewrite and use new active boxnet cksum file to identify current boxnet-ro
		# only activate and softactivate may change this checksum
		# the reference file is THEROLLOUTFLE

		local THEROLLOUTFLE="/etc/phion/dynconf/boxnet.conf.rollout"
		local MYROLLOUTFLE="${SSHRUNDIR}/boxnet.conf.rollout.$$.tmp"
		local OPP="/opt/phion/preserve"
		local OPR="/opt/phion/run"
		local PHION_BOXCONFNET="/opt/phion/config/active/boxnet.conf"
		local PHION_BOXCONFNET_TMP="${SSHRUNDIR}/boxnet.conf.$$.tmp"


		local NEWROLLOUT=1

		[ -s ${THEROLLOUTFLE} -a -s ${OPP}/ro_network_active ] && {

			local RCKSUM=$(cksum ${THEROLLOUTFLE} 2>/dev/null)
			set -- ${RCKSUM}
			RCKSUM=${1}
			local ROCKSUM=$(cat ${OPP}/ro_network_active )

			[ ${RCKSUM:-0} = ${ROCKSUM:-_} ] && {
				NEWROLLOUT=0
				source ${THEROLLOUTFLE}

			}


		}


		[ ${NEWROLLOUT:-1} = 1 ] && {

			[ -f ${PHION_BOXCONFNET} ] &&  {
				/bin/sed -e "s/CHECKLESS = [012]*/#/
				s/SERVERINC = [012]*/#/" ${PHION_BOXCONFNET} > ${PHION_BOXCONFNET_TMP}

			${PHION_ROLLOUT_NET} ${PHION_BOXCONFNET_TMP} ${MYROLLOUTFLE} &>/dev/null

				[ -f ${PHION_BOXCONFNET_TMP} ] && rm -f ${PHION_BOXCONFNET_TMP}
				source ${MYROLLOUTFLE}
				CopyOrDelRolloutFile  ${MYROLLOUTFLE}
			}
		}

	}

	if [ -f "/opt/phion/config/active/ssh.conf" ]; then
		${PHION_ROLLOUT_NET} /opt/phion/config/active/ssh.conf ${SSHRUNDIR}/ssh.conf.rollout.$$.tmp &>/dev/null

		source ${SSHRUNDIR}/ssh.conf.rollout.$$.tmp

		if diff --brief ${SSHRUNDIR}/ssh.conf.rollout.$$.tmp ${SSHCONFDIR}/ssh.conf.rollout &>/dev/null; then
			CopyOrDelRolloutFile ${SSHRUNDIR}/ssh.conf.rollout.$$.tmp
		else
			MoveOrDelRolloutFile ${SSHRUNDIR}/ssh.conf.rollout.$$.tmp ${SSHCONFDIR}/ssh.conf.rollout
		fi
	fi

	[ $N != 1 ] && {

		LISTENIP=$box_boxnet_IP_1

		if [ -f "$PHION_BINDIPS" ]; then
			while read line; do
				BINDIP="$BINDIP $line"
			done < "$PHION_BINDIPS"
		fi


		BINDIP=${BINDIP:-"$LISTENIP"}
	}

	##echo $BINDIP

	return 0

	}


function handleSSHd
{
	BINDIPADDR=$@
	local ARG0="${PREFIX} $(SUB1) handleSSHd"
	local ARGS="ARGS"

	local STATUS=0

	trap '' INT TERM HUP
	$logerror "Notice" "[0213008] ${ARG0}(${ARGS}): binding to ARGS = $(MARK ${BINDIPADDR})"
	$logerror "Notice" "[0213009] ${ARG0}(${ARGS}): writing /etc/ssh/sshd_config"


	if [ -e /etc/ssh/sshd_config ]; then
		/bin/cp -f /etc/ssh/sshd_config ${SSHRUNDIR}/sshd_config.bak
	fi


	/bin/cat > ${SSHRUNDIR}/sshd_config.$$.tmp <<-EOF
		#/etc/ssh/sshd_config
		#created: $(date)
		#do not edit manually all changes will be lost

		# This is ssh server systemwide configuration file.

		# FIRST section: PHION configured entries

	EOF

	for i in $BINDIPADDR; do
		echo "ListenAddress $i" >> ${SSHRUNDIR}/sshd_config.$$.tmp
	done

	[[ ${box_ENABLEDSAKEYS:-yes} = "yes" && -r /etc/ssh/ssh_host_dsa_key ]] &&\
		echo "HostKey /etc/ssh/ssh_host_dsa_key" >> ${SSHRUNDIR}/sshd_config.$$.tmp
	[[ -r /etc/ssh/ssh_host_ecdsa_key ]] &&\
		echo "HostKey /etc/ssh/ssh_host_ecdsa_key" >> ${SSHRUNDIR}/sshd_config.$$.tmp
	echo -n "HostKeyAlgorithms ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521" >> ${SSHRUNDIR}/sshd_config.$$.tmp
	[[ ${box_ENABLEDSAKEYS:-yes} = "yes" ]] && {
		echo ",ssh-dss" >> ${SSHRUNDIR}/sshd_config.$$.tmp
		echo -n "PubkeyAcceptedKeyTypes +ssh-dss" >> ${SSHRUNDIR}/sshd_config.$$.tmp
	}
	echo "" >> ${SSHRUNDIR}/sshd_config.$$.tmp

	echo "AllowTcpForwarding ${box_ALLOWTCPFORWARDING:-no}"  >> ${SSHRUNDIR}/sshd_config.$$.tmp
	echo "LoginGraceTime ${box_LOGRACE:-90}"  >> ${SSHRUNDIR}/sshd_config.$$.tmp
	echo "PermitRootLogin ${box_PROOT:-yes}"  >> ${SSHRUNDIR}/sshd_config.$$.tmp
	echo "StrictModes ${box_STRICTMODE:-yes}" >> ${SSHRUNDIR}/sshd_config.$$.tmp

	if [ ${box_FTPSUB:-no} = "yes" ]; then
		if [ -x /usr/libexec/openssh/sftp-server ]; then
			echo "Subsystem sftp /usr/libexec/openssh/sftp-server"  >> ${SSHRUNDIR}/sshd_config.$$.tmp
		else
			$logerror "Error" "[0213010] ${ARG0}(${ARGS}): missing executable $(MARK /usr/libexec/openssh/sftp-server )"
			STATUS=1
		fi
	fi

	if [ ${box_AUTHPWD:-no} = "yes" ]; then
		echo "PasswordAuthentication no" >> ${SSHRUNDIR}/sshd_config.$$.tmp
		echo "ChallengeResponseAuthentication no" >> ${SSHRUNDIR}/sshd_config.$$.tmp
	else
		echo "PasswordAuthentication yes" >> ${SSHRUNDIR}/sshd_config.$$.tmp
		echo "ChallengeResponseAuthentication yes" >> ${SSHRUNDIR}/sshd_config.$$.tmp
	fi
	echo "UsePAM yes" >> ${SSHRUNDIR}/sshd_config.$$.tmp

	echo "ClientAliveInterval ${box_CLIENTALIVEINTERVAL:-0}"  >> ${SSHRUNDIR}/sshd_config.$$.tmp
	echo "ClientAliveCountMax ${box_CLIENTALIVECOUNTMAX:-3}"  >> ${SSHRUNDIR}/sshd_config.$$.tmp
	echo "Compression ${box_COMP:-yes}"  >> ${SSHRUNDIR}/sshd_config.$$.tmp

	echo "" >> ${SSHRUNDIR}/sshd_config.$$.tmp
	echo "# SECOND section: default configuration from template file" >> ${SSHRUNDIR}/sshd_config.$$.tmp

	if [ -f "$PHION_ETC"/templates/sshd_config.template ]; then
		/bin/cat "$PHION_ETC"/templates/sshd_config.template >> ${SSHRUNDIR}/sshd_config.$$.tmp
	fi

	if diff --brief ${SSHRUNDIR}/sshd_config.$$.tmp /etc/ssh/sshd_config &>/dev/null; then
		rm -f ${SSHRUNDIR}/sshd_config.$$.tmp
	else
		mv -f ${SSHRUNDIR}/sshd_config.$$.tmp /etc/ssh/sshd_config
		if [ -d $ARTROOTDIR/config/etc ]; then
			[ ! -d $ARTROOTDIR/config/etc/ssh ] && mkdir $ARTROOTDIR/config/etc/ssh
			cp -f /etc/ssh/sshd_config $ARTROOTDIR/config/etc/ssh
		fi
	fi

	cp -f /etc/phion/templates/ssh_config.template ${SSHRUNDIR}/ssh_config.$$.tmp
	[[ ${box_ENABLEDSAKEYS:-yes} = "yes" ]] && echo -e "\tPubkeyAcceptedKeyTypes +ssh-dss" >> ${SSHRUNDIR}/ssh_config.$$.tmp
	if diff --brief ${SSHRUNDIR}/ssh_config.$$.tmp /etc/ssh/ssh_config &>/dev/null; then
		rm -f ${SSHRUNDIR}/ssh_config.$$.tmp
	else
		mv -f ${SSHRUNDIR}/ssh_config.$$.tmp  /etc/ssh/ssh_config
	fi


	[ $STATUS = 0 ] && $logerror "Notice" "[0213002] ${ARG0}(${ARGS}): /etc/ssh/sshd_config successfully written"
	[ $STATUS = 1 ] && $logerror "Warning" "[0213003] ${ARG0}(${ARGS}): /etc/ssh/sshd_config partially written"

	trap - INT TERM HUP
	return $STATUS
}

function writeFailLock
{
denyCount=${box_BRUTEFORCEPROTECTIONCOUNT:-6}
denyCountTime=${box_BRUTEFORCEPROTECTIONTIME:-300}

for file in /etc/pam.d/password-auth /etc/pam.d/system-auth
do
        if ! /bin/grep -q pam_faillock.so $file; then
                /bin/sed -i "/delay=2000000/ i auth        required      pam_faillock.so preauth silent audit even_deny_root denyCount="$denyCount" unlock_time="$denyCountTime"" $file
                /bin/sed -i "/1000 quiet_success/ i auth        [default=die] pam_faillock.so authfail audit even_deny_root denyCount="$denyCount" unlock_time="$denyCountTime"" $file
                /bin/sed -i '/account * required * pam_unix.so/ i account     required      pam_faillock.so' $file
        fi
done
}

function removeWriteLock
{
  for file in /etc/pam.d/password-auth /etc/pam.d/system-auth
do
        if /bin/grep -q pam_faillock.so $file; then
                /bin/sed -i "/pam_faillock.so/d" $file >> /dev/null
        fi
done
}


################# begin main body ########################


$logerror "Info" "[0213013] ${ARG0}(${ARGS}): ------------- START ---------------------------"

$logerror "Info" "[0210107] ${ARG0}(${ARGS}): ARGS=$ARGLIST"

[ $N != 1 ] && {
	readCONFs
	$logerror "Info" "[0210108] ${ARG0}(${ARGS}): starting handling of ssh daemon configuration"
}

[ $N = 1 ] && {
	source ${ROOUTFLE}
	$logerror "Info" "[0210108] ${ARG0}(${ARGS}): starting network triggered handling of ssh daemon configuration"
}

handleSSHd $BINDIPS
removeWriteLock
[[ ${box_BRUTEFORCEPROTECTIONBOOL:-no} = "yes" ]] && writeFailLock

SSHCHCK=${box_SSHEVT:-0}

if [ $N != 1 -a $ISBOOT != 1 -a ! -f /var/run/keepsshrunning.state.service ]; then

	if (/etc/rc.d/init.d/sshd stop; sleep 1; /etc/rc.d/init.d/sshd start;) ; then
		$logerror "Notice" "[0213011] ${ARG0}(${ARGS}): sshd successfully restarted"
		[ $SSHCHCK -ge 2 ] && logger -i -puucp.info -tEvent "layer_id=1;layer_name=network layer;class_id=1;class_name=${ARGB};type_id=2071;type_name=sshd;data=restart of sshd succeeded"
	else
		$logerror "Error" "[0213012] ${ARG0}(${ARGS}): restart of sshd failed"
		[ $SSHCHCK -ge 0 ] && logger -i -puucp.info -tEvent "layer_id=1;layer_name=network layer;class_id=1;class_name=${ARGB};type_id=2070;type_name=sshd;data=restart of sshd failed"
	fi
fi

$logerror "Info" "[0210112] ${ARG0}(${ARGS}): finished activation of ssh daemon configuration"
$logerror "Info" "[0213014] ${ARG0}(${ARGS}): -------------- END ----------------------------"



exit 0


################# end main body   ########################
