#!/bin/sh
# Name          : aws-ecs-pci-v1.1.sh
# Summary       : Datapipe PCI-DSS v3.2 Hardening Standards Script
# Author        : Kenny Lo, John Lavin
# Date          : May 10, 2017

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin 

# Sanity check : OS version check
if [ -e /etc/system-release ]; then
AWS_ECS=`grep -icE "Amazon Linux AMI" /etc/system-release`
fi

if [ $AWS_ECS -lt 1 ]; then
echo "This script will only be applicable for AWS ECS. Please check your OS. Exiting ..."
sleep 2
exit
fi

# Install required packages for hardening script
rpm -e ntp
rpm -e ntpdate
yum -y install sysstat rcs pam_passwdqc audispd-plugins authconfig tcp_wrappers chrony

# Confirm packages installed
if [ ! -f /usr/bin/rcs ]; then
echo "RCS did not install successfully. Please manually install the following packages and re-run hardening script."
echo ""
echo "yum -y install chrony sysstat rcs"
echo "--"
echo "No modifications have been made to the system."
sleep 5
exit
fi

if [ ! -f /usr/bin/sar ]; then
echo "Sysstat did not install successfully. Please manually install the following packages and re-run hardening script."
echo ""
echo "yum -y install chrony sysstat rcs"
echo "--"
echo "No modifications have been made to the system."
sleep 5
exit
fi

if [ ! -f /usr/sbin/chronyd  ]; then
echo "chrony did not install successfully.  Please manually install the following packages and re-run hardening script."
echo "" 
echo "yum -y install chrony sysstat rcs"
echo "--"
echo "No modifications have been made to the system."
sleep 5
exit
fi

# startup chrony
chkconfig --level 35 chrony on
echo "OPTIONS=\"-u chrony\"" > /etc/sysconfig/chronyd
/etc/init.d/chrony restart

