#!/bin/sh -x
# Name          : oel7-pci-dss-3.2-v1.5.sh
# Summary       : Datapipe PCI-DSS v3.2 Hardening Standards Script for OEL7
# Author        : Kenny Lo
# Date          : Dec 20, 2018
# $Id: 

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin 

yum -y install redhat-lsb-core

# Sanity check : OS version check
DIST=$(lsb_release -i | sed 's/\t//g' |awk -F':' '{print $2}')
RELEASE=$(lsb_release -r | sed 's/\t//g' |awk -F':' '{print $2}')
if [[ "$DIST" == Oracle* ]] && [[ "$RELEASE" == 7.* ]]; then
	echo "OS version check: Passed"
	else
        echo "This script will only work on Oralce Linux Server release 7. Please check your OS and version number."
        sleep 3
        exit 1
fi

# Install required packages for hardening script
yum -y install sysstat rcs libpwquality tcp_wrappers audispd-plugins authconfig

# 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 sysstat rcs"
echo "--"
echo "No modifications have been made to the system."
sleep 3
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 sysstat rcs"
echo "--"
echo "No modifications have been made to the system."
sleep 3
exit
fi

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 systemctl list-unit-files | grep disabled" >> $LOGFILE1
/usr/bin/systemctl list-unit-files | grep disabled >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### run systemctl list-unit-files | grep enabled" >> $LOGFILE1
/usr/bin/systemctl list-unit-files | grep enabled >> $LOGFILE1
echo ++++++++++++++ >> $LOGFILE1
echo "### run systemctl list-unit-files | grep -v enabled | grep -v disabled" >> $LOGFILE1
/usr/bin/systemctl list-unit-files | grep -v enabled | grep -v disabled >> $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 -Th" >> $LOGFILE1
df -Tk >> $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 "OEL7 PCI DSS v3.2 System Hardening v1.5 being Applied." >> $LOGFILE2

# Update system date and time
systemctl enable chronyd
#

# 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/grub2 \
	/etc/default \
	/etc/skel \
	/etc/security \
	/etc/audit \
	/etc/pam.d \
	/root
do
if [ -d $DIRECTORY ];then
mkdir $DIRECTORY/RCS
fi
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/selinux/config \
	/etc/sysconfig/authconfig \
	/etc/sysconfig/init \
	/etc/sysconfig/selinux \
	/etc/sysconfig/sendmail \
	/etc/inittab \
	/etc/sysctl.conf \
	/etc/rsyslog.conf \
	/etc/vsftpd.conf \
	/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/grub2/grub.cfg \
	/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/audit/rules.d/audit.rules \
	/etc/audit/auditd.conf \
	/etc/pam.d/passwd \
	/etc/pam.d/password-auth-ac \
	/etc/pam.d/system-auth-ac \
	/etc/pam.d/sshd \
	/etc/selinux/config
do
if [ -e $FILE ];then
ci -l -wsecurity $FILE <<EOF
Original State Before Datapipe PCI-DSS Hardening Standards Were Applied.
.
EOF
fi
done

# remove /var/tmp and link it to /tmp
rm  -rf  /var/tmp 
ln  -s   /tmp  /var/tmp 

# Apply Latest OS Patches
PATCHOPTION=$1
if [ X$PATCHOPTION == XFULL ];then
yum -y update
elif [ X$PATCHOPTION == XSECURITY ];then
yum -y update --security
elif [ X$PATCHOPTION == XNONE ];then
echo "skipping yum update"
else
echo "Patch option is NOT provided, yum update will be skipped."
fi


# 2.3 Configure SSH

SSH_CONFIG='/etc/ssh/ssh_config'
if [ -e $SSH_CONFIG ]; then
   echo "Securing $SSH_CONFIG"
   grep -v "^Host \*" $SSH_CONFIG | grep -v "#   Protocol 2,1" \
           > $SSH_CONFIG.tmp
   awk '/^#.* Host /               { print "Host *"; print "Protocol 2"; next };
        /^#.*Port /                { print "Port 22"; next };
                                   { print }' $SSH_CONFIG.tmp  \
                                            > $SSH_CONFIG

   if [ "`egrep -l ^Protocol $SSH_CONFIG`" == "" ]; then
        echo 'Protocol 2' >> $SSH_CONFIG
   fi
   chown root:root $SSH_CONFIG
   chmod 0644      $SSH_CONFIG
   rm $SSH_CONFIG.tmp
else
   echo "OK - No $SSH_CONFIG to secure."
