#!/bin/bash
# This script is being depricated. Do not use it!

# Update init scripts with service dependenices.
/bin/update-svc-deps

# Set file permission to 640 for sshinfo log file
chmod 0640 /var/log/audit/sshinfo.log

# Reload the firewall in case there were services removed in patch phase
/usr/lib/applmgmt/networking/bin/firewall-reload

# PR 2005144 Post B2BUpgrade if systemd rpm gets updated
# all config changes are wiped off. Preserving these workaround after update
#TODO remove this workaround after moving to photon2
echo “Changing watchdog timer for journald service to 10min”
sed -i.bak s/#SyncIntervalSec=5m/SyncIntervalSec=10s/g \
/etc/systemd/journald.conf
sed -i.bak s/WatchdogSec=3min/WatchdogSec=10min/g \
/usr/lib/systemd/system/systemd-journald.service
sed -i.bak s/WatchdogSec=3min/WatchdogSec=10min/g \
/usr/lib/systemd/system/systemd-udevd.service
sed -i.bak s/WatchdogSec=3min/WatchdogSec=10min/g \
/usr/lib/systemd/system/systemd-logind.service
#calling deamon-reload inorder to refresh/reload any config changes done.
echo "Reloading daemon"
/usr/bin/systemctl daemon-reload
/usr/bin/systemctl restart systemd-journald
/usr/bin/systemctl restart systemd-udevd
/usr/bin/systemctl restart systemd-logind


#disable cloud-int service PR1982599
systemctl stop cloud-init-local.service && systemctl disable cloud-init-local.service
systemctl stop cloud-init.service && systemctl disable cloud-init.service
systemctl stop cloud-config.service && systemctl disable cloud-config.service
systemctl stop cloud-final.service && systemctl disable cloud-final.service

#PR 2035598 systemd rpm update 99-dhcp-en.network config file on system
#which has been set up with static IP.
dhcp_network_file="/etc/systemd/network/99-dhcp-en.network"

if [ -f $dhcp_network_file ] ; then
    /usr/bin/rm $dhcp_network_file
fi

# 1. Find if there is ntp rpm in the patch and if we install it
# 2. Find if ntpd is started. It is started/stopped by applmgmt.
#    If it is not started then we must not start it.
# 3. Restart ntpd
grep -q 'relativepath.*ntp.*rpm' \
/storage/core/software-packages/staged-configuration.json \
&& pgrep ntpd \
&& echo 'restarting ntpd' \
&& systemctl restart ntpd

# PR 2173605, update sendmail.cf post patch
# Get the deployment type or assume embedded as default
deploymentType=`/bin/install-parameter deployment.node.type embedded`
SENDMAIL_CONF_FILE="/usr/bin/sendmail_config.py"
if [ -f $SENDMAIL_CONF_FILE ] && [ $deploymentType == 'embedded' -o $deploymentType == 'management' ]
then
    echo "$(date): Modifying sendmail config files."
    if [ ! -f /etc/mail/auth/auth-info ] ; then
        mkdir -m 700 /etc/mail/auth
        touch /etc/mail/auth/auth-info
    fi

    # start vmware-vpostgres.
    echo "Starting vPostgres service."
    service-control --start vmware-vpostgres

    echo "$(date): Updating sendmail.cf file by picking mail server details from VCDB."
    /usr/bin/python $SENDMAIL_CONF_FILE
    if [ "$?" -ne "0" ]
    then
	    echo "Failed to update sendmail.cf"
    fi
    echo "$(date): Successfully updated sendmail config file on target."
fi

# PHOTON 3.0 and higher : Changing the symbolic link of
# /etc/resolv.conf to point to /run/systemd/resolve/resolv.conf
# Reset pkgverify_level to none
if ! grep -Fxq "VMware Photon Linux 1.0" /etc/photon-release
then
    ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf
    if ! grep -Fxq '%_pkgverify_level none' /etc/rpm/macros
    then
       echo "%_pkgverify_level none" >> /etc/rpm/macros
    fi
fi

# OpenSSL 1.1.1 should use the same certificates as the regular OpenSSL
if [ -d "/etc/nxtgn-openssl" ] && [ -d "/etc/ssl/certs" ] && [ ! -L "/etc/nxtgn-openssl/certs" ] ; then
   rmdir /etc/nxtgn-openssl/certs
   ln -sf /etc/ssl/certs /etc/nxtgn-openssl/certs
fi