LOGDIR=/etc/DATAPIPE
LOGFILE1=$LOGDIR/b4hardening.log
mkdir -p $LOGDIR
touch $LOGFILE1
echo ### >> $LOGFILE1
echo "System info before applying Datapipe hardening standard." >> $LOGFILE1
echo Date: `date +%c` >> $LOGFILE1
echo HOSTNAME: `hostname` >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
uptime >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### ps -elf" >> $LOGFILE1
ps -elf >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### netstat -an | grep LIST" >> $LOGFILE1
netstat -an | grep LIST >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### netstat -an | grep LSIT" >> $LOGFILE1
netstat -anlp | grep LIST >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### cat /etc/hosts.allow" >> $LOGFILE1
cat /etc/hosts.allow >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### cat /etc/hosts.deny" >> $LOGFILE1
cat /etc/hosts.deny >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### ls -l /var/spool/cron" >> $LOGFILE1
ls -l /var/spool/cron >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### cat /var/spool/cron/*" >> $LOGFILE1
cat /var/spool/cron/* >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### run /sbin/chkconfig --list" >> $LOGFILE1
/sbin/chkconfig --list >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### run /sbin/chkcofig --list | grep 3:on" >> $LOGFILE1
/sbin/chkconfig --list | grep 3:on >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### cat /etc/passwd" >> $LOGFILE1
cat /etc/passwd >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### egrep -v 'bin/false|bin/nologin|bin/shutdown|bin/halt|bin/sync' /etc/passwd" >> $LOGFILE1
egrep -v 'bin/false|bin/nologin|bin/shutdown|bin/halt|bin/sync' /etc/passwd >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### run last" >> $LOGFILE1
last >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### run /sbin/runlevel" >> $LOGFILE1
/sbin/runlevel >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### run df -k" >> $LOGFILE1
df -k >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### run mount" >> $LOGFILE1
mount >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### run ls -l /etc/exports" >> $LOGFILE1
ls -l /etc/exports >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### run cat /etc/exports" >> $LOGFILE1
cat /etc/exports >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### cat /etc/fstab" >> $LOGFILE1
cat /etc/fstab >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### run cat /etc/mtab" >> $LOGFILE1
cat /etc/mtab >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### run ls -l /var/log" >> $LOGFILE1
ls -l /var/log >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo END. >> $LOGFILE1

####
LOGFILE2=$LOGDIR/hardening.log
touch $LOGFILE2
echo Date: `date +%c` >> $LOGFILE2
echo HOSTNAME: `hostname` >> $LOGFILE2
echo $0 is executed. >> $LOGFILE2
echo Datapipe AWS ECS PCI System Hardening v1.1 being Applied. >> $LOGFILE2

# Create RCS directories

for DIRECTORY in \
	/etc/ \
	/etc/ssh \
	/etc/rc.d/init.d \
	/etc/sysconfig \
	/etc/rc.d \
	/usr/share/hal/fdi \
	/etc/vsftpd \
	/etc/X11/xdm \
	/etc/X11/xinit \
	/etc/X11/gdm \
	/boot/grub \
	/etc/default \
	/etc/skel \
	/etc/security \
	/etc/audit \
	/etc/pam.d \
	/root
do
	mkdir $DIRECTORY/RCS
done

# Check in every file to be modified by the PCI script:
for FILE in \
	/etc/ssh/ssh_config \
	/etc/ssh/sshd_config \
	/etc/crontab \
	/etc/hosts.deny \
	/etc/hosts.allow \
	/etc/rc.d/init.d/functions \
	/etc/sysconfig/authconfig \
	/etc/sysconfig/init \
	/etc/sysconfig/sendmail \
	/etc/sysconfig/selinux \
	/etc/selinux/config \
	/etc/inittab \
	/etc/sysctl.conf \
	/etc/rsyslog.conf \
	/etc/vsftpd.conf \
	/etc/rc.d/rc.sysinit \
	/etc/fstab \
	/usr/share/hal/fdi/95userpolicy \
	/usr/share/hal/fdi/polilcy/20thirdparty \
	/etc/ftpaccess \
	/etc/ftpusers \
	/etc/vsftpd/vsftpd.conf \
	/etc/vsftpd.ftpusers \
	/etc/X11/xdm/Xservers \
	/etc/X11/xinit/xserverrc \
	/etc/X11/xinit \
	/etc/at.allow \
	/etc/at.deny \
	/etc/cron.allow \
	/etc/cron.deny \
	/etc/securetty \
	/etc/X11/gdm/gdm.conf \
	/boot/grub/grub.conf \
	/etc/inittab \
	/etc/exports \
	/etc/default/useradd \
	/etc/passwd \
	/etc/shadow \
	/etc/group \
	/etc/gshadow \
	/etc/login.defs \
	/etc/bashrc \
	/etc/csh.cshrc \
	/etc/csh.login \
	/etc/profile \
	/etc/skel/.bashrc \
	/root/.bash_profile \
	/root/.bashrc \
	/root/.bash_profile \
	/root/.cshrc \
	/root/.tcshrc \
	/etc/security/limits.conf \
	/etc/pam.d/su \
	/etc/security/access.conf \
	/etc/issue \
	/etc/motd \
	/etc/chrony.conf \
	/etc/issue.net \
	/etc/vsftpd.conf \
        /etc/audisp/plugins.d/syslog.conf \
	/etc/audit/audit.rules \
	/etc/audit/auditd.conf \
	/etc/pam.d/password-auth-ac \
	/etc/pam.d/system-auth-ac \
	/etc/pam.d/sshd
do
ci -l -wsecurity $FILE <<EOF
Original State Before Datapipe PCI-DSS Hardening Standards Were Applied.
.
EOF
done

rm  -rf  /var/tmp 
ln  -s   /tmp  /var/tmp 


# 2 Patches, Packages and Initial Lockdown
# 2.1 Apply Latest OS Patches

yum -y update

## PCI 2.2.4.53 Requires this to be disabled
if [ -e /etc/init.d/yum-updatesd ];then
service    yum-updatesd  stop
chkconfig --level 35 yum-updatesd  off
fi


# 2.2 Validate The System Before Making Changes
# For the time being, assuming new system, no
# checks to perform


# 2.3 Configure SSH

SSHD_CONFIG='/etc/ssh/sshd_config'
if [ -e $SSHD_CONFIG ]; then 
   echo "Securing $SSHD_CONFIG" 
   # Had to put the " no" in for the RhostsRSAAuthentication source pattern 
   # match, as otherwise the change was taking place twice so the file ended 
   # up with TWO records like that.  The " no" pattern made the one unique. 
   # That 2nd record was a combination of comments in the default original file. 
   # Some lines ARE duplicated in the original config file, one is commented 
   # out, the next one isn't. 
   # Also, the spacing below is a little off so lines fit on the page. 
   awk '/^#.*Port /                     { print "Port 22"; next }; 
        /^#.*Protocol /                 { print "Protocol 2"; next }; 
        /^#MaxAuthTries /               { print "MaxAuthTries 4"; next };
        /^#.*LogLevel /                 { print "LogLevel VERBOSE"; next }; 
        /^#PermitRootLogin /            { print "PermitRootLogin no"; next }; 
     /^#RhostsRSAAuthentication no /    { print "RhostsRSAAuthentication no"; next }; 
        /^#HostbasedAuthentication /    { print "HostbasedAuthentication no"; next }; 
        /^#.*IgnoreRhosts /             { print "IgnoreRhosts yes"; next }; 
        /^#.*PermitEmptyPasswords /     { print "PermitEmptyPasswords no"; next }; 
        /^#.*Banner /                   { print "Banner /etc/issue.net"; next }; 
        /^X11Forwarding /           { print "X11Forwarding no"; next }; 
        /^#.*ClientAliveCountMax /      { print "ClientAliveCountMax 3"; next }; 
        /^#.*ClientAliveInterval /      { print "ClientAliveInterval 900"; next }; 
        /^#.*LoginGraceTime /          { print "LoginGraceTime 60"; next }; 
                                        { print }' /etc/ssh/sshd_config  \
                                                   > $SSHD_CONFIG.new
mv /etc/ssh/sshd_config.new /etc/ssh/sshd_config

   chown root:root $SSHD_CONFIG 
   chmod 0600      $SSHD_CONFIG 
fi

# 2.4 Enable System Accounting
# Enabled when sysstat is installed.  So we just have to correct directory permissions
chmod 600 /var/log/sa/*


# 3 Minimize xinetd network services
# 3.1 Disable Standard Services

for SERVICE in    \
    amanda        \
    chargen       \
    chargen-udp   \
    cups          \
    cups-lpd      \
    daytime       \
    daytime-udp   \
    echo          \
    echo-udp      \
    eklogin       \
    ekrb5-telnet  \
    finger        \
    gssftp        \
    imap          \
    imaps         \
    ipop2         \
    ipop3         \
    klogin        \
    krb5-telnet   \
    kshell        \
    ktalk         \
    ntalk         \
    rexec         \
    rlogin        \
    rsh           \
    rsync         \
    talk          \
    tcpmux-server \
    telnet        \
    tftp          \
    time-dgram    \
    time-stream   \
    uucp
do 
    if [ -e /etc/xinetd.d/$SERVICE ]; then 
         echo "Disabling SERVICE($SERVICE) - `ls -la /etc/xinetd.d/$SERVICE`." 
         chkconfig --level 35 ${SERVICE} off 


    fi 
done 


# 3.2 Configure TCP Wrappers and Firewall to Limit Access
# 3.2.1 Check /etc/hosts.deny for deny all statement
echo "ALL: ALL" >> /etc/hosts.deny

# 3.2.2 Check /etc/hosts.allow:  Allow Access to Locally Connected Networks
echo "ALL: localhost" >> /etc/hosts.allow
echo "sshd : ALL : allow" >> /etc/hosts.allow
echo "bpcd : ALL : allow" >> /etc/hosts.allow
echo "vnetd : ALL : allow" >> /etc/hosts.allow
echo "snmpd : ALL : allow" >> /etc/hosts.allow
echo "pbx_exchange : ALL : allow" >> /etc/hosts.allow

# 3.3 Only Enable telnet If Absolutely Necessary
# Leaving disabled

# 3.4 Only Enable FTP, If Absolutely Necessary
# Leaving disabled

# 3.5 Only Enable rlogin/rsh/rcp, If Absolutely Necessary
# Leaving disabled

# 3.6 Only Enable TFTP Server, If Absolutely Necessary
# Leaving disabled


# 4 Minimize boot services
# 4.1 Set Daemon umask

 
chown root:root   /etc/sysconfig/init 
chmod 0755        /etc/sysconfig/init 


# 4.2 Disable xinetd, If Possible

echo "The 'chkconfig' status of 'xinetd' is shown before it is turned off and" 
echo "then after so it can visually be compared." 
echo "Note: The remaining chkconfig checks, in this hardening script, do the" 
echo "same thing." 
chkconfig  --list   xinetd 
chkconfig  --level  12345  xinetd  off 
chkconfig  --list   xinetd 


# 4.3 Ensure sendmail is only listening to the localhost, If Possible
# This is going under the assumption sendmail is not needed.
# NOTE:  The email server need not be running to send outgoing mail.

if [ -e /etc/init.d/sendmail ];then
echo "DAEMON=no"  > /etc/sysconfig/sendmail
echo "QUEUE=1h"  >> /etc/sysconfig/sendmail
chkconfig  --list   sendmail
chkconfig  --level  12345  sendmail off
chkconfig  --list   sendmail
chown root:root     /etc/sysconfig/sendmail
chmod 0644          /etc/sysconfig/sendmail
fi

# 4.4 Disable GUI Login, If Possible
sed -i 's/id:5:initdefault:/id:3:initdefault:/' /etc/inittab 
chown  root:root  /etc/inittab 
chmod  0600       /etc/inittab 

# 4.5 Disable X Font Server, If Possible

if [ -e /etc/init.d/xfs ];then
chkconfig  --list   xfs 
chkconfig  --level  12345  xfs  off 
chkconfig  --list   xfs 
fi


# 4.6 Disable Standard Boot Services

echo " When doing this from within X windows the display will slow to a horrible" 
echo " crawl as soon as the xfs service is disabled.  Recommend doing this" 
echo " script from init 3 (runlevel 3)." 
# From a scripted perspective, this will be backwards from what the CIS Benchmark 
# recommends.  Philosophy is to leave the few known/necessary services on, that 
# do remain in the minimialized baseline, and then as each other step/procedure 
# below is covered, it will disable what we know we don't need for a secure and 
# hardened baseline. 
# 
# The following services ARE stopped/disabled using the following effort for the 
# baseline: 
# 
# This affects network/NFS mapping during system building and/or during kickstart 
# %post processing. 
#     autofs 
#     automount 
#     iptables 
#     portmap 
#     NFS services 
#     NFS statd 
#     system message bus 
# ** Warning** Disabling 'nfs' at this point in the script forcefully unmounts 
#              any NFS network mounts. 
# The following services should normally be enabled, unless there is a compelling 
# reason not to:  (which is why this hardening section does not alter their state) 
 
   for SERVICE in                \
       abrtd                     \
       acpid                     \
       amd                       \
       anacron                   \
       apmd                      \
       arptables_jf              \
       aprwatch                  \
       atd                       \
       autofs                    \
       avahi-daemon              \
       avahi-dnsconfd            \
       bpgd                      \
       bluetooth                 \
       bootparamd                \
       capi                      \
       conman                    \
       cups                      \
       cyrus-imapd               \
       dc_client                 \
       dc_server                 \
       dhcdbd                    \
       dhcp6s                    \
       dhcpd                     \
       dhcrelay                  \
       dovecot                   \
       dund                      \
       firstboot                 \
       gpm                       \
       haldaemon                 \
       hidd                      \
       hplip                     \
       httpd                     \
       ibmasm                    \
       ipmi                      \
       irda                      \
       iscsi                     \
       iscsid                    \
       isdn                      \
       kadmin                    \
       kdump                     \
       kprop                     \
       krb524                    \
       krb5kdc                   \
       kudzu                     \
       ldap                      \
       lisa                      \
       lm_sensors                \
       mailman                   \
       mcstrans                  \
       mdmonitor                 \
       mdmpd                     \
       microcode_ctl             \
       multipathd                \
       mysqld                    \
       named                     \
       netfs                     \
       netplugd                  \
       NetworkManager            \
       nfs                       \
       nfslock                   \
       nscd                      \
       openibd                   \
       ospf6d                    \
       ospfd                     \
       pand                      \
       pcscd                     \
       portmap                   \
       postgresql                \
       privoxy                   \
       psacct                    \
       radvd                     \
       rarpd                     \
       rdisc                     \
       readahead_early           \
       readahead_later           \
       ripd                      \
       ripngd                    \
       rpcgssd                   \
       rpcidmapd                 \
       rpcsvcgssd                \
       rstatd                    \
       rusersd                   \
       rwhod                     \
       saslauthd                 \
       setroubleshoot            \
       smartd                    \
       smb                       \
       snmptrapd                 \
       spamassassin              \
       squid                     \
       tog-pegasus               \
       tomcat5                   \
       tux                       \
       winbind                   \
       wine                      \
       wpa_supplicant            \
       xend                      \
       xendomains                \
       ypbind                    \
       yppasswdd                 \
       ypserv                    \
       ypxfrd                    \
       zebra
   do 
        if [ -e /etc/init.d/$SERVICE ]; then 
             # Doing business this way causes less needless errors that a 
             # reviewer of the hardening process doesn't need to deal with. 
             service $SERVICE stop 
             chkconfig  --level  12345  $SERVICE  off 
        fi 
   done 


# 4.7 Only Enable SMB (Windows File Sharing) Processes, If Absolutely Necessary
# Leaving disabled


# 4.8 Only Enable NFS Server Processes, If Absolutely Necessary
# Leaving disabled


# 4.9 Only Enable NFS Client Processes, If Absolutely Necessary
# Leaving disabled


# 4.10 Only Enable NIS Client Processes, If Absolutely Necessary
# Leaving disabled


# 4.11 Only Enable NIS Server Processes, If Absolutely Necessary
# Leaving disabled


# 4.12 Only Enable RPC Portmap Process, If Absolutely Necessary
# Leaving disabled


# 4.13 Only Enable netfs Script, If Absolutely Necessary
# Leaving disabled


# 4.14 Only Enable Printer Daemon Processes, If Absolutely Necessary
# Leaving disabled

rpm -e bluez-utilz-cups 
rpm -e cups 
rpm -e libgnomecups 
rpm -e hal-cups-utils 


# 4.15 Only Enable Web Server Processes, If Absolutely Necessary
# Leaving disabled, but need to revisit this one to doc the
# http://cisecurity.org/bench_apache.html


# 4.16 Only Enable SNMP Processes, If Absolutely Necessary
# Leaving disabled


# 4.17 Only Enable DNS Server Process, If Absolutely Necessary
# Leaving disabled


# 4.18 Only Enable SQL Server Processes, If Absolutely Necessary
# Leaving disabled


# 4.19 Only Enable Squid Cache Server, If Absolutely Necessary
# Leaving disabled


# 4.20 Only Enable Kudzu Hardware Detection, If Absolutely Necessary
# Leaving disabled


# 4.21 Only Enable cyrus-imapd, If Absolutely Necessary
# Leaving disabled


# 4.22 Only Enable dovecot, If Absolutely Necessary
# Leaving disabled


# 5 System Network Parameter Tuning
# 5.1 Network Parameter Modifications

cat <<END_SCRIPT  >>  /etc/sysctl.conf 
### The following lines are added by hardening scripts, per CIS Red Hat Enterprise Linux Benchmark
net.ipv4.conf.default.secure_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 4096
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.tcp_timestamps = 0
net.ipv4.ip_forward = 1
# This is for TW Policy RHEL6 2.2.3.11 & 2.2.3.12
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
#
kernel.exec-shield = 1
kernel.randomize_va_space = 2
###
END_SCRIPT
chown root:root /etc/sysctl.conf 



# 5.2 Additional Network Parameter Modifications

cat <<END_SCRIPT  >>  /etc/sysctl.conf 
# The following 3 lines are added by hardening script, per CIS Red Hat Enterprise Linux Benchmark:

net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.icmp_ignore_bogus_error_responses = 1
#
# Per CIS Red Hat Enterprise Linux Benchmark, 4.4.2.1 disable IPv6 Router Advertisements and 4.4.2.2 disable IPv6 Redirect Acceptance
net.ipv6.conf.all.accept_ra = 0
net.ipv6.conf.default.accept_ra = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0
END_SCRIPT
chown root:root /etc/sysctl.conf 


# 6 Logging
# 6.1 Capture Messages Sent To syslog AUTHPRIV Facility

if [ `grep -v '^#' /etc/rsyslog.conf | grep -v authpriv\.none | grep -c  \
     'authpriv'` -eq 0 ]; then 
      echo "Established the following record in /etc/rsyslog.conf" 
      echo "authpriv.*\t\t\t\t/var/log/secure" 
      echo -e "# the following line is added by hardening script." >> /etc/rsyslog.conf
      echo -e "authpriv.*\t\t\t\t/var/log/secure" >> /etc/rsyslog.conf 
else 
      echo "rsyslog OK.  Didn't have to change rsyslog.conf for authpriv; the" 
echo "following record is good:" 
      grep "^authpriv" /etc/rsyslog.conf | grep '/var/log/secure' 
fi 
# Add record for 'authpriv.*' to /var/log/messages, placing it after the authpriv record 
if [ `grep -v '^#' /etc/rsyslog.conf | grep -v log\/secure | grep -c 'authpriv.\*'` -ne 1 ]; then 
sed -i '/\/var\/log\/secure/a \authpriv.*                                              /var/log/messages' /etc/rsyslog.conf
else 
echo "rsyslog OK.  Didn't have to change rsyslog.conf for authpriv.*; the" 
echo "following record is good:" 
      grep 'authpriv.\*' /etc/rsyslog.conf 
fi 
chown root:root /etc/rsyslog.conf 
# Original/default permissions are 0644. 
chmod 0600      /etc/rsyslog.conf 




touch /var/log/secure 
chown root:root /var/log/secure 
chmod 0600      /var/log/secure 
echo "Restarting rsyslog service to immediately implement the latest configuration." 
service rsyslog stop 
service rsyslog start


# 6.2 Turn On Additional Logging For FTP Daemon

FILE="" 
if [ -f /etc/vsftpd.conf ]; then 
     FILE="/etc/vsftpd.conf" 
else 
     FILE="/etc/vsftpd/vsftpd.conf" 
fi 
if [ -f $FILE ]; then 
    awk '/^#?xferlog_std_format/ \
        { print "xferlog_std_format=NO"; next }; 
    /^#?log_ftp_protocol/ \
        { print "log_ftp_protocol=YES"; next }; 
    { print }' ${FILE} > ${FILE}.new
mv ${FILE}.new ${FILE}
    if [ `egrep -c log_ftp_protocol ${FILE}` == 0 ]; then 
        echo "log_ftp_protocol=YES" >> ${FILE} 
    fi 
    chown root:root $FILE 
    chmod 0600      $FILE 
    
    
else 
     echo "OK - No /etc/vsftpd.conf." 
fi 
 

# 6.3 Confirm Permissions On System Log Files

echo "Some errors MAY appear here for directories, logs and/or files not installed 
on this system." 
cd /var/log 
 
# Part 1 
echo "Extra---Ensure the btmp log file for 'lastb' is in place and with proper permissions." 

touch /var/log/btmp 
chown root:root  /var/log/btmp 

 
echo "Before listing of the log directory [explicit]." 
#ls -la /var/log 
 
# Part 2 
echo "LogPerms Part 1." 
for LogFile in \
    boot.log         \
    cron             \
    dmesg            \
    ksyms            \
    httpd            \
    maillog          \
    mailman          \
    messages         \
    news             \
    pgsql            \
    rpmpkgs          \
    sa               \
    samba            \
    scrollkeeper.log \
    secure           \
    spooler          \
    squid            \
    vbox
do 
    # This check allows only entries that exist to have permissions set. 
    # Visually cleaner for the person running it. 
    if [ -e ${LogFile} ]; then 
         # Utilizing recursive here is harmless when applied to a single file. 
         chmod -R  o-rwx  ${LogFile}* 
    
	
    fi 
done 
echo "LogPerms Part 2." 
for LogFile in \
    boot.log          \
    cron              \
    dmesg             \
    gdm               \
    httpd             \
    ksyms             \
    lastlog           \
    maillog           \
    mailman           \
    messages          \
    news              \
    pgsql             \
    rpmpkgs           \
    samba             \
    sa                \
    scrollkeeper.log  \
    secure            \
    spooler           \
    squid             \
    vbox 
do 
    if [ -e ${LogFile} ]; then 
         chmod -R  g-w  ${LogFile}* 

		 
    fi 
done 
 
echo "LogPerms Part 3." 
for LogFile in \
    boot.log         \
    cron             \
    httpd            \
    maillog          \
    mailman          \
    messages         \
    pgsql            \
    sa               \
    samba            \
    secure           \
    spooler 
do 
    if [ -e ${LogFile} ]; then 
         chmod -R  g-rx  ${LogFile}* 

		 
    fi 
done 
 
echo "LogPerms Part 4." 
for LogFile in \
    gdm        \
    httpd      \
    news       \
    samba      \
    squid      \
    sa         \
    vbox 
do 
    if [ -e ${LogFile} ]; then 
         chmod -R  o-w  ${LogFile}* 

		 
    fi 
done 

echo "LogPerms Part 5." 
for LogFile in \
    httpd      \
    samba      \
    squid      \
    sa 
do 
    if [ -e ${LogFile} ]; then 
         chmod -R  o-rx  ${LogFile}* 
    
	
    fi 
done 
 
echo "LogPerms Part 6." 
for LogFile in \
    kernel     \
    lastlog    \
    mailman    \
    syslog     \
    loginlog 
do 
    if [ -e ${LogFile} ]; then 
         chmod -R  u-x  ${LogFile}* 
    
	
    fi 
done 
 
echo "LogPerms Part 7." 
# Removing group write permissions to btmp and wtmp 
chgrp utmp btmp 
chmod g-w btmp 
chgrp utmp wtmp 
chmod g-w wtmp 






chown root:root /etc/rc.d/rc.sysinit 
 
chmod 0700      /etc/rc.d/rc.sysinit 


 
echo "LogPerms Part 8." 
[ -e news ]    && chown -R news:news news 
[ -e pgsql ]   && chown postgres:postgres pgsql 
[ -e squid ]   && chown -R squid:squid squid 
#[ -e lastlog ] && chmod 0600 lastlog 
chown -R root:root . 
echo "" 
 
echo "Follow-on listing of the log directory [explicit]." 
ls -la /var/log 


# 6.4 Configure syslogd to Send Logs to a Remote LogHost
# I have nothing in place for this yet, will have to revisit


# 7 File and Directory Permissions/Access
# 7.1 Add 'nodev' Option To Appropriate Partitions In /etc/fstab
# Skip this requirement in RHEL6 as it breaks /etc/fstab















# 7.2 Add 'nosuid' and 'nodev' Option For Removable Media In /etc/fstab
# Part 1 
# Skip this requirement in RHEL6 as it breaks /etc/fstab










  
 
# Part 2 
fdiPATH='unknown' 
if [ -e /usr/share/hal/fdi/95userpolicy ]; then 
     # Apply this to RHEL AS4 system 
     fdiPATH="/usr/share/hal/fdi/95userpolicy" 
else 
     if [ -e /usr/share/hal/fdi/policy/20thirdparty ]; then 
          # apply this for RHEL5 
          fdiPATH="/usr/share/hal/fdi/policy/20thirdparty" 
     fi 
fi 
if [ "$fdiPATH" == 'unknown' ]; then 
     echo "Neither path was available, fdi for hal NOT secured." 
     echo "RHEL AS4: /usr/share/hal/fdi/95userpolicy" 
     echo "RHEL5 and RHEL 6:    /usr/share/hal/fdi/polilcy/20thirdparty" 
else 
     echo "Placing floppycdrom.fdi at: ($fdiPATH)." 
     cat <<END_SCRIPT >> $fdiPATH/floppycdrom.fdi 
<?xml version="1.0" encoding="ISO-8859-1"?> <!-- -*- SGML -*- --> 
<deviceinfo version="0.2"> 
  <!-- Default policies merged onto computer root object  --> 
  <device> 
    <match key="info.udi" string="/org/freedesktop/Hal/devices/computer"> 
      <merge key="storage.policy.default.mount_option.nodev" 
type="bool">true</merge> 
      <merge key="storage.policy.default.mount_option.nosuid" 
type="bool">true</merge> 
    </match> 
  </device> 
</deviceinfo> 
END_SCRIPT
     chown root:root   $fdiPATH/floppycdrom.fdi 
     chmod 0640        $fdiPATH/floppycdrom.fdi 
     echo "Established $fdiPATH/floppycdrom.fdi" 
fi 


# 7.3 Disable User-Mounted Removable File Systems

cd /etc/security 
   CONS_PERM_FILE="console.perms" 
   DEF_FILE="console.perms.d/50-default.perms" 
   # If the test below passes, the 2nd file is changed, not the first. 
   # Need to protect both. 
   test -f $DEF_FILE && CONS_PERM_FILE="$DEF_FILE" 
# Each entry listed below will NOT be commented out in the "console.perms" file. 
# The remaining entries in that file WILL be commented out and thus disabled 
# post-reboot. 
# Further, "memstick" and "diskonkey" were not part of the original CIS 
# specification to be left alone, but have been included to tailor the hardened 
# build for usage of normal system USB requirements (such as keyboards and mice). 
awk '( $1 == "<console>" ) && ( $3 !~/sound|fb|kbd|joystick|v4l|mainboard|gpm|scanner|memstick|diskonkey/ ) \
    { $1 = "#<console>" }; { print }' ${CONS_PERM_FILE} > $CONS_PERM_FILE.new
mv $CONS_PERM_FILE.new $CONS_PERM_FILE
# Virgin default permissions were 0644 & 0600 respectively...  Just noting the difference
chown root:root $CONS_PERM_FILE 
chmod 0600      $CONS_PERM_FILE 



# 7.4 Verify passwd, shadow, and group File Permissions

chown root:root /etc/group /etc/gshadow /etc/passwd /etc/shadow 
chmod 0644 /etc/group /etc/passwd 
chmod 0000 /etc/gshadow /etc/shadow 
 

# 7.5 Ensure World-Writable Directories Have Their Sticky Bit Set
# skip this section, no changes will be made

for PART in `awk '( $3 ~ "ext[234]" ) { print  $2 }'  /etc/fstab`; 
do 
     find $PART -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print 
done 

# 7.6 Find Unauthorized World-Writable Files
# skip this section, no changes will be made

for PART in $( grep -v '^#' /etc/fstab | awk '( $3 ~ "ext[234]" ) { print $2 }' ); 
do 
    find $PART -xdev -type f  \( -perm -0002 -a ! -perm -1000 \) -print 
done 

# 7.7 Find Unauthorized SUID/SGID System Executables
# skip this section, no changes will be made

# 7.8 Find All Unowned Directories and Files
# skip this section, no changes will be made

# 7.9 Disable USB Devices
# Need to revisit this one as this may mess up the dc techs
# DEF_KERN=$( grubby --default-kernel) 
#grubby --update-kernel=$DEF_KERN --args="nousb" 


# 8.2 Create ftpusers Files

if [ -f /etc/ftpaccess ]; then 
   for NAME in `cut -d: -f1 /etc/passwd`; do 
       if [ `id -u $NAME` -lt 500 ]; then 
            echo $NAME >> /etc/ftpusers 
       fi 
   done 
   chown root:root /etc/ftpusers 
   chmod 0600      /etc/ftpusers 
 
   VSFTP_CONF="/etc/vsftpd/vsftpd.conf" 
     ALT_CONF="/etc/vsftpd/vsftpd.conf" 
   test -f $ALT_CONF && VSFTP_CONF=$ALT_CONF 
   if [ -e $VSFTP_CONF ] && ! grep -q "^userlist_deny=NO" $VSFTP_CONF; then 
        /bin/cp -fp /etc/ftpusers /etc/vsftpd.ftpusers 
        chown root:root /etc/vsftpd/vsftpd.conf 
        chgrp 0600      /etc/vsftpd/vsftpd.conf 
   fi 
else 
     echo "OK - No /etc/ftpaccess to tailor." 
fi 


# 8.3 Prevent X Server From Listening On Port 6000/tcp

if [ -e /etc/X11/xdm/Xservers ]; then 
    cd /etc/X11/xdm 
    awk '( $1 !~ /^#/ && $3 == "/usr/X11R6/bin/X" ) { $3 = $3 " -nolisten tcp" }; 
    { print }' Xservers > Xservers.new
mv Xservers.new Xservers
    chown root:root Xservers 
    chmod 0444      Xservers 
else 
    echo "No /etc/X11/xdm/Xservers file to secure." 
fi 
if [ -d /etc/X11/xinit ]; then 
    cd /etc/X11/xinit 
    if [ -e xserverrc ]; then 
         echo "Fixing /etc/X11/xinit/xserverrc" 
         awk '/X/ && !/^#/ { print $0 " :0 -nolisten tcp \\\$@"; next }; \
         { print }' xserverrc > xserverrc.new
mv xserverrc.new xserverrc
    else 
         cat <<END_SCRIPT > xserverrc 
#!/bin/bash 
exec X :0 -nolisten tcp \$@ 
END_SCRIPT
    fi 
    chown root:root xserverrc 
    chmod 0755      xserverrc 
else 
    echo "No /etc/X11/xinit file to secure." 
fi 


# 8.4 Restrict at/cron To Authorized Users

# With x.allow only users listed can use 'at' or 'cron' 
# {where 'x' indicates either 'at' or 'cron'} 
# Without x.allow then x.deny is checked, members of x.deny are excluded 
# Without either (x.allow and x.deny), then only root can use 'at' and 'cron' 
# At a minimum x.allow should exist and list root 
#echo "Attempting to list the following files for the 'before' picture." 
#echo "Any 'errors' are alright, as we are simply looking to see what exists." 
#ls -la /etc/at.allow /etc/at.deny /etc/cron.allow /etc/cron.deny 
for file in /etc/at.deny /etc/cron.deny
do
rm -f $file
done

# allow root to run cronjob only 
echo  root  >  /etc/at.allow 
echo  root  >  /etc/cron.allow 
chown  root:root  /etc/at.allow  /etc/cron.allow 
chmod  0400       /etc/at.allow  /etc/cron.allow 

# 8.5 Restrict Permissions On crontab Files

ls -lad /etc/cron* /var/spool/cron* 
chown  root:root  /etc/crontab 
chmod  0400       /etc/crontab 
chown  -R  root:root  /var/spool/cron 
chmod  -R  go-rwx     /var/spool/cron 
cd /etc 
chmod 700 /etc/cron.weekly
chmod 700 /etc/cron.hourly
chmod 700 /etc/cron.daily
chmod 700 /etc/cron.monthly
chmod 700 /etc/cron.d

# 8.6 Restrict Root Logins To System Console

echo ttyS0 > /etc/securetty 
echo ttyS1 >> /etc/securetty 

echo console >> /etc/securetty 
# These are acceptable for the GUI and runlevel 3, when trimmed down to 6 
for i in `seq 1 6`; do 
     echo vc/$i >> /etc/securetty 
done

for i in `seq 1 6`; do
     echo tty$i >> /etc/securetty
done

# 
#### Commented this out to be more secure as it denies root logins to the physical 
# TEXT console. 
#    Check pg 14 in Hardening Linux for additional safety in the /etc/inittab 
# file. 
# Do we want this as a required argument submitted on the command line? 
# 
#  for i in `seq 1 6`; do 
#       echo tty$i >> /etc/securetty 
#  done 
chown  root:root  /etc/securetty 
chmod  0400       /etc/securetty 



# Part 2 
# Second modification of gdm.conf, if it exists. 
if [ -e /etc/X11/gdm/gdm.conf ]; then 
     #### There is another file to consider: "/etc/X11/gdm/gdm.conf" 
     # "AllowRoot=true" should be set to false to prevent root from logging in to 
     # the gdm GUI. 
     # "AllowRemoteRoot=true" should be set to false to prevent root logins from 
     # remote systems. 
     # Doing this change is supportive of logging in as a regular user and using 
     # 'su' to get to root. 
     # Before allowing a reboot, ensure at least one account is created for a 
     # SysAdmin type. 
     cd /etc/X11/gdm 
     sed -i -e 's/AllowRoot=true/AllowRoot=false/'             \
         -e 's/AllowRemoteRoot=true/AllowRemoteRoot=false/' \
         -e 's/^#Use24Clock=false/Use24Clock=true/'   
         /etc/X11/gdm/gdm.conf
     chown root:root gdm.conf 
     chmod 0644      gdm.conf 
else 
    echo "No /etc/X11/gdm/gdm.conf file to further secure." 
fi 
 
# Part 3 
echo "The following is only required when a serial console is used for this server."
echo "Either of these would be added manually post-baseline compliance, depending" 
echo "on the COM port the serial cable is physically attached to." 
echo "#    echo ttyS0 >> /etc/securetty" 
echo "#    echo ttyS1 >> /etc/securetty" 


# 8.7 Set GRUB Password
# Most likely I'll be skipping this.

chown root:root /boot/grub/grub.conf 
chmod 0600      /boot/grub/grub.conf
chmod 0600      /boot/grub/menu.lst


# 8.8 Require Authentication For Single-User Mode

# Better to keep it unchanged

if [ "`grep -l sulogin inittab`" = "" ]; then 
     awk '{ print }; /^id:[0123456sS]:initdefault:/ { print "~~:S:wait:/sbin/sulogin" }' \
         /etc/inittab > /etc/inittab.tmp
     /bin/cp -pf /etc/inittab.tmp /etc/inittab 
     chown root:root inittab 
     chmod 0600      inittab 
     
     
else 
     echo "OK.  /etc/inittab already properly configured for Single-User" 
     echo "Mode Authentication." 
fi 


# 8.9 Restrict NFS Client Requests To Privileged Ports

echo "/etc/exports size is (`wc -c /etc/exports | cut -d' ' -f1`)." 
if [ `wc -c /etc/exports | cut -d' ' -f1` == 0 ]; then 
     echo "Ok - No changes were necessary to /etc/exports." 
else 
     echo "Size (for /etc/exports) is greater than 0" 
     ls -la  /etc/export* 
     perl -i.orig -pe 'next if (/^\s*#/ || /^\s*$/); 
          ($res, @hst) = split(" "); 
          foreach $ent (@hst) { 
          undef(%set); 
          ($optlist) = $ent =~ /\((.*?)\)/; 
          foreach $opt (split(/,/, $optlist)) { 
          $set{$opt} = 1; 
          } 
          delete($set{"insecure"}); 
          $set{"secure"} = 1; 
          $ent =~ s/\(.*?\)//; 
          $ent .= "(" .  join(",", keys(%set)) .  ")"; 
          } 
          $hst[0] = "(secure)" unless (@hst); 
          $_ = "$res\t" .  join(" ", @hst) .  "\n";'    /etc/exports 
fi 
chown root:root /etc/exports 
chmod 0644      /etc/exports 


# 8.10 Only Enable syslog To Accept Messages, If Absolutely Necessary
# Is this machine a log server, or does it need to receive Syslog messages via the network from other 
# systems? 


# 9 User Accounts and Environment
# 9.1 Block Login of System Accounts

echo "Setting the default login shell for the system accounts (uid less than 500) to /sbin/nologin" 
cd /etc 
for NAME in `/bin/awk -F: '0+$3 < 500 && $1 !~ /^[[:space:]]*(#.*|root|sync|shutdown|halt|admin|dpadmin|dpadmin2|dpadmin3|dpscanner|clientadmin|ec2-user|centos)$/ && $7 !~ /^\/sbin\/nologin$/ {print $1}' /etc/passwd`; do 
         usermod -L -s /sbin/nologin $NAME 
done 

chown root:root /etc/passwd 
chmod 0644      /etc/passwd 

chown root:root  /etc/shadow 
chmod 0000       /etc/shadow 



# 9.2 Verify That There Are No Accounts With Empty Password Fields
# This will only display info..

#awk -F: '( $2 == "" ) { print $1 }' /etc/shadow


# 9.3 Set Account Expiration Parameters On Active Accounts

# The login.defs manpage indicates these functions are now # all handled by PAM. 
# This changes the defaults applicable to new accounts added to the system after 
# this point. 
cd /etc 
awk  '($1 ~ /^PASS_MAX_DAYS/)  { $2="90" } 
      ($1 ~ /^PASS_MIN_DAYS/)  { $2="7" } 
      ($1 ~ /^PASS_WARN_AGE/)  { $2="14" } 
      ($1 ~ /^PASS_MIN_LEN/)   { $2="9" } 
      { print }' login.defs  >  login.defs.new
mv login.defs.new login.defs
useradd  -D  -f  7 
# This applies the same basis of changes to existing accounts. 
# -m: (7)  The number of days between permitted password changes. 
# -M: (90) The maximum number of days a password is valid. 
# -W: (14) The maximum number of days of advanced warning before a password is no 
# longer valid. 
# -I: (7)  The maximum number of days of inactivity, after a password has expired,  
# before the account is locked. 
for  NAME  in  `cut  -d:  -f1  /etc/passwd`;  do 
                uid=`id  -u  $NAME` 
                if  [  $uid  -ge  500  -a  $uid  !=  65534 ];  then 
                       chage  -m  7  -M  90  -W  14  -I  7  $NAME 
                fi 
done 
cat <<END_SCRIPT  >> login.defs 
 
# The following 2 lines added, per CIS Red Hat Enterprise Linux Benchmark sec 9.3 
# Establish a forced five-second minimum delay between failed logins 
FAIL_DELAY  5 
END_SCRIPT
chown  root:root  login.defs 
chmod  0640       login.defs 


# 9.4 Verify No Legacy '+' Entries Exist In passwd, shadow, And group Files

# Do a context specific diff to only show differences related to having plus signs 
# in the file. 
# Otherwise the output is too much 
grep -v ^+:   /etc/group     > /etc/group.tmp 
grep -v ^+:   /etc/gshadow   > /etc/gshadow.tmp 
grep -v ^+:   /etc/passwd    > /etc/passwd.tmp 
grep -v ^+:   /etc/shadow    > /etc/shadow.tmp 
mv /etc/group.tmp /etc/group
mv /etc/gshadow.tmp /etc/gshadow
mv /etc/passwd.tmp /etc/passwd
mv /etc/shadow.tmp /etc/shadow

chown root:root /etc/group /etc/gshadow /etc/passwd /etc/shadow
chmod 0644 /etc/group
chmod 0000 /etc/gshadow /etc/shadow


# 9.5 No '.' or Group/World-Writable Directory In Root's $PATH
# skip this section


# 9.6 User Home Directories Should Be Mode 0750 or More Restrictive

for DIR in `awk -F: '( $3 >= 500 ) { print $6 }' /etc/passwd | grep -v soap`; do
    if [ $DIR != /var/lib/nfs ]; then 
         chmod -R g-w   $DIR 
         chmod -R o-rwx $DIR 
    fi 
done 


# 9.7 No User Dot-Files Should Be World-Writable

for DIR in `awk -F: '($3 >= 500) { print $6 }' /etc/passwd`; do 
    for FILE in $DIR/.[A-Za-z0-9]*; do 
        if [ ! -h "$FILE" -a -f "$FILE" ]; then 
             chmod go-w "$FILE" 
        fi 
    done 
done 


# 9.8 Remove User .netrc Files

# 9.9 Set Default umask For Users

# skip this section

# PCI 8.5.15 Log out users idle for 15 minutes

cat << EOF > /etc/profile.d/tmout.sh
if [ -z "\$TMOUT" ]
then
        TMOUT=900
        export TMOUT
fi
EOF
chmod 644 /etc/profile.d/tmout.sh
chown root:root /etc/profile.d/tmout.sh

echo "export HISTTIMEFORMAT=\"%m/%d/%y %T\ \"" >> /etc/profile
echo "export HISTTIMEFORMAT=\"%m/%d/%y %T\ \"" >> /etc/bashrc

# fix file owner and permission issues
for file in /etc/bashrc /etc/csh.cshrc /etc/csh.login /etc/profile /root/.bash_profile /root/.bashrc /root/.cshrc /root/.tcshrc

do
if [ -e $file ];then
chown root:root $file
chmod 0400 $file
fi
done


# 9.10 Disable Core Dumps
awk '( $1 == "#*" && $2 == "soft" && $3 == "core" && $4 == "0" ) {  \
       print "*                soft    core            0";          \
       print "*                hard    core            0"; next  }  \
     { print }'  /etc/security/limits.conf > /etc/security/limits.conf.new
mv /etc/security/limits.conf.new /etc/security/limits.conf
chown root:root /etc/security/limits.conf
chmod 0644      /etc/security/limits.conf


# 10 Warning Banners
# 10.1 Create Warnings For Network And Physical Access Services

cat << EOF > /etc/issue

                           !!WARNING!!!
              READ THIS BEFORE ATTEMPTING TO LOGON

This system is for the use of authorized users only. Individuals
using this computer without authority, or in excess of their authority,
are subject to having all of their activities on this system monitored
and recorded by system personnel.  In the course of monitoring individuals
improperly using this system, or in the course of system maintenance,
the activities of authorized users may also be monitored.  Anyone using
this system expressly consents to such monitoring and is advised that if
such monitoring reveals possible criminal activity, system personnel may
provide the evidence of such monitoring to law enforcement officials.

EOF
 
# Create banners for network access: 
/bin/cp -pf /etc/issue  /etc/issue.net 
 
# Protect banner files: 
chown  root:root  /etc/issue  /etc/issue.net  /etc/motd 
chmod  0644       /etc/issue  /etc/issue.net  /etc/motd 

# 10.2 Create Warnings For GUI-Based Logins
# This is optional and we are not using GUI's

# 10.3 Create "authorized only" Banners For vsftpd, proftpd, If Applicable

cd /etc 
if [ -d vsftpd ]; then 
    cd vsftpd 
fi 
if [ -e vsftpd.conf ]; then 
   echo "ftpd_banner=Authorized users only.  All activity may be monitored and \
         reported." >> vsftpd.conf 
   chown root:root vsftpd.conf 
   chmod 0600      vsftpd.conf 
else 
   echo "OK - No vsftpd to change." 
fi 


# 11  Misc odds and ends
# 11.1 Configure and enable the auditd and sysstat services, if possible
# PCI:  Modified from CIS to meet PCI Requirements:


echo "Configure and enable the auditd and sysstat services, if possible." 
auditPATH='/etc/audit' 
# Part 1 
echo "Enforce auditing minimums." 
# This will enforce auditing minimums. 
cat <<END_SCRIPT   >         $auditPATH/audit.rules 
## This file contains the auditctl rules that are loaded 
## whenever the audit daemon is started via the initscripts. 
## The rules are simply the parameters that would be passed 
## to auditctl. 
## 
## First rule - delete all 
-D 
 
## Increase the buffers to 8192 to survive stress events. 
## Make this bigger for busy systems 
-b 8192
 
## Set failure mode to syslog notice {these two are mutually exclusive} 
-f 1 
 
## Set failure mode to panic {these two are mutually exclusive} 
## -f 2 
 
## NOTE: 
## 1) if this is being used on a 32 bit machine, comment out the b64 lines 
## 2) These rules assume that login under the root account is not allowed. 
## 3) It is also assumed that 500 represents the first usable user account. 
## 4) If these rules generate too much spurious data for your tastes, limit the 
##    the syscall file rules with a directory, like -F dir=/etc 
## 5) You can search for the results on the key fields in the rules 
## 
## (GEN002880: CAT II) The IAO will ensure the auditing software can 
## record the following for each audit event:  
##- Date and time of the event  
##- Userid that initiated the event  
##- Type of event  
##- Success or failure of the event  
##- For I&A events, the origin of the request (e.g., terminal ID)  
##- For events that introduce an object into a user’s address space, and 
##  for object deletion events, the name of the object, and in MLS 
##  systems, the object’s security level. 
## 
## Things that could affect time 
#-a always,exit -F arch=b32 -S adjtimex -S settimeofday -S stime -k time-change 
#-a always,exit -F arch=b64 -S adjtimex -S settimeofday -k time-change 
#-a always,exit -F arch=b32 -S clock_settime -k time-change 
#-a always,exit -F arch=b64 -S clock_settime -k time-change 
-w /etc/localtime -p wa -k time-change 
 
## Things that affect identity 
-w /etc/group -p wa -k identity 
-w /etc/passwd -p wa -k identity 
-w /etc/gshadow -p wa -k identity 
-w /etc/shadow -p wa -k identity 
-w /etc/security/opasswd -p wa -k identity 
 
## Things that could affect system locale 
-a exit,always -F arch=b32 -S sethostname -S setdomainname -k system-locale 
-a exit,always -F arch=b64 -S sethostname -S setdomainname -k system-locale 
-w /etc/issue -p wa -k system-locale 
-w /etc/issue.net -p wa -k system-locale 
-w /etc/hosts -p wa -k system-locale 
-w /etc/sysconfig/network -p wa -k system-locale 
 
## Things that could affect MAC policy 
-w /etc/selinux/ -p wa -k MAC-policy 
 
## The SysAdmin will configure the auditing system to audit the following events 
## for all users and root: 
## - Logon (unsuccessful and successful) and logout (successful) 
##   This is handled by pam, sshd, login, and gdm 
##   Might also want to watch these files if needing extra information 
-w /var/log/faillog -p wa -k logins 
-w /var/log/lastlog -p wa -k logins 
-w /var/log/tallylog -p wa -k logins 
 
##- Process and session initiation (unsuccessful and successful) 
## 
## The session initiation is audited by pam without any rules needed. 
## Might also want to watch this file if needing extra information 
-w /var/run/utmp -p wa -k session 
-w /var/log/btmp -p wa -k session 
-w /var/log/wtmp -p wa -k session 

-w /sbin/insmod -p x -k modules
-w /sbin/rmmod -p x -k modules
-w /sbin/modprobe -p x -k modules
 
##- Discretionary access control permission modification (unsuccessful 
## and successful use of chown/chmod) 

-a always,exit -F arch=b32 -S chmod -S fchmod -S fchmodat -F auid>=500 -F auid!=4294967295 -k perm_mod
-a always,exit -F arch=b64 -S chmod -S fchmod -S fchmodat -F auid>=500 -F auid!=4294967295 -k perm_mod
-a always,exit -F arch=b32 -S chown -S fchown -S fchownat -S lchown -F auid>=500 -F auid!=4294967295 -k perm_mod 
-a always,exit -F arch=b64 -S chown -S fchown -S fchownat -S lchown -F auid>=500 -F auid!=4294967295 -k perm_mod
-a always,exit -F arch=b32 -S setxattr -S lsetxattr -S fsetxattr -S removexattr -S lremovexattr -S fremovexattr -F auid>=500 -F auid!=4294967295 -k perm_mod
-a always,exit -F arch=b64 -S setxattr -S lsetxattr -S fsetxattr -S removexattr -S lremovexattr -S fremovexattr -F auid>=500 -F auid!=4294967295 -k perm_mod
 
##- Unauthorized access attempts to files (unsuccessful)  
-a always,exit -F arch=b32 -S creat -S open -S openat -S truncate -S ftruncate -F exit=-EACCES -F auid>=500 -F auid!=4294967295 -k access
-a always,exit -F arch=b32 -S creat -S open -S openat -S truncate -S ftruncate -F exit=-EPERM -F auid>=500 -F auid!=4294967295 -k access
-a always,exit -F arch=b64 -S creat -S open -S openat -S truncate -S ftruncate -F exit=-EACCES -F auid>=500 -F auid!=4294967295 -k access
-a always,exit -F arch=b64 -S creat -S open -S openat -S truncate -S ftruncate -F exit=-EPERM -F auid>=500 -F auid!=4294967295 -k access
 
##- Use of privileged commands (unsuccessful and successful) 
##  use find /bin -type f -perm -04000 2>/dev/null and put all those files in 
##  a rule like this 
-a always,exit -F path=/bin/ping -F perm=x -F auid>=500 -F auid!=4294967295 -k privileged
 
##- Use of print command (unsuccessful and successful)  
 
##- Export to media (successful) 
## You have to mount media before using it. You must disable all automounting 
## so that its done manually in order to get the correct user requesting the 
## export 
-a always,exit -F arch=b32 -S mount -F auid>=500 -F auid!=4294967295 -k mounts
-a always,exit -F arch=b64 -S mount -F auid>=500 -F auid!=4294967295 -k mounts
 
##- System startup and shutdown (unsuccessful and successful) 
 
##- Files and programs deleted by the user (successful and unsuccessful) 
-a always,exit -F arch=b32 -S unlink -S unlinkat -S rename -S renameat -F auid>=500 -F auid!=4294967295 -k delete
-a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -F auid>=500 -F auid!=4294967295 -k delete

##- Audit the loading and unloading of kernel modules
-a always,exit -F arch=b64 -S init_module -S delete_module -k modules
-a always,exit -F arch=b32 -S init_module -S delete_module -k modules

##- Audit setuid/setgid program
-a always,exit -F path=/sbin/pam_timestamp_check -F perm=x -F auid>=500 -F auid!=4294967295 -k privileged

##- All system administration actions  
##- All security personnel actions 
##  
## Look for pam_tty_audit and add it to your login entry point's pam configs. 
## If that is not found, use sudo which should be patched to record its 
## commands to the audit system. Do not allow unrestricted root shells or 
## sudo cannot record the action. 
-w /etc/sudoers.d/ -p wa -k privileged-actions
-w /etc/sudoers -p wa -k scope
-w /var/log/sudo.log -p wa -k actions 
 
## Optional - could indicate someone trying to do something bad or 
## just debugging 
#-a entry,always -F arch=b32 -S ptrace -k tracing 
#-a entry,always -F arch=b64 -S ptrace -k tracing 

## Optional - could be an attempt to bypass audit or simply legacy program 
#-a always,exit -F arch=b32 -S personality -k bypass 
#-a always,exit -F arch=b64 -S personality -k bypass 
 
## Put your own watches after this point 
# -w /your-file -p rwxa -k mykey 

## FOR PCI: 10.2.0.11
# -a exit,always -S stime -S acct -S reboot -S swapon -S settimeofday

## For PCI: 10.2.0.12
# -a exit,always -S setrlimit -S setdomainname -S sched_setparam -S sched_setscheduler

## For PCI: 10.2.0.13
# -a exit,always -S chmod -S fchmod -S chown -S chown32 -S fchown

## For PCI: 10.2.0.14
# -a exit,always -S fchown32 -S lchown -S lchown32

## For PCI: 10.2.3.1
# -w /var/log/audit/

## For PCI: 10.2.3.2
# -w /etc/audit/auditd.conf

## For PCI: 10.2.3.3
# -w /etc/audit/audit.rules

## For PCI: 10.2.4.1
# -a exit,always -S open -F success=0

## For PCI: 10.2.7.1
# -a exit,always -S unlink -S rmdir
 
## Make the configuration immutable - reboot is required to change audit rules 
-e 2

END_SCRIPT
chown root:root $auditPATH/audit.rules 
chmod 0600      $auditPATH/audit.rules 
 
# Part 2 
echo "Strengthen auditd.conf settings." 
sed -e "s/num_logs = 4/num_logs = 5/"                            \
    -e "s/max_log_file = 8/max_log_file = 100/"                  \
    -e "s/space_left = 75/space_left = 125/"                     \
    -e "s/admin_space_left = 50/admin_space_left = 75/"          \
    -e "s/space_left_action = SYSLOG/space_left_action = email/" \
       $auditPATH/auditd.conf > $auditPATH/auditd.conf.new
mv $auditPATH/auditd.conf.new $auditPATH/auditd.conf
chown root:root $auditPATH/auditd.conf 
# Default permissions were originally 0640. 
chmod 0600      $auditPATH/auditd.conf 
 
# Part 3 
echo "Make auditd applicable across reboots." 
echo "-------" 
chkconfig --level 35 auditd  on 
chkconfig --level 35 sysstat on 
echo "-------" 
# Enable auditd and sysstat services, good even if rebooting soon 
service auditd  restart 
service sysstat restart 
echo "-------" 

# the following services should be keep enabled
# cpuspeed crond easyagent-tcp irqbalance lvm2-monitor messagebus network chrony rawdevices restorecond sshd rsyslog vmware-tools
for service in `echo "cpuspeed crond easyagent-tcp irqbalance lvm2-monitor messagebus network chrony rawdevices restorecond sshd rsyslog vmware-tools iptables ip6tables docker"`
do
if [ -a /etc/init.d/$service ]
then
echo "Keep this service: $service enabled."
chkconfig --level 35 $service on
echo "Done ..."
echo ++++++++++
fi
done
echo "" 


# 11.2 Verify no duplicate userIDs exist

echo "Verify no duplicate userIDs exist." 
#dup username 
x=`cut -f1 -d: /etc/passwd | sort | uniq -d | tr "\n" " "` 
if [ "x$x" != "x" ] 
then 
echo "The following duplicate usernames found: $x" 
fi 
#dup uid 
x=`cut -f3 -d: /etc/passwd | sort | uniq -d | tr "\n" " "` 
if [ "x$x" != "x" ] 
then 
echo "The following duplicate uids found: $x" 
fi 
#dup groupname 
x=`cut -f1 -d: /etc/group | sort | uniq -d | tr "\n" " "` 
if [ "x$x" != "x" ] 
then 
echo "The following duplicate group names found: $x" 
fi 
#dup uid 
x=`cut -f3 -d: /etc/group | sort | uniq -d | tr "\n" " "` 
if [ "x$x" != "x" ] 
then 
echo "The following duplicate gids found: $x" 
fi 
echo "" 


# 11.3 Force permissions on root's home directory to be 0700

ls -lad /root 
chown root:root /root 
chmod 0700      /root 
ls -lad /root 


# 11.4 Utilize PAM to Enforce UserID password complexity
# PCI:  Modified requirements for 8.5.10 - 8.5.14

cd /etc/pam.d 

cat << EOF > /etc/pam.d/system-auth-ac
auth        required      pam_env.so
# PCI 8.5.13 Limit repeated access attempts after 6 failed attempts
# PCI 8.5.14 Set lockout duration to 30 minutes after 6 failed attempts
#auth        required      pam_tally2.so onerr=fail deny=6 unlock_time=1800
auth        required      pam_faillock.so authfail deny=6 unlock_time=1800
auth        sufficient    pam_unix.so try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_succeed_if.so uid < 500 quiet
account     required      pam_permit.so
account     required      pam_tally2.so

# PCI 8.5.10 Require a minimum password length of 8 characters
# PCI 8.5.11 Use passwords containing both numeric and alphabetic characters
password    required      pam_passwdqc.so min=disabled,disabled,8,8,8 passphrase=3 match=4 similar=deny random=0 enforce=everyone retry=3
# PCI 8.5.12 New password can not be the same as any of the last 4 passwords
# CIS RHEL6 security hardening standard 6.3.5: Upgrade Password Hashing Algorithm to SHA-512.
password    sufficient    pam_unix.so remember=4 sha512 shadow try_first_pass use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
EOF

chown root:root /etc/pam.d/system-auth-ac 
chmod 0644      /etc/pam.d/system-auth-ac



echo "Protecting a hardened copy of /etc/pam.d/system-auth-ac" 
/bin/cp -pf /etc/pam.d/system-auth-ac  /etc/pam.d/system-auth-ac.HardenedProtectedCopy 

chattr +i /etc/pam.d/system-auth-ac.HardenedProtectedCopy 


# update /etc/sysconfig/authconfig to disable pam_cracklib and enable pam_passwdqc
sed -i -e 's/USECRACKLIB=yes/USECRACKLIB=no/g' -e 's/USEPASSWDQC=no/USEPASSWDQC=yes/g' /etc/sysconfig/authconfig


cd /etc/pam.d/
sed -i 's/nullok//g' /etc/pam.d/password-auth-ac
sed -i '/quiet_success/a \auth        requisite     pam_faillock.so authfail deny=6 unlock_time=1800' /etc/pam.d/password-auth-ac
sed -i 's/sha512/sha512 remember=4/' /etc/pam.d/password-auth-ac

echo "Protecting a hardened copy of /etc/pam.d/password-auth-ac"
/bin/cp -pf /etc/pam.d/password-auth-ac  /etc/pam.d/password-auth-ac.HardenedProtectedCopy
chattr +i /etc/pam.d/password-auth-ac.HardenedProtectedCopy

cat << EOF > /etc/pam.d/sshd
#%PAM-1.0
auth       required     pam_sepermit.so
# PCI 8.5.13 Limit repeated access attempts after 6 failed attempts
# PCI 8.5.14 Set lockout duration to 30 minutes after 6 failed attempts
auth        required      pam_tally2.so onerr=fail deny=6 unlock_time=1800
auth       include      password-auth
account    required     pam_nologin.so
account    include      password-auth
password   include      password-auth
# pam_selinux.so close should be the first session rule
session    required     pam_selinux.so close
session    required     pam_loginuid.so
# pam_selinux.so open should only be followed by sessions to be executed in the user context
session    required     pam_selinux.so open env_params
session    optional     pam_keyinit.so force revoke
session    include      password-auth
EOF

chown root:root /etc/pam.d/sshd

echo "Protecting a hardened copy of /etc/pam.d/sshd"
/bin/cp -pf /etc/pam.d/sshd  /etc/pam.d/sshd.HardenedProtectedCopy
chattr +i /etc/pam.d/sshd.HardenedProtectedCopy
# 11.5 Ensure perms on man and doc pages prevent modification by unprivileged users

echo "Restrict permissions to 0644 on /usr/share/man and /usr/share/doc content" 

for DIR in /usr/share/doc /usr/local/share/doc /usr/share/man /usr/local/share/man

do
if [ -d $DIR ];then
chmod -R go-w $DIR
fi
done


################
# PCI SPECIFIC #
################

# PCI: 2.2.3.34 Verify that 'immutable' flag is added to /etc/fstab

chattr +i /etc/fstab


# PCI: 2.2.3.39 Find SUID System Executables and remove SUID bit

for PART in `awk '($1 !~ /#/ && $3 ~ "ext2|ext3|reiserfs|ext4") { print $2 }' /etc/fstab`; do find $PART \( -perm -04000 \) -type f -xdev -print 2>/dev/null | sort >> /tmp/CIS_7.7_f1; done; for FILE in /bin/mount /bin/ping /bin/ping6 /bin/su /bin/traceroute /bin/traceroute6 /bin/umount /media/.hal-mtab-lock /sbin/mount.nfs /sbin/mount.nfs4 /sbin/netreport /sbin/pam_timestamp_check /sbin/pwdb_chkpwd /sbin/umount.nfs /sbin/umount.nfs4 /sbin/unix_chkpwd /usr/X11R6/bin/Xorg /usr/bin/at /usr/bin/chage /usr/bin/chfn /usr/bin/chsh /usr/bin/crontab /usr/bin/cu /usr/bin/gataxx /usr/bin/glines /usr/bin/gnibbles /usr/bin/gnobots2 /usr/bin/gnomine /usr/bin/gnotravex /usr/bin/gnotski /usr/bin/gpasswd /usr/bin/gtali /usr/bin/iagno /usr/bin/kgrantpty /usr/bin/kon /usr/bin/kpac_dhcp_helper /usr/bin/locate /usr/bin/lockfile /usr/bin/lppasswd /usr/bin/mahjongg /usr/bin/newgrp /usr/bin/newvc /usr/bin/passwd /usr/bin/rcp /usr/bin/rlogin /usr/bin/rsh /usr/bin/same-gnome /usr/bin/screen /usr/bin/sg /usr/bin/slocate /usr/bin/sperl5.8.5 /usr/bin/ssh-agent /usr/bin/sudo /usr/bin/sudoedit /usr/bin/uucp /usr/bin/uuname /usr/bin/uuname /usr/bin/uustat /usr/bin/uux /usr/bin/wall /usr/bin/write /usr/bin/xterm /usr/kerberos/bin/ksu /usr/lib/amanda/amqde /usr/lib/amanda/calcsize /usr/lib/amanda/dumper /usr/lib/amanda/killpgrp /usr/lib/amanda/planner /usr/lib/amanda/rundump /usr/lib/amanda/runtar /usr/lib/cyrus-imapd/deliver /usr/lib/mc/cons.saver /usr/lib/mgetty+sendfax/faxq-helper /usr/lib/news/bin/inndstart /usr/lib/news/bin/rnews /usr/lib/news/bin/startinnfeed /usr/lib/vte/gnome-pty-helper /usr/libexec/openssh/ssh-keysign /usr/libexec/pt_chown /usr/libexec/utempter/utempter /usr/lib64/vte/gnome-pty-helper /usr/bin/locate /usr/bin/screen /usr/bin/Xorg /usr/lib/squid/ncsa_auth /usr/lib/squid/pam_auth /usr/libexec/libvirt_proxy /usr/libexec/mc/cons.saver /usr/libexec/openssh/ssh-keysign /usr/libexec/utempter/utempter /usr/sbin/amcheck /usr/sbin/ccreds_validate /usr/sbin/exim /usr/sbin/gnome-pty-helper /usr/sbin/lockdev /usr/sbin/postdrop /usr/sbin/postqueue /usr/sbin/sendmail.sendmail /usr/sbin/suexec /usr/sbin/userhelper /usr/sbin/userisdnctl /usr/sbin/usernetctl /usr/sbin/utempter /usr/sbin/uucico /usr/sbin/uuxqt /usr/sbin/utempter; do grep -v ${FILE} /tmp/CIS_7.7_f1 > /tmp/CIS_7.7_f2; /bin/cp -pf /tmp/CIS_7.7_f2 /tmp/CIS_7.7_f1; done; x=`wc -c /tmp/CIS_7.7_f1 | cut -d" " -f1`; if [ $x != 0 ]; then sed 's/^.*/ls -lad &/' /tmp/CIS_7.7_f1 > /tmp/CIS_7.7_f2; echo "The following files have the SUID bit set. Removing the SUID bit on them:"; /bin/bash /tmp/CIS_7.7_f2; fi; 

