#!/bin/bash

. /usr/lib/common-criteria/scripts/libcc

SSHDCONFIG="/etc/ssh/sshd_config"

# Options to configure
SSHDOPTIONS="
Ciphers aes128-cbc,aes192-cbc,aes256-cbc,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
PermitRootLogin no
PrintMotd yes
Protocol 2
PubkeyAuthentication yes
KexAlgorithms diffie-hellman-group-exchange-sha256,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521
MACs hmac-sha1-etm@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com
UsePAM yes
HostbasedAcceptedKeyTypes rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519
"

[ ! -f $SSHDCONFIG ] && {
	cc_echo "SSHD configuration file $SSHDCONFIG does not exist - skipping configuration"
	cc_exit 0
}

trap "cc_exec_log rm -f $SSHDCONFIG.$$ $SSHDCONFIG.NEW.$$" 0 1 2 3 15
perl -ne 'print unless /CC Configuration START/../CC configuration END/' < $SSHDCONFIG >$SSHDCONFIG.$$
echo "## CC Configuration START" >> $SSHDCONFIG.NEW.$$

OLDIFS=$IFS
IFS="
"
for i in $SSHDOPTIONS
do
	keyword=${i%% *}
	cc_echo "SSHD configuration: Processing option $keyword"

	# disable existing key words
	sed -i "s/^${keyword}/# Option ${keyword} disabled and reused above by CC configuration\n# ${keyword}/g" $SSHDCONFIG.$$

	echo $i >> $SSHDCONFIG.NEW.$$
done
echo "## CC Configuration END" >> $SSHDCONFIG.NEW.$$

# Make sure that evaluation specific configuration is at the top to prevent
# it being hijacked by Match configuration
cat $SSHDCONFIG.$$ >> $SSHDCONFIG.NEW.$$

cc_replace $SSHDCONFIG.NEW.$$ $SSHDCONFIG
cc_exit 0