# Remove Pycrpto directory if it's already there
if [ -d /usr/lib/applmgmt/pycrypto ] ; then
   rm -rf /usr/lib/applmgmt/pycrypto
fi

# Function to update the password file for observability services
# password files present in /etc/vmware/vmware-vmon/svcCfgfiles/jmx folder
function update_password_file() {
    #Updates the password file in the path /etc/vmware/vmware-vmon/svcCfgfiles/jmx/*.password
    #This will generate random password
    echo "$(date): Inside update_password_file : "
    password=$(cat /dev/urandom | env LC_CTYPE=C tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1)
        for file in /etc/vmware/vmware-vmon/svcCfgfiles/jmx/*.password; do
            echo "observabilityRole $password" > $file
            echo "$(date): Password changed in $file"
        done
    echo "$(date): Password Change is succesfull"
    echo "$(date): Updating database with the new password"

    # Start/Stop of OBS service
    systemctl stop observability
    sqlite3 /storage/db/stellar.db << EOF
    replace into observabilitysettings values ('jmxpassword', "$password");
EOF
    echo "$(date): Password updated in db"
    systemctl start observability
}

if [ -d "/etc/vmware/vmware-vmon/svcCfgfiles/jmx" ]; then
 update_password_file
else
 echo "$(date): Skipping Password update since jmx folder doesnt exist"
fi

echo "$(date): Restoring pam.d files"
cd /etc/pam.d
for a in *.patch.backup
do
    mv -f $a "${a%.patch.backup}"
done

#PR 2415233, auditd logs are not rotated by default resulting in root
# partition fill up. This change will enable auditd logs doesn't use its
# own log rotation mechanism  for rotation, instead we will use logrotate
# to rotate auditd logs.
function update_auditd_conf {
   SEARCH_STR="num_logs.*"
   REPLACE_STR="num_logs = 2"
   AUDIT_CONF="/etc/audit/auditd.conf"

   cp /etc/audit/auditd.conf /etc/audit/auditd.conf_bak
   echo "$(date): num_logs set to 2 in auditd.conf"
   sed -i "s/^$SEARCH_STR/$REPLACE_STR/" "$AUDIT_CONF"
   systemctl reload auditd > /dev/null
}

# Update auditd.conf
update_auditd_conf

# Workaround to replace lighttpd.conf file post patching (PR#2415443)
CONF_FILE="/etc/applmgmt/appliance/lighttpd.conf"
TMP_CONF_FILE="/etc/applmgmt/appliance/lighttpd.conf.tmp"
if [ -f $TMP_CONF_FILE ]; then
   /bin/cmp $TMP_CONF_FILE $CONF_FILE
   EXIT_CODE=$?
   if [ $EXIT_CODE -ne 0 ]; then
      mv $TMP_CONF_FILE $CONF_FILE
      systemctl restart vami-lighttp
      EXIT_CODE=$?
      if [ $EXIT_CODE -ne 0 ]; then
         echo "$(date): Failed to restart VAMI lighttpd server."
      fi
      echo "$(date): Succesfully updated VAMI HSTS headers."
   fi
fi

# Restart DDNS
/usr/bin/python /usr/lib/applmgmt/ddns/py/ddns.py --disable
echo "$(date): Disabled DDNS"
/usr/bin/python /usr/lib/applmgmt/ddns/py/ddns.py --enable
echo "$(date): Enabled DDNS"

deprecatedRpms=(
    dbcc
    VMware-jmemtool
    VMware-mbcs
)
for rpm in ${deprecatedRpms[@]}; do
    rpm -qi --quiet $rpm && rpm -e $rpm
done

#Removing the extra servicecontrol conf for syslog.
FILE = "/etc/vmware-syslog/vmware-services-servicecontrol.conf"
if [ -f "$FILE" ]; then
    rm -rf $FILE;
fi

# Reseting banner control to redirect back banner to ui.
echo "Resetting banner control"
/usr/bin/banner_ctrl reset


# Restore non default certs from the previous JRE installation
certs=$(ls  /tmp/certs)

for cert_file in $certs
do
    alias=$(echo $cert_file | cut -d '.' -f1)
    echo "importing $cert_file with alias $alias"
    check_if_exists=$(keytool -noprompt -storepass changeit -list -trustcacerts -alias "$alias" -keystore /usr/java/jre-vmware/lib/security/cacerts | grep -c 'Certificate fingerprint')

    if [ $check_if_exists -eq 0 ]; then
        keytool -noprompt -storepass changeit -import -trustcacerts -file "/tmp/certs/$cert_file"  -alias $alias -keystore /usr/java/jre-vmware/lib/security/cacerts
    else
        echo "skipping $alias as it already exists in keystore"
    fi

done

rm -rf /tmp/certs

# Removing MBCS from the lookup service
python $(dirname $0)/remove_mbcs_from_lookup_service.py

# This will enable stig compliance across VCSA and will run only for full update
SCRIPT=$(readlink -f "$0")
SCRIPTPATH=$(dirname "$SCRIPT")
STAGEPATH=$(dirname "$SCRIPTPATH")
isleafServiceUpdate=$(grep "allowed_b2b_components" $STAGEPATH/rpm-manifest.json | wc -l)

if [ $isleafServiceUpdate -eq 0 ]; then
    echo "Apply stig rules via ansible scripts"
    #Apply ansible based hardening scripts
    mkdir -p /var/log/stig
    # Skipping tag for banner in /etc/issue
    # Skipping PHTN-30-000002 as it's creating duplicate entry in /etc/pam.d/system-auth in VCSA in patched setup
    ansible-playbook --connection=local -i 127.0.0.1, /opt/vmware/etc/compliance/stig/ansible-scripts/playbook.yml --skip-tags "PHTN-30-000002,PHTN-30-000003,PHTN-30-000007,PHTN-30-000053,PHTN-30-000055,PHTN-30-000116" -v > /var/log/stig/applystig.out

    echo "Relax stig rules not needed/compatible for VCSA"

    # Fix /etc/pam.d/system-password to allow vcsa deployment
    sed -i '/^password/d' /etc/pam.d/system-password
    echo "password  requisite   pam_cracklib.so" >> /etc/pam.d/system-password
    echo "password  required    pam_unix.so       sha512 shadow try_first_pass" >> /etc/pam.d/system-password

    # Set umask to 022
    sed -i 's/umask 027/umask 022/g' /etc/profile.d/umask.sh

    # Set bashrc to have conditional timeout
    sed -i '/TMOUT/d' /etc/bash.bashrc

    # Unset sshd timeout
    sed -i '/^ClientAliveInterval/d' /etc/ssh/sshd_config

    # Reset VCSA Banner
    sed -i 's/^#Banner none/Banner \/etc\/issue/' /etc/ssh/sshd_config

    # PHTN-30-000009 is commenting out Ciphers. re-enable it to values defined by vasecurity sshd hardening
    sed -i 's/^#Ciphers.*$/Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com/' /etc/ssh/sshd_config
    systemctl restart sshd
fi

if ! grep -q "VMware-vCenter-Cloud-Gateway" /etc/vmware/.buildInfo && \
 [ -e /usr/lib/systemd/system/cap-workflow-engine.service ] && \
 ! systemctl is-active --quiet cap-workflow-engine.service ; then
    /usr/bin/systemctl start cap-workflow-engine.service
fi

# Enable kernel FIPS. PR#2954725
# Enable vami-lighttp FIPS. PR#2877221
if [ $isleafServiceUpdate -eq 0 ]; then
    FipsFlag=$(grep "fips=" /boot/photon.cfg | wc -l)
    if [ $FipsFlag -eq 0 ]; then
        # To append fips=1 when the entry is not there in the file
        sed -i '/^photon_cmdline/s/$/ fips=1/' /boot/photon.cfg
    else
        # Enable Kernel FIPS
        sed -i 's/fips=0/fips=1/g' /boot/photon.cfg
    fi
    echo "Setting the Kernel FIPS mode as 1."
    LighttpdFipsFlag=$(grep "server.fips-mode =" /opt/vmware/etc/lighttpd/lighttpd.conf  | wc -l)
    if [ $LighttpdFipsFlag -eq 0 ]; then
        # To append fips=enabled when the entry is not there in the lighttpd conf file.
        sed -i '$aserver.fips-mode = "enable"' /opt/vmware/etc/lighttpd/lighttpd.conf
    else
        # Enable Lighttpd FIPS if its disabled in the config.
        sed -i 's/server.fips-mode = "disable"/server.fips-mode = "enable"/g' /opt/vmware/etc/lighttpd/lighttpd.conf
    fi
    systemctl restart vami-lighttp
    echo "Set FIPS mode for vami-lighttpd"
fi

# Set vmonapi https endpoint to reject from external
sed -i 's/allow/reject/g' /etc/vmware-rhttpproxy/endpoints.conf.d/vmonapi-proxy.conf

true