for i in `cat /tmp/CIS_7.7_f2 |awk '{print $3}'`; do chmod u-s $i; done  ; rm -f /tmp/CIS_7.7_f1 /tmp/CIS_7.7_f2
echo "Done."


# PCI: 2.2.3.45-46 Verify wu-ftpd and vsftp FTP Users Settings
# This restricts system accounts from transferring data via ftp

SYSACCT="daemon ident bin sys adm smtp uucp nuucp listen lpd lp ingres oracle oracle7 oracle8 oracle9 oracle9i informix news nobody nobody4 noaccess sybase tivoli www ftp tftp hpdb sshd invscout gccs secm an sysadmin install staff COE tracker predmail snmp inews smmsp sm spmadmin share BIF GCCS JDISS SA SSO SM ftp gccsrv gtnsmint irc Imadmin imadmin netadmin oradba halt mail rpm vcsa nscd rpc rpcuser mailnull pcap xfs chrony gdm sync shutdown halt operator gopher nfsnobody dbus haldaemon netdump webalizer pvm mysql mailman dovecot cyrus amanda pegasus HPSMH hpsmh webadmind webadmin webservd avahi beagleidx hsqldb postfix hacluster named canna wnn fax quagga htt root"
for userid in $SYSACCT; do echo $userid >> /etc/ftpusers; done