fi
 
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 }; 
        /^#.*LogLevel /                 { print "LogLevel VERBOSE"; next }; 
        /^#PermitRootLogin /            { print "PermitRootLogin no"; next }; 
        /^#.*LoginGraceTime /          { print "LoginGraceTime 60"; 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 }; 
        /^#MaxAuthTries /                   { print "MaxAuthTries 4"; next }; 
                                        { print }' $SSHD_CONFIG \
                                                   > $SSHD_CONFIG.new
   mv $SSHD_CONFIG.new $SSHD_CONFIG
   chown root:root $SSHD_CONFIG
   chmod 0600      $SSHD_CONFIG
else 
   echo "OK - No $SSHD_CONFIG to secure." 
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


# 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

# 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." 
if [ -e /etc/init.d/xinetd ];then
chkconfig  --list   xinetd 
chkconfig  --level  12345  xinetd  off 
chkconfig  --list   xinetd 
fi


# 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, set server to run at runlevel 3
systemctl set-default multi-user.target


# 4.5 Disable X Font Server, If Possible

if [ -e /etc/init.d/xfs ];then
chkconfig  --level  12345  xfs  off 
fi


# 4.6 Disable Standard Boot Services


# 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

for PACKAGE in bluez telnet-server rsh-server ypbind ypserv tftp tftp-server talk talk-server xinetd vsftpd
do
rpm -qa | grep $PACKAGE
if [ $? -eq 0 ];then
rpm -e $PACKAGE
fi
done

# Disable verify command on Postfix
echo "disable_vrfy_command = yes" >> /etc/postfix/mail.cf


# 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 11 lines added by hardening scripts, per CIS Red Hat Enterprise Linux Benchmark sec 5.1: 
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.default.rp_filter = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route=0
net.ipv4.tcp_timestamps = 0
# This is for TW Policy RHEL7 2.2.3.11 & 2.2.3.12
#net.ipv4.conf.all.log_martians = 1
#net.ipv4.conf.default.log_martians = 1
# Restrict Core Dumps as per CIS RHEL7 Benchmark 1.6.1
fs.suid_dumpable = 0
# Enable Randomized Virtual Memory Region Placement as per CIS RHEL7 Benchmark 1.6.1
kernel.randomize_va_space = 2
#
# Oracle 11gR2
kernel.sem = 250 32000 100 142
fs.file-max = 6815747
net.ipv4.ip_local_port_range = 9000 65500
net.core.rmem_default = 262144
net.core.wmem_default=262144
net.core.rmem_max=4194304
net.core.wmem_max=1048576
kernel.msgmni = 2878
kernel.shmmni = 4096
# For 11g recommended value for net.core.rmem_max is 4194304
# For 10g uncomment the following line, comment other entries for this parameter and re-run sysctl -p
# net.core.rmem_max=2097152
fs.aio-max-nr = 3145728
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 sec 5.2: 
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 
chmod 0600 /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             \
    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 
 

# 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 RHEL7 as it breaks /etc/fstab


# 7.2 Add 'nosuid' and 'nodev' Option For Removable Media In /etc/fstab
# Part 1 
# Skip this requirement in RHEL7 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 -f $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 
 

# 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]" || $3 ~ "xfs" ) { 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]" || $3 ~ "xfs" ) { 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 System Access, Authentication, and Authorization
# 8.1 Remove .rhosts Support In PAM Configuration Files

# 8.2 Create ftpusers Files

if [ -f /etc/ftpaccess ]; then 
   for NAME in `cut -d: -f1 /etc/passwd`; do 
       if [ `id -u $NAME` -lt 1000 ]; 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 -f 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 -f 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 
echo  oracle  >>  /etc/at.allow 
echo  oracle  >>  /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 
ls | grep cron | xargs chown -R root:root 
ls | grep cron | xargs chmod -R go-rwx 
#ls -lad /etc/cron* /var/spool/cron* 


# 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 
     /bin/cp -pf gdm.conf gdm.conf.tmp 
     sed -e 's/AllowRoot=true/AllowRoot=false/'             \
         -e 's/AllowRemoteRoot=true/AllowRemoteRoot=false/' \
         -e 's/^#Use24Clock=false/Use24Clock=true/'   
         gdm.conf.tmp  >  gdm.conf 
     rm gdm.conf.tmp
     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/grub2/grub.cfg 
chmod 0600      /boot/grub2/grub.cfg


# 8.8 Require Authentication For Single-User Mode
# Better to keep it unchanged