# PCI: 7.1.1.8 Verify /etc/cups/cupsd.conf Permissions
if [ -e /etc/cups/cupsd.conf ]; then
chmod 600 /etc/cups/cupsd.conf
chown lp:sys /etc/cups/cupsd.conf
fi

# PCI: 7.1.1.13 - Verify /var/log/btmp Permissions
if [ -e /var/log/btmp ];then
#chmod 600 /var/log/btmp
chown root:utmp /var/log/btmp
fi

# PCI: 7.1.1.49 - Verify /etc/security/console.perms Permissions
if [ -e /etc/security/console.perms ];then
chmod 600 /etc/security/console.perms
chown root:root /etc/security/console.perms
fi

# PCI: 7.1.1.65 - Verify /etc/pam.d/system-auth-ac Permissions
if [ -e /etc/pam.d/system-auth-ac ];then
chmod 644 /etc/pam.d/system-auth-ac
chown root:root /etc/pam.d/system-auth-ac
fi

# PCI: 7.1.1.94 - Ensure Perms on man and doc pages prevent modifications by unprivileged users
#for i in `find /usr/share/doc /usr/local/share/man /usr/share/man /usr/local/share/doc -follow  \( ! -perm -u+r -o ! -perm -u+w -o ! -perm -g+r -o ! -perm -o+r -o -perm -u+x -o -perm -g+w -o -perm -g+x -o -perm -o+w -o -perm -o+x \) 2>/dev/null`; do chmod 644 $i; done

# PCI: 8.5.9 - Change user passwords at least every 90 days
cat <<END_SCRIPT  > /etc/default/useradd
# useradd defaults file
GROUP=100
HOME=/home
INACTIVE=7
EXPIRE=
SHELL=/bin/bash
SKEL=/etc/skel
CREATE_MAIL_SPOOL=yes
END_SCRIPT

# PCI: 8.5.11.1 - Passwords Must Contain at Least One Numeric Character
# PCI: 8.5.11.2 - Passwords Must Contain at Least One Alphabetic Character
##
## Refer to CIS section where this was corrected:
## 11.4 Utilize PAM to Enforce UserID password complexity
##

# PCI: 8.5.15 - If a session is idle for 15 minutes, require user to log back in.
# Due to permissions, handled this up in CIS section: # 9.9 Set Default umask For Users

# PCI: 10.2.0.10 - 10.2.0.14 audit.rules
# PCI: 10.2.3.1 - 10.2.3.3
# PCI: 10.2.4.1
# PCI: 10.2.7.1
##
## Refer to CIS section where this was corrected:
## 11.1 Configure and enable the auditd and sysstat services, if possible

# PCI: 10.2 Audit Trail Automation
# The following line satisfies requirements:
# PCI: 10.2.0.2 - 10.2.0.9