# 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 1000) to /sbin/nologin" 
cd /etc 
for NAME in `/bin/awk -F: '0+$3 < 1000 && $1 !~ /^[[:space:]]*(#.*|mysql|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 


# 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 -f 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  1000  -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

# update /etc/login.defs to enable removal of at/cron/print jobs while removing user.
sed -i 's/#USERDEL_CMD/USERDEL_CMD/' /etc/login.defs

chown  root:root  login.defs 
chmod  0640       login.defs 


# 9.4 Verify No Legacy '+' Entries Exist In passwd, shadow, And group Files

# 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 >= 1000 ) { 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 >= 1000) { 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

find  /home  -name  .netrc  -exec rm -f {} \;


# 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 -f /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:
echo "Authorized uses only. All activities may be monitored and reported." > /etc/issue.net
/bin/cp -pf /etc/issue  /etc/motd
chown root:root /etc/issue.net
chmod 644 /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." 
AuditRulePATH='/etc/audit/rules.d' 
AuditdPATH='/etc/audit' 
# Part 1 
echo "Enforce auditing minimums." 
# This will enforce auditing minimums. 

cat <<END_SCRIPT   >         $AuditRulePATH/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 1000 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>=1000 -F auid!=4294967295 -k perm_mod
-a always,exit -F arch=b64 -S chmod -S fchmod -S fchmodat -F auid>=1000 -F auid!=4294967295 -k perm_mod
-a always,exit -F arch=b32 -S chown -S fchown -S fchownat -S lchown -F auid>=1000 -F auid!=4294967295 -k perm_mod 
-a always,exit -F arch=b64 -S chown -S fchown -S fchownat -S lchown -F auid>=1000 -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>=1000 -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>=1000 -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>=1000 -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>=1000 -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>=1000 -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>=1000 -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>=1000 -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>=1000 -F auid!=4294967295 -k mounts
-a always,exit -F arch=b64 -S mount -F auid>=1000 -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>=1000 -F auid!=4294967295 -k delete
-a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -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>=1000 -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 scope
-w /etc/sudoers -p wa -k scope
 
## 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/rules.d/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

### NOTE: all rules need to be placed above this line (before the immutable flag has been set). ###
## Make the configuration immutable - reboot is required to change audit rules 
-e 2
##
##
END_SCRIPT

chown root:root $AuditRulePATH/audit.rules 
chmod 0600      $AuditRulePATH/audit.rules 
 
# Part 2 
echo "Strengthen auditd.conf settings." 
sed -i -e "s/space_left = 75/space_left = 125/"                  \
    -e "s/space_left_action = SYSLOG/space_left_action = email/" \
    -e "s/admin_space_left = 50/admin_space_left = 75/"          \
       $AuditdPATH/auditd.conf
chown root:root $AuditdPATH/auditd.conf 
# Default permissions were originally 0640. 
chmod 0600      $AuditdPATH/auditd.conf 
 
# Part 3 
chkconfig --level 35 auditd  on 
chkconfig --level 35 sysstat on 

# 11.2 Verify no duplicate userIDs exist
# skipped.

# 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
#%PAM-1.0
# 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_env.so
auth        required      pam_faillock.so preauth audit deny=6 unlock_time=1800
auth        sufficient    pam_unix.so try_first_pass
auth        [default=die] pam_faillock.so authfail audit deny=6 unlock_time=1800
auth        sufficient     pam_faillock.so authsucc audit deny=6 unlock_time=1800
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        required      pam_deny.so

account     required      pam_faillock.so
account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so sha512 shadow try_first_pass use_authtok remember=4
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
#session     optional      pam_oddjob_mkhomedir.so 
-session     optional      pam_systemd.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

cat << EOF > /etc/pam.d/password-auth-ac
#%PAM-1.0
# 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_env.so
auth        required      pam_faillock.so preauth audit deny=6 unlock_time=1800
auth        sufficient    pam_unix.so try_first_pass
auth        [default=die] pam_faillock.so authfail audit deny=6 unlock_time=1800
auth        sufficient     pam_faillock.so authsucc audit deny=6 unlock_time=1800
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        required      pam_deny.so

account     required      pam_faillock.so
account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so sha512 shadow try_first_pass use_authtok remember=4
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
#session     optional      pam_oddjob_mkhomedir.so
-session     optional      pam_systemd.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/password-auth-ac
chmod 0644      /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/passwd
#%PAM-1.0
auth       include      system-auth
account    include      system-auth
password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password   substack     system-auth
-password   optional    pam_gnome_keyring.so use_authtok
password   substack     postlogin
EOF

# disable selinux
cat << EOF > /etc/selinux/config

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these two values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected. 
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted 


EOF
chown root:root /etc/selinux/config
chmod 644 /etc/selinux/config

# 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


# 13.1 Remove CIS benchmark hardening backup files
# no action required.

################
# 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|xfs") { 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 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

# 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/selinux/config \
        /etc/sysconfig/authconfig \
        /etc/sysconfig/init \
        /etc/sysconfig/selinux \
        /etc/sysconfig/sendmail \
        /etc/sysctl.conf \
        /etc/rsyslog.conf \
        /etc/vsftpd.conf \
        /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/grub2/grub.cfg \
        /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/audit/rules.d/audit.rules \
        /etc/audit/auditd.conf \
        /etc/pam.d/system-auth-ac \
        /etc/pam.d/password-auth-ac \
        /etc/pam.d/passwd \
	/etc/pam.d/sshd \
	/etc/selinux/config
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/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
chown root:root /etc/shadow
fi

if [ -e /etc/gshadow ];then
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 dpadmin dpadmin2 dpadmin3 clientadmin ec2-user centos
do
awk -F: '{print $1}' /etc/passwd | grep ^$newusers$
if [ $? -eq 0 ];then
useradd $newusers
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

###
for ex_users in `grep bash /etc/passwd|awk -F: '{print $1}'|egrep -v 'root|dpadmin|dpadmin2|dpadmin3|clientadmin|ec2-user|centos|dpscanner'`
do
usermod -a -G ssh_access $ex_users
usermod -a -G wheel $ex_users
chage -I -1 -m 7 -M -1 -E -1 $ex_users
done

# CIS RHEL7 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
#echo -e "tmpfs\\t/dev/shm\\ttmpfs\\tnosuid,nodev,noexec,defaults\\t0\\t0" >> /etc/fstab
chattr +i /etc/fstab

# CIS RHEL7 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

# 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

# disable some of the services
for service in atd cups firewalld
do
systemctl stop $service
systemctl disable $service
done


#############################################
# 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 2.0 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 2.0 Hardening Standards.
.
EOF

# This is for TW policy RHEL7 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  -o ! -name mysql \) -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 RHEL7 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

# install iptables service for contingency
yum install -y iptables-services
systemctl stop iptables
systemctl disable iptables

# create /var/log/lastlog
if [ ! -e /var/log/lastlog ];then
touch /var/log/lastlog
chmod 600 /var/log/lastlog
fi

sed -i 's/uucp/#uucp/' /etc/rsyslog.conf

for file in `/bin/awk -F "#" '$1 !~ /^[[:space:]]*\$/ && $1 !~ /\*[[:space:]]*$/ && $1 !~ /^[[:space:]]*$/{ split($1,a," "); gsub(/-/,"",a[2]); if(a[2] !~ /^@/ && a[2] ~ /^[[:space:]]*\//){ print a[2];} }' /etc/rsyslog.conf 2>/dev/null | grep "\/var\/log" | sort -u`
do
chmod u-x,g-wx,o-rwx $file
done

chmod 000 /etc/shadow
chmod 000 /etc/gshadow

# enable auditd before system boots up.
grubby --update-kernel=ALL --args="audit=1"
chmod go-rwx /boot/grub2/grub.cfg

chmod u-x,og-rwx /var/log/boot.log
rm -rf /var/db/sudo/*

if [ -e /usr/bin/telnet ];then
rpm -e telnet
fi

# 
touch  /.autorelabel 

#sestatus
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/sysconfig/selinux
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
setenforce permissive
#sestatus

#sed -i 's/active = no/active = yes/g' /etc/audisp/plugins.d/syslog.conf
authconfig --passalgo=sha512 --update
authconfig --passminlen=9 --passminclass=4 --passmaxrepeat=3 --passmaxclassrepeat=3 \
--enablereqlower --enablerequpper --enablereqdigit  --enablereqother --update

chmod 600 /etc/ssh/sshd_config

echo "Done for RHEL7 PCI DSS v3.2 System Hardening at `date +%c`." >> $LOGFILE2

# Protect hardening report.
chmod -R 600 /etc/DATAPIPE
chattr +i /etc/DATAPIPE/*

# remove support from unneeded filesystems.
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

# configure chrony daemon to run by chrony.
echo "OPTIONS=\"-u chrony\"" > /etc/sysconfig/chronyd

#
cd /etc/pam.d
unalias cp
cp password-auth-ac.HardenedProtectedCopy password-auth-ac
cp system-auth-ac.HardenedProtectedCopy system-auth-ac
#
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 /oel7-pci*.sh /tmp/oel7-pci*.sh /root/oel7-pci*.sh; do if [ -e $file ]; then rm -f $file; fi; done
#
find /home -name oel7-pci*.sh -exec rm -f {} \;
#

# END