cat << EOF >> /etc/rsyslog.conf

# Configuring the rsyslog default file permissions to 0640
\$FileCreateMode 0640

# Datapipe Event Management
\$template datapipe,"%timegenerated%,%HOSTNAME%,%syslogtag%,%msg%\n"
# kern.warning;*.err;authpriv.none;*.info;mail.none;cron.none;*.emerg;local7.*            @@x.x.x.x;datapipe
EOF

# Check in all changes made by PCI script into RCS:
for FILE in \
        /etc/ssh/ssh_config \
        /etc/ssh/sshd_config \
        /etc/crontab \
        /etc/hosts.deny \
        /etc/hosts.allow \
        /etc/rc.d/init.d/functions \
	/etc/sysconfig/authconfig \
        /etc/sysconfig/init \
        /etc/sysconfig/sendmail \
        /etc/sysconfig/selinux \
        /etc/selinux/config \
        /etc/inittab \
        /etc/sysctl.conf \
        /etc/rsyslog.conf \
        /etc/vsftpd.conf \
        /etc/rc.d/rc.sysinit \
        /etc/fstab \
        /usr/share/hal/fdi/95userpolicy \
        /usr/share/hal/fdi/polilcy/20thirdparty \
        /etc/ftpaccess \
        /etc/ftpusers \
        /etc/vsftpd/vsftpd.conf \
        /etc/vsftpd.ftpusers \
        /etc/X11/xdm/Xservers \
        /etc/X11/xinit/xserverrc \
        /etc/X11/xinit \
        /etc/at.allow \
        /etc/at.deny \
        /etc/cron.allow \
        /etc/cron.deny \
        /etc/securetty \
        /etc/X11/gdm/gdm.conf \
        /boot/grub/grub.conf \
        /etc/inittab \
        /etc/exports \
        /etc/default/useradd \
        /etc/passwd \
        /etc/shadow \
        /etc/group \
        /etc/gshadow \
        /etc/login.defs \
        /etc/bashrc \
        /etc/csh.cshrc \
        /etc/csh.login \
        /etc/profile \
        /etc/skel/.bashrc \
        /root/.bash_profile \
        /root/.bashrc \
        /root/.bash_profile \
        /root/.cshrc \
        /root/.tcshrc \
        /etc/security/limits.conf \
        /etc/pam.d/su \
        /etc/security/access.conf \
        /etc/issue \
        /etc/motd \
        /etc/issue.net \
        /etc/vsftpd.conf \
        /etc/audisp/plugins.d/syslog.conf \
        /etc/audit/audit.rules \
        /etc/audit/auditd.conf \
        /etc/pam.d/system-auth-ac \
        /etc/pam.d/password-auth-ac \
	/etc/pam.d/sshd
do
if [ -e $FILE ];then
ci -l -wsecurity $FILE <<EOF
Datapipe PCI-DSS Hardening Standards Applied.
.
EOF
fi
done

# Set Default Core Dumps
echo "ulimit -S -c 0 > /dev/null 2>&1" >> /etc/profile

# Fix permissions of files as RCS will change the files to writable by the owner:
# This will be corrected in next version of this script.

if [ -e /etc/sysconfig/init ];then
chmod 755 /etc/sysconfig/init
chown root:root /etc/sysconfig/init
fi

if [ -e /etc/inittab ];then
chmod 600 /etc/inittab
chown root:root /etc/inittab
fi

if [ -e /etc/sysctl.conf ];then
#chmod 600 /etc/sysctl.conf
chown root:root /etc/sysctl.conf
fi

if [ -e /etc/rc.d/rc.sysinit ];then
chmod 700 /etc/rc.d/rc.sysinit
chown root:root /etc/rc.d/rc.sysinit
fi

if [ -e /etc/rsyslog.conf ];then
chmod 600 /etc/rsyslog.conf
chown root:root /etc/rsyslog.conf
fi

if [ -e /etc/at.allow ];then
chmod 400 /etc/at.allow
chown root:root /etc/at.allow
fi

if [ -e /etc/cron.allow ];then
chmod 400 /etc/cron.allow
chown root:root /etc/cron.allow
fi

if [ -e /etc/crontab ];then
chmod 400 /etc/crontab
chown root:root /etc/crontab
fi

if [ -e /etc/securetty ];then
chmod 400 /etc/securetty
chown root:root /etc/securetty
fi

if [ -e /etc/login.defs ];then
chmod 640 /etc/login.defs
chown root:root /etc/login.defs
fi

if [ -e /etc/shadow ];then
chmod 000 /etc/shadow
chown root:root /etc/shadow
fi

if [ -e /etc/gshadow ];then
chmod 000 /etc/gshadow
chown root:root /etc/gshadow
fi

if [ -e /etc/profile ];then
chmod 444 /etc/profile
chown root:root /etc/profile
fi

if [ -e /etc/csh.login ];then
chmod 444 /etc/csh.login
chown root:root /etc/csh.login
fi

if [ -e /etc/csh.cshrc ];then
chmod 444 /etc/csh.cshrc
chown root:root /etc/csh.cshrc
fi

if [ -e /etc/bashrc ];then
chmod 444 /etc/bashrc
chown root:root /etc/bashrc
fi

if [ -e /root/.bashrc ];then
chmod 400 /root/.bashrc
chown root:root /root/.bashrc
fi

if [ -e /root/.cshrc ];then
chmod 400 /root/.cshrc
chown root:root /root/.cshrc
fi

if [ -e /root/.tcshrc ];then
chmod 400 /root/.tcshrc
chown root:root /root/.tcshrc
fi

if [ -e /root/.bash_profile ];then
chmod 400 /root/.bash_profile
chown root:root /root/.bash_profile
fi

if [ -e /etc/security/access.conf ]; then
chmod 640 /etc/security/access.conf
chown root:root /etc/security/access.conf
fi

if [ -e /etc/audit/auditd.conf ];then
chmod 600 /etc/audit/auditd.conf
chown root:root /etc/audit/auditd.conf
fi
# Modification to PCI - 8.5.9.2 Verify PASS_MAX_DAYS Setting for Non-system 
# Accounts.  This is for our Retina service and for general support issues.


# create ssh_access group and add DP users to ssh_access group
groupadd -g 599 ssh_access
###
for newusers in admin dpadmin dpadmin2 dpadmin3 clientadmin ec2-user centos
do
awk -F: '{print $1}' /etc/passwd | grep ^$newusers$
if [ $? -eq 0 ];then
usermod -a -G ssh_access $newusers
usermod -a -G wheel $newusers
chage -I -1 -m 7 -M -1 -E -1 $newusers
fi
done
###
for newusers in dpscanner
do
awk -F: '{print $1}' /etc/passwd | grep ^$newusers$
if [ $? -eq 1 ];then
useradd $newusers
usermod -a -G ssh_access $newusers
usermod -a -G wheel $newusers
chage -I -1 -m 7 -M -1 -E -1 $newusers
else
usermod -a -G ssh_access $newusers
usermod -a -G wheel $newusers
chage -I -1 -m 7 -M -1 -E -1 $newusers
fi
done
###
usermod -a -G wheel root
usermod -a -G ssh_access root

# CIS RHEL6 security hardening standard.
#1.1.14  Add nodev Option to /dev/shm Partition
#1.1.15 Add nosuid Option to /dev/shm Partition
#1.1.16 Add noexec Option to /dev/shm Partition
chattr -i /etc/fstab
sed -i '/^tmpfs[ \t]*\/dev\/shm[ \t]*tmpfs[ \t]*defaults/ s/defaults/nosuid,nodev,noexec,defaults/' /etc/fstab
chattr +i /etc/fstab

# CIS RHEL6 security hardening standard 6.2.11  Use Only Approved Cipher in Counter Mode
echo >> /etc/ssh/sshd_config
echo \# Use Only Approved Cipher in Counter Mode >> /etc/ssh/sshd_config
echo Ciphers aes128-ctr,aes192-ctr,aes256-ctr >> /etc/ssh/sshd_config
echo MACs hmac-sha2-256,hmac-sha2-512 >> /etc/ssh/sshd_config

# restrict ssh access to "ssh_access" group only
echo >> /etc/ssh/sshd_config
echo \# Restrict ssh access to \"ssh_access\" group only >> /etc/ssh/sshd_config
echo \# Please add user to ssh_access group if necessary: \"usermod -a -G ssh_access USERNAME\" >> /etc/ssh/sshd_config
echo AllowGroups ssh_access domain_users \"domain users\" >> /etc/ssh/sshd_config

chmod 600 /etc/ssh/sshd_config

# this is for TW policy 2.2.4.3 disable Ctrl-Alt-Delete
cd /etc/init/
sed -i 's/^start on control-alt-delete/#start on control-alt-delete/' /etc/init/control-alt-delete.conf
sed -i 's/^exec\ \/sbin\/shutdown\ \-r\ now\ \"Control-Alt-Delete pressed\"/#exec\ \/sbin\/shutdown\ \-r\ now\ \"Control-Alt-Delete pressed\"/' /etc/init/control-alt-delete.conf

cat << EOF > /etc/init/control-alt-delete.override
#
start on control-alt-delete
#
exec /bin/logger -p authpriv.notice -t init "Ctrl-Alt-Del was pressed and ignored"
EOF

chown root:root /etc/init/control-alt-delete.override
chmod 644 /etc/init/control-alt-delete.override

# this is for TW policy 7.1.1.134 Limit Access to the Root Account from SU
cd /etc/pam.d
sed -i '/^#auth[\ \t]*required[\ \t]*pam_wheel.so[\ \t]*use_uid$/ s/#auth/auth/' /etc/pam.d/su




#############################################
# additional security setting / configuration
# 1. add NOZEROCONF to /etc/sysconfig/network to get rid of the link-local route
#if [ X`grep NOZEROCONF /etc/sysconfig/network` = "X" ]; then echo "NOZEROCONF=yes" >> /etc/sysconfig/network; fi

# 2. set sa permission
cat << EOF > /etc/cron.d/set-sa-permission
1 * * * * root /usr/bin/find /var/log/sa -perm /g+r,o+r -exec /bin/chmod -R 600 {} \; > /dev/null 2>&1
EOF
chmod 600 /etc/cron.d/set-sa-permission
chown root:root /etc/cron.d/set-sa-permission
for i in {1..9};do touch /var/log/sa/sa0$i; touch /var/log/sa/sar0$i; done
for i in {10..31};do touch /var/log/sa/sa$i; touch /var/log/sa/sar$i; done
chmod -R 600 /var/log/sa

# 3. change default /var/log/wtmp attribute to 644
ci -l -wsecurity /etc/logrotate.conf <<EOF
State before upgrade to Datapipe PCI-DSS Hardening Standards.
.
EOF
sed -i 's/create 0664 root utmp/create 0644 root utmp/' /etc/logrotate.conf

# backup file after change
ci -l -wsecurity /etc/logrotate.conf <<EOF
Upgraded to Datapipe PCI-DSS Hardening Standards.
.
EOF

# This is for TW policy RHEL6 7.1.1.3
# Change permissions on the invalid log files found using the chmod u-x,g-wx,o-rwx
for LOGFILE in `find /var/log -type f \( ! -name secure \) -ls 2>/dev/null | awk '$3 !~ /^-..-.-----$/ {print $NF}'`
do
chmod u-x,g-wx,o-rwx $LOGFILE
done

# others: minor changes

if [ -d /var/lib/nfs ]; then chmod 750 /var/lib/nfs; fi

grep -q games /etc/passwd
if [ $? -eq 0 ];then chmod 750 /usr/games; fi

if [ -e /etc/init.d/lm_sensors ];then
/etc/init.d/lm_sensors stop
chkconfig --level 12345 lm_sensors off
fi

chmod 0640 /var/log/dmesg*
chmod 0444       /etc/bashrc /etc/csh.cshrc /etc/csh.login /etc/profile
chmod 0400       /root/.bash_profile /root/.bashrc /root/.cshrc /root/.tcshrc

chmod u-x,go-rwx /etc/rsyslog.conf
chmod 0640 /var/log/dmesg*
chmod go-rwx /var/log/boot.log*

# this is for TW policy RHEL6 7.1.1.25
/bin/awk -F "#" '$1 !~ /^[[:space:]]*\$/ && $1 !~ /\*[[:space:]]*$/ && $1 !~ /^[[:space:]]*$/{ split($1,a," "); \
gsub(/-/,"",a[2]); if(a[2] !~ /^@/){ print a[2];} }' /etc/rsyslog.conf 2>/dev/null > /tmp/logfiles
for file in `cat /tmp/logfiles`
do
chown root:root $file
chmod go-rwx $file
done
rm -f /tmp/logfiles

if [ -e /etc/cron.daily/rpm ];then
chmod 700 /etc/cron.daily/rpm
fi
find /home -type d -name RCS -exec chmod -R g-rwx,o-rwx {} \;
find /boot -type d -name RCS -exec chmod -R g-rwx,o-rwx {} \;
find /etc -type d -name RCS -exec chmod -R g-rwx,o-rwx {} \;
find /usr -type d -name RCS -exec chmod -R g-rwx,o-rwx {} \;
find /root -type d -name RCS -exec chmod -R g-rwx,o-rwx {} \;
if [ -d /usr/openv/netbackup/logs ]; then chmod -R o-w /usr/openv/netbackup/logs; fi

# this is for TW policy 7.1.1.131
if [ -e /etc/abrt ];then
chmod 750 /etc/abrt
fi

# remove world-writable file permission to /etc/jlumachine.id
if [ -e /etc/jlumachine.id ]; then chmod o-w /etc/jlumachine.id; fi

grubby --update-kernel=ALL --args="audit=1"
echo 'install usb-storage /bin/true' > /etc/modprobe.d/usb.conf
echo 'install vfat /bin/true' > /etc/modprobe.d/vfat.conf
echo 'install cramfs /bin/true' > /etc/modprobe.d/cramf.conf
echo 'install hfs /bin/true' > /etc/modprobe.d/hfs.conf
echo 'install hfsplus /bin/true' >> /etc/modprobe.d/hfs.conf
echo 'install squashfs /bin/true' > /etc/modprobe.d/squashfs.conf
echo 'install udf /bin/true' > /etc/modprobe.d/udf.conf
#sed -iBAK 's/active = no/active = yes/g' /etc/audisp/plugins.d/syslog.conf

if [ -e /usr/bin/telnet ];then
rpm -e telnet
fi 

# 
touch  /.autorelabel 


# create /var/log/lastlog
if [ ! -e /var/log/lastlog ];then
touch /var/log/lastlog
chmod 600 /var/log/lastlog
fi

cd /var/log
chmod -R o-rwx /var/log/*

#sestatus
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/sysconfig/selinux
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
#sestatus

sed -i -e 's/^#\ ucredit/ucredit/' -e 's/^#\ dcredit/dcredit/' -e 's/^#\ minlen/minlen/' \
-e 's/^#\ lcredit/lcredit/' -e 's/^#\ ocredit/ocredit/' /etc/security/pwquality.conf

authconfig --passalgo=sha512 --update

# set gpgcheck to 1
sed -i 's/gpgcheck=0/gpgcheck=1/' /etc/yum.repos.d/amzn-nosrc.repo

echo "Done for AWS ECS System Hardening at `date +%c`." >> $LOGFILE2

# Protect hardening report.
chmod -R 600 /etc/DATAPIPE
chattr +i /etc/DATAPIPE/*
#

cp /etc/pam.d/system-auth-ac.HardenedProtectedCopy /etc/pam.d/system-auth-ac
cp /etc/pam.d/password-auth-ac.HardenedProtectedCopy /etc/pam.d/password-auth-ac
chmod 600 /boot/grub/menu.lst

# remove the below backup copy to avoid any error message shown on /var/log/message.
rm -f /etc/audisp/plugins.d/syslog.conf,v

cat << EOF >> /etc/ssh/sshd_config
#
Match User dpadmin,dpadmin2,dpadmin3,dpscanner
PermitEmptyPasswords no
PasswordAuthentication yes
### Please insert your configuration above the "Match" line, no configuration can be added after this line.
EOF

#
# remove the hardening script if found
for file in /aws-ecs-pci*.sh /tmp/aws-ecs-pci*.sh /root/aws-ecs-pci*.sh; do if [ -e $file ]; then rm -f $file; fi; done
#
find /home -name aws-ecs-pci*.sh -exec rm -f {} \;
#
# END
