commit bbf5757397e44e3b027b57306a6854a910a2d3ae Author: Phil Connor Date: Tue Mar 12 10:00:34 2024 -0500 initial commit after prune move from main diff --git a/CodeServerInstall.sh b/CodeServerInstall.sh new file mode 100644 index 0000000..11052db --- /dev/null +++ b/CodeServerInstall.sh @@ -0,0 +1,535 @@ +#!/bin/bash + +#################################################################### +#### Code-Server install Script for Oracle Linux, Centos/Redhat #### +#### and Ubuntu Servers. #### +#### Author: Phil Connor 02/10/2020 #### +#### Contact: contact@mylinux.work #### +#### Version 1.30 #### +#### #### +#### To use this script chmod it to 755 #### +#### or simply type bash #### +#################################################################### + +############################# +#### User Configurations #### +############################# +CODEDIR=/code # Home directory for your Code +EMAIL=admin@mydomain.com # your domain email address +HTTPTYPE=APACHE # Choose Apache, Caddy or Nginx All UPPER Case +PASSWD=pAsSwOrD # Your Password for Code-server used for Apache, Nginx and Caddy +UNAME=MyUser # Username Used for Caddy +SERVDIR=/usr/local/code-server # where you want the code-server installed +SERVERNAME=code.mydomain.cloud # server fqdn name +USRDIR=/var/lib/code-server + +######################## +#### System Configs #### +######################## +CADPASS="$(echo -e "${PASSWD}\n$PASSWD" | caddy hash-password 2>/dev/null | tail --lines=1)" +if [ "$(command -v lsb_release)" ]; then + OS=$(lsb_release -i | awk '{print $3}' | tr '[:upper:]' '[:lower:]') + OSVER=$(lsb_release -r | awk '{print $2}' | awk -F. '{print $1}') +else + OS=$(grep PRETTY_NAME /etc/os-release | sed 's/PRETTY_NAME=//g' | tr -d '="' | awk '{print $1}' | tr '[:upper:]' '[:lower:]') + OSVER=$(grep VERSION_ID /etc/os-release | sed 's/VERSION_ID=//g' | tr -d '="' | awk -F. '{print $1}') +fi + +define() { + IFS=$'\n' read -r -d '' "$1" + } + +########################################################### +#### Detect Package Manger from OS and OSVer Variables #### +########################################################### +if [[ ${OS} = alma || ${OS} = amazon || ${OS} = centos || ${OS} = red || ${OS} = rocky || ${OS} = oracle ]]; then + if [ "${OSVER}" = 7 ]; then + PAKMGR="yum -y" + else + PAKMGR="dnf -y" + fi +elif [ "${OS}" = ubuntu ]; then + PAKMGR="apt -y" +fi + +################################ +#### Check if OS is Updated #### +################################ +if [ "${OS}" = ubuntu ]; then + ${PAKMGR} update && ${PAKMGR} upgrade + ${PAKMGR} install libc6 libstdc++6 snapd +else + ${PAKMGR} update + ${PAKMGR} install snapd +fi + +############################################### +#### Get the latest version of Code Server #### +############################################### +get_latest_version() { + { + version="$(curl -fsSLI -o /dev/null -w "%{url_effective}" https://github.com/coder/code-server/releases/latest)" + version="${version#https://github.com/coder/code-server/releases/tag/}" + version="${version#v}" + echo "$version" + } +} + +######################################### +#### Download and Install Codeserver #### +######################################### +install_codeserver() { + { + # check if command wget exists + if ! command -v wget >/dev/null 2>&1; then + ${PAKMGR} install wget + fi + cd ~/ || exit + wget "https://github.com/coder/code-server/releases/download/v$version/code-server-$version-linux-amd64.tar.gz" + tar xvf "code-server-$version-linux-amd64.tar.gz" + mkdir ${CODEDIR} + mkdir ${SERVDIR} + cp -r ~/code-server-"$version"-linux-amd64/* ${SERVDIR} + ln -s ${SERVDIR}/bin/code-server /usr/bin/code-server + # Code Directory + mkdir "${CODEDIR}" + # User Directory + mkdir "${USRDIR}" + + csserv=/lib/systemd/system + touch $csserv/code-server.service + OUTFILE1="$csserv/code-server.service" + define SFILE << EOF + [Unit] + Description=code-server + After=nginx.service + + [Service] + Type=simple + Environment=PASSWORD=$PASSWD + ExecStart=/usr/bin/code-server --bind-addr 127.0.0.1:8080 --user-data-dir ${USRDIR} --auth password + Restart=always + + [Install] + WantedBy=multi-user.target +EOF + + { + printf "%s\n" "$SFILE" | cut -c 2- + } > "$OUTFILE1" + + if [ $HTTPTYPE = CADDY ]; then + sed -i 's/After=nginx.service/After=caddy.service/g' $csserv/code-server.service + sed -i 's/auth: password/auth: none' /root/.config/code-server/config.yaml + sed -i "ExecStart=/usr/bin/code-server --bind-addr 127.0.0.1:8080 --user-data-dir ${CODEDIR} --auth password/ExecStart=/usr/bin/code-server --bind-addr 127.0.0.1:8080 --user-data-dir ${CODEDIR}" $csserv/code-server.service + fi + + systemctl daemon-reload + systemctl start code-server + systemctl enable code-server + } +} + +######################################## +#### Install Apache, Nginx or Caddy #### +######################################## +install_http() { + { + if [ $HTTPTYPE = APACHE ]; then + csserv=/lib/systemd/system + sed -i 's/After=nginx.service/After=apache.service/g' $csserv/code-server.service + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + if ! command -v httpd &> /dev/null; then + ${PAKMGR} install httpd + systemctl enable --now httpd + fi + AOUTFILE="/etc/httpd/conf.d/code-server.conf" + elif [ "${OS}" = ubuntu ]; then + if ! command -v apache2 &> /dev/null; then + ${PAKMGR} install apache2 + systemctl enable --now apache2 + fi + AOUTFILE="/etc/apache2/sites-available/code-server.conf" + fi + define ACONF << 'EOF' + + ServerName $SERVERNAME + #ProxyPreserveHost On + RewriteEngine On + RewriteCond %{HTTP:Connection} Upgrade [NC] + RewriteCond %{HTTP:Upgrade} websocket [NC] + RewriteRule /(.*) ws://127.0.0.1:8080/$1 [P,L] + #RewriteCond %{HTTP:Upgrade} =websocket [NC] + #RewriteRule /(.*) ws://127.0.0.1:8080/$1 [P,L] + #RewriteCond %{HTTP:Upgrade} !=websocket [NC] + #RewriteRule /(.*) http://127.0.0.1:8080/$1 [P,L] + ProxyRequests off + #RequestHeader set X-Forwarded-Proto https + #RequestHeader set X-Forwarded-Port 443 + ProxyPass / http://127.0.0.1:8080/ nocanon + ProxyPassReverse / http://127.0.0.1:8080/ + +EOF + { + printf "%s\n" "$ACONF" | cut -c 4- + } > "$AOUTFILE" + + systemctl daemon-reload + systemctl restart code-server + if [ "${OS}" = ubuntu ]; then + a2enmod proxy + a2enmod proxy_http + a2ensite code-server.conf + systemctl restart apache2 + else + systemctl restart httpd + fi + fi + + if [ $HTTPTYPE = NGINX ]; then + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + OUTFILE="/etc/yum.repos.d/nginx.repo" + define NYUM << 'EOF' + [nginx-stable] + name=nginx stable repo + baseurl=http://nginx.org/packages/centos/$releasever/$basearch/ + gpgcheck=1 + enabled=1 + gpgkey=https://nginx.org/keys/nginx_signing.key + module_hotfixes=true +EOF + { + printf "%s\n" "$NYUM" | cut -c 4- + } > "$OUTFILE" + if [ "${OSVER}" = 8 ] || [ "${OSVER}" = 9 ]; then + # shellcheck disable=2016 + sed -i 's/baseurl=http:\/\/nginx.org\/packages\/centos\/7\/$basearch\//baseurl=http:\/\/nginx.org\/packages\/centos\/8\/$basearch\//g' $OUTFILE + fi + fi + + if [ "${OS}" = ubuntu ]; then + ${PAKMGR} install curl gnupg2 ca-certificates lsb-release + echo "deb http://nginx.org/packages/ubuntu $(lsb_release -cs) nginx" | sudo tee /etc/apt/sources.list.d/nginx.list + echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" | sudo tee /etc/apt/preferences.d/99nginx + curl -o /tmp/nginx_signing.key https://nginx.org/keys/nginx_signing.key + if [ "$OSVER" = 16 ]; then + gpg --with-fingerprint /tmp/nginx_signing.key + else + gpg --dry-run --quiet --import --import-options show-only /tmp/nginx_signing.key + fi + sudo mv /tmp/nginx_signing.key /etc/apt/trusted.gpg.d/nginx_signing.asc + sudo apt update + fi + + ${PAKMGR} install nginx + + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + nxdir=/etc/nginx/conf.d + elif [ "${OS}" = ubuntu ]; then + if [ "$OSVER" = 16 ]; then + nxdir=/etc/nginx/sites-available + else + nxdir=/etc/nginx/conf.d + fi + fi + + OUTFILE2="$nxdir/code-server.conf" + define NFIG << EOF + server { + listen 80; + listen [::]:80; + server_name $SERVERNAME; + location / { + proxy_pass http://localhost:8080/; + proxy_set_header Host \$host; + proxy_set_header Upgrade \$http_upgrade; + proxy_set_header Connection upgrade; + proxy_set_header Accept-Encoding gzip; + } + } +EOF + { + printf "%s\n" "$NFIG" | cut -c 2- + } > "$OUTFILE2" + + if [ "${OS}" = ubuntu ]; then + mv $nxdir/default $nxdir/default.orig + ln -s $nxdir/code-server.conf $nxdir/code-server.conf + else + mv $nxdir/default.conf $nxdir/default.conf.orig + fi + systemctl start nginx + systemctl enable nginx + fi + + if [ "$HTTPTYPE" = CADDY ]; then + if [ "${OS}" = ubuntu ]; then + ${PAKMGR} debian-keyring debian-archive-keyring apt-transport-https + curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/cfg/gpg/gpg.155B6D79CA56EA34.key' | apt-key add - + curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/cfg/setup/config.deb.txt?distro=debian&version=any-version' | tee -a /etc/apt/sources.list.d/caddy-stable.list + ${PAKMGR} update + ${PAKMGR} install caddy + elif [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + if [ "${OSVER}" = 7 ]; then + ${PAKMGR} install yum-plugin-copr + elif [ "${OSVER}" = 8 ] || [ "${OSVER}" = 9 ]; then + ${PAKMGR} install 'dnf-command(copr)' + fi + ${PAKMGR} copr enable @caddy/caddy + ${PAKMGR} install caddy + fi + + caddir=/etc/caddy + mv $caddir/Caddyfile $caddir/Caddyfile.orig + touch $caddir/Caddyfile + OUTFILE3="$caddir/Caddyfile" + define CFILE << EOF + { #### Remove these 3 lines + acme_ca https://acme-staging-v02.api.letsencrypt.org/directory #### to make server live + } #### and grab cert from letsencrypt + + $SERVERNAME { + basicauth /* { + $UNAME $CADPASS + } + reverse_proxy 127.0.0.1:8080 + } + +EOF + { + printf "%s\n" "$CFILE" | cut -c 2- + } > "$OUTFILE3" + + systemctl enable caddy + systemctl start caddy + + fi + + } +} + +########################################## +#### Install Certbot and request Cert #### +########################################## +install_certbot() { + { + if [ $HTTPTYPE = NGINX ];then + if [ "${OS}" = ubuntu ]; then + ${PAKMGR} remove letsencrypt + ${PAKMGR} remove certbot + snap install core; snap refresh core + snap install --classic certbot + ${PAKMGR} install python3-certbot-nginx + elif [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + ${PAKMGR} remove certbot + ${PAKMGR} install epel-release + ${PAKMGR} install snapd + if [ "$OSVER" = 7 ]; then + ${PAKMGR} install python2-certbot-nginx + elif [ "${OSVER}" = 8 ] || [ "${OSVER}" = 9 ]; then + ${PAKMGR} install python3-certbot-nginx + fi + fi + fi + if [ $HTTPTYPE = APACHE ];then + if [ "${OS}" = ubuntu ]; then + ${PAKMGR} remove letsencrypt + ${PAKMGR} remove certbot + snap install core; snap refresh core + snap install --classic certbot + ${PAKMGR} install python3-certbot-apache + elif [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + ${PAKMGR} remove certbot + ${PAKMGR} install epel-release + ${PAKMGR} install snapd + if [ "$OSVER" = 7 ]; then + ${PAKMGR} install python2-certbot-apache + elif [ "${OSVER}" = 8 ] || [ "${OSVER}" = 9 ]; then + ${PAKMGR} install python3-certbot-apache + fi + snap install core; snap refresh core + snap install --classic certbot + fi + fi + systemctl enable --now snapd.socket + ln -s /var/lib/snapd/snap /snap + ln -s /snap/bin/certbot /usr/bin/certbot + + if [ $HTTPTYPE = NGINX ]; then + certbot --non-interactive --redirect --agree-tos --nginx -d $SERVERNAME -m "$EMAIL" #--dry-run + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + if ! grep "certbot" /var/spool/cron/root; then + echo "0 */12 * * * root certbot -q renew --nginx" >> /var/spool/cron/root + fi + elif [ "${OS}" = ubuntu ]; then + if ! grep "certbot" /var/spool/cron/crontabs/root; then + echo "0 */12 * * * root certbot -q renew --nginx" >> /var/spool/cron/crontabs/root + fi + + grep nginx /var/log/audit/audit.log | audit2allow -M nginx + semodule -i nginx.pp + fi + elif [ $HTTPTYPE = APACHE ]; then + certbot --non-interactive --redirect --agree-tos --apache -d $SERVERNAME -m "$EMAIL" # --dry-run + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + if ! grep "certbot" /var/spool/cron/root; then + echo "0 */12 * * * root certbot -q renew --apache" >> /var/spool/cron/root + fi + elif [ "${OS}" = ubuntu ]; then + if ! grep "certbot" /var/spool/cron/crontabs/root; then + echo "0 */12 * * * root certbot -q renew --apache" >> /var/spool/cron/crontabs/root + fi + fi + fi + + } +} + +function install_firewall() { + { + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + ${PAKMGR} install ipset perl-libwww-perl.noarch perl-LWP-Protocol-https.noarch perl-GDGraph perl-Sys-Syslog perl-Math-BigInt + elif [ "${OS}" = ubuntu ]; then + ${PAKMGR} install ipset libwww-perl liblwp-protocol-https-perl libgd-graph-perl + fi + cd /usr/src || exit + # rm -fv csf.tgz + wget https://download.configserver.com/csf.tgz + tar -xzf csf.tgz + cd csf || exit + ./install.sh + echo '' + echo '###########################################' + echo '#### Testing if CSF firewall will work ####' + echo '###########################################' + echo '' + perl /usr/local/csf/bin/csftest.pl + ##### Initial Settings ##### + sed -i 's/TESTING = "1"/TESTING = "0"/g' /etc/csf/csf.conf + sed -i 's/RESTRICT_SYSLOG = "0"/RESTRICT_SYSLOG = "3"/g' /etc/csf/csf.conf + sed -i '/^RESTRICT_UI/c\RESTRICT_UI = "1"' /etc/csf/csf.conf + sed -i '/^AUTO_UPDATES/c\AUTO_UPDATES = "1"' /etc/csf/csf.conf + ##### IPv4 Port Settings ##### + sed -i 's/TCP_IN = "20,21,22,25,53,80,110,143,443,465,587,993,995"/TCP_IN = "22,80,443,5666,10000"/g' /etc/csf/csf.conf + sed -i 's/TCP_OUT = "20,21,22,25,53,80,110,113,443,587,993,995"/TCP_OUT = "22,25,53,80,443,5666,10000"/g' /etc/csf/csf.conf + sed -i 's/UDP_IN = "20,21,53,80,443"/UDP_IN = "80,443"/g' /etc/csf/csf.conf + sed -i 's/UDP_OUT = "20,21,53,113,123"/UDP_OUT = "53,113,123"/g' /etc/csf/csf.conf + sed -i '/^ICMP_IN_RATE/c\ICMP_IN_RATE = "1/s"' /etc/csf/csf.conf + ##### IPv6 Port Settings ##### + sed -i 's/IPV6 = "0"/IPV6 = "1"/g' /etc/csf/csf.conf + sed -i 's/TCP6_IN = "20,21,22,25,53,80,110,143,443,465,587,993,995"/TCP6_IN = "22,80,443,5666"/g' /etc/csf/csf.conf + sed -i 's/TCP6_OUT = "20,21,22,25,53,80,110,113,443,587,993,995"/TCP6_OUT = "22,80,443,5666"/g' /etc/csf/csf.conf + sed -i 's/UDP6_IN = "20,21,53,80,443"/UDP6_IN = "80,443"/g' /etc/csf/csf.conf + sed -i 's/UDP6_OUT = "20,21,53,113,123"/UDP6_OUT = "53,113,123"/g' /etc/csf/csf.conf + ##### General Settings ##### + sed -i 's/SYSLOG_CHECK = "0"/SYSLOG_CHECK = "300"/g' /etc/csf/csf.conf + sed -i '/^IGNORE_ALLOW/c\IGNORE_ALLOW = "0"' /etc/csf/csf.conf + sed -i '/^LF_CSF/c\LF_CSF = "1"' /etc/csf/csf.conf + sed -i 's/LF_IPSET = "0"/LF_IPSET = "1"/g' /etc/csf/csf.conf + sed -i '/^PACKET_FILTER/c\PACKET_FILTER = "1"' /etc/csf/csf.conf + ##### SMTP Settings ##### + sed -i 's/SMTP_BLOCK = "0"/SMTP_BLOCK = "1"/g' /etc/csf/csf.conf + ##### Port Flood Settings ##### + sed -i 's/SYNFLOOD = "0"/SYNFLOOD = "1"/g' /etc/csf/csf.conf + sed -i 's/CONNLIMIT = ""/CONNLIMIT= "22;5,25;3,80;10"/g' /etc/csf/csf.conf + sed -i 's/PORTFLOOD = ""/PORTFLOOD = "22;tcp;5;300,25;tcp;5;300,80;tcp;20;5"/g' /etc/csf/csf.conf + sed -i 's/UDPFLOOD = "0"/UDPFLOOD = "1"/g' /etc/csf/csf.conf + ##### Logging Settings ##### + sed -i 's/SYSLOG = "0"/SYSLOG = "1"/g' /etc/csf/csf.conf + sed -i '/^DROP_LOGGING/c\DROP_LOGGING = "1"' /etc/csf/csf.conf + sed -i '/^DROP_ONLYRES/c\DROP_ONLYRES = "0"' /etc/csf/csf.conf + sed -i '/^UDPFLOOD_LOGGING/c\UDPFLOOD_LOGGING = "1"' /etc/csf/csf.conf + ##### Temp to Perm/Netblock Settings ##### + sed -i '/^LF_PERMBLOCK^/c\LF_PERMBLOCK = "1"' /etc/csf/csf.conf + sed -i 's/LF_NETBLOCK = "0"/LF_NETBLOCK = "1"/g' /etc/csf/csf.conf + ##### Login Failure Blocking and Alerts ##### + sed -i 's/LF_SSHD = "5"/LF_SSHD = "3"/g' /etc/csf/csf.conf + sed -i 's/LF_FTPD = "10"/LF_FTPD = "5"/g' /etc/csf/csf.conf + sed -i 's/LF_SMTPAUTH = "0"/LF_SMTPAUTH = "5"/g' /etc/csf/csf.conf + sed -i 's/LF_EXIMSYNTAX = "0"/LF_EXIMSYNTAX = "10"/g' /etc/csf/csf.conf + sed -i 's/LF_POP3D = "0"/LF_POP3D = "5"/g' /etc/csf/csf.conf + sed -i 's/LF_IMAPD = "0"/LF_IMAPD = "5"/g' /etc/csf/csf.conf + sed -i 's/LF_HTACCESS = "0"/LF_HTACCESS = "5"/g' /etc/csf/csf.conf + sed -i 's/LF_MODSEC = "5"/LF_MODSEC = "3"/g' /etc/csf/csf.conf + sed -i 's/LF_CXS = "0"/LF_CXS = "1"/g' /etc/csf/csf.conf + sed -i 's/LF_SYMLINK = "0"/LF_SYMLINK = "5"/g' /etc/csf/csf.conf + sed -i 's/LF_WEBMIN = "0"/LF_WEBMIN = "3"/g' /etc/csf/csf.conf + sed -i '/^LF_SSH_EMAIL_ALERT/c\LF_SSH_EMAIL_ALERT = "1"' /etc/csf/csf.conf + sed -i '/^LF_SU_EMAIL_ALERT/c\LF_SU_EMAIL_ALERT = "1"' /etc/csf/csf.conf + sed -i '/^LF_SUDO_EMAIL_ALERT/c\LF_SUDO_EMAIL_ALERT = "1"' /etc/csf/csf.conf + sed -i '/^LF_WEBMIN_EMAIL_ALERT/c\LF_WEBMIN_EMAIL_ALERT = "1"' /etc/csf/csf.conf + sed -i '/^LF_CONSOLE_EMAIL_ALERT/c\LF_CONSOLE_EMAIL_ALERT = "1"' /etc/csf/csf.conf + sed -i '/^LF_BLOCKINONLY/c\LF_BLOCKINONLY = "0"' /etc/csf/csf.conf + ##### Directory Watching & Integrity ##### + sed -i '/^LF_DIRWATCH^/c\LF_DIRWATCH = "300"' /etc/csf/csf.conf + sed -i '/^LF_INTEGRITY/c\LF_INTEGRITY = "3600"' /etc/csf/csf.conf + ##### Distributed Attacks ##### + sed -i 's/LF_DISTATTACK = "0"/LF_DISTATTACK = "1"/g' /etc/csf/csf.conf + sed -i 's/LF_DISTFTP = "0"/LF_DISTFTP = "5"/g' /etc/csf/csf.conf + sed -i 's/LF_DISTSMTP = "0"/LF_DISTSMTP = "5"/g' /etc/csf/csf.conf + ##### Connection Tracking ##### + sed -i 's/CT_LIMIT = "0"/CT_LIMIT = "300"/g' /etc/csf/csf.conf + ##### Process Tracking ##### + sed -i '/^PT_LIMIT/c\PT_LIMIT = "60"' /etc/csf/csf.conf + sed -i '/^PT_SKIP_HTTP/c\PT_SKIP_HTTP = "0"' /etc/csf/csf.conf + sed -i 's/PT_DELETED = "0"/PT_DELETED = "1"/g' /etc/csf/csf.conf + sed -i 's/PT_USERTIME = "1800"/PT_USERTIME = "0"/g' /etc/csf/csf.conf + sed -i 's/PT_FORKBOMB = "0"/PT_FORKBOMB = "250"/g' /etc/csf/csf.conf + ##### Port Scan Tracking ##### + sed -i 's/PS_INTERVAL = "0"/PS_INTERVAL = "300"/g' /etc/csf/csf.conf + sed -i '/^PS_EMAIL_ALERT/c\PS_EMAIL_ALERT = "1"' /etc/csf/csf.conf + ##### User ID Tracking ##### + sed -i 's/UID_INTERVAL = "0"/UID_INTERVAL = "600"/g' /etc/csf/csf.conf + ##### Account Tracking ##### + sed -i 's/AT_ALERT = "2"/AT_ALERT = "1"/g' /etc/csf/csf.conf + systemctl enable --now csf + systemctl enable --now lfd + } +} + +function install_webmin() { + { + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + OUTFILE="/etc/yum.repos.d/webmin.repo" + define WYUM << 'EOF' + [Webmin] + name=Webmin Distribution Neutral + #baseurl=https://download.webmin.com/download/yum + mirrorlist=https://download.webmin.com/download/yum/mirrorlist + enabled=1 +EOF + { + printf "%s\n" "$WYUM" | cut -c 3- + } > "$OUTFILE" + wget https://download.webmin.com/jcameron-key.asc + rpm --import jcameron-key.asc + if [ "${OSVER}" = 7 ]; then + ${PAKMGR} install perl-Encode-Detect perl-Net-SSLeay perl-Data-Dumper tcp_wrappers-devel perl-IO-Tty webmin unzip + elif [ "${OSVER}" = 8 ] || [ "${OSVER}" = 9 ]; then + ${PAKMGR} install perl-Encode-Detect perl-Net-SSLeay perl-Data-Dumper tcp_wrappers tcp_wrappers-libs unzip + dnf config-manager --set-enabled powertools + ${PAKMGR} install perl-IO-Tty webmin + fi + elif [ "${OS}" = ubuntu ]; then + { + echo '' + echo '############################' + echo '#### Adding Webmin Repo ####' + echo '############################' + echo '' + echo 'deb https://download.webmin.com/download/repository sarge contrib' + } >> /etc/apt/sources.list + wget https://download.webmin.com/jcameron-key.asc + apt-key add jcameron-key.asc + ${PAKMGR} install apt-transport-https + ${PAKMGR} update + ${PAKMGR} install webmin + fi + } +} +get_latest_version +install_codeserver +install_http +install_certbot +install_firewall +install_webmin \ No newline at end of file diff --git a/NagiosInstall.sh b/NagiosInstall.sh new file mode 100644 index 0000000..98b5085 --- /dev/null +++ b/NagiosInstall.sh @@ -0,0 +1,432 @@ +#!/bin/bash + +###################################################################################### +#### Version 2.2 #### +#### For questions or comments contact@mylinux.work #### +#### Author : Phil Connor #### +#### #### +#### Notes : #### +#### This script is a simple "helper" to install and configure Maria, #### +#### PowerDNS and PowerAdmin on RedHat Based servers. #### +#### There is no silver bullet. Don't expect the perfect setup, #### +#### review comments and adapt the parameters to your application usage. #### +#### #### +#### Use this script at your OWN risk. There is no guarantee whatsoever. #### +#### #### +#### Usage chmod 755 then ./PdnsInstall.sh or bash PdnsInstall.sh #### +###################################################################################### + +############################ +#### User Configurables #### +############################ +# HTTP=apache +NAGAD=nagiosadmin +NAGADPASS=MyPaSsWoRd +# SAEMAIL= + +########################## +#### System Variables #### +########################## +# IPADD=$(ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1') +if [ "$(command -v lsb_release)" ]; then + OS=$(lsb_release -i | awk '{print $3}' | tr '[:upper:]' '[:lower:]') + OSVER=$(lsb_release -r | awk '{print $2}' | awk -F. '{print $1}') +else + OS=$(grep PRETTY_NAME /etc/os-release | sed 's/PRETTY_NAME=//g' | tr -d '="' | awk '{print $1}' | tr '[:upper:]' '[:lower:]') + OSVER=$(grep VERSION_ID /etc/os-release | sed 's/VERSION_ID=//g' | tr -d '="' | awk -F. '{print $1}') +fi + +########################################################### +#### Detect Package Manger from OS and OSVer Variables #### +########################################################### +if [[ ${OS} = alma || ${OS} = amazon || ${OS} = centos || ${OS} = red || ${OS} = rocky || ${OS} = oracle ]]; then + if [ "${OSVER}" = 7 ]; then + PAKMGR="yum -y" + else + PAKMGR="dnf -y" + fi +elif [ "${OS}" = ubuntu ]; then + PAKMGR="apt -y" +fi + +########################### +#### Install Net-Utils #### +########################### +if [ ! "$(command -v ifconfig)" ]; then + if [ "${OS}" = ubuntu ]; then + ${PAKMGR} update + ${PAKMGR} install net-utils + else + ${PAKMGR} install net-tools + fi +fi + +######################## +#### Nagios Install #### +######################## +function nagios_install() { + { + if [ "${OS}" = ubuntu ]; then + htpath=/etc/apache2/conf-enabled/nagios4-cgi.conf + else + htpath=/etc/apache2/conf.d/nagios.conf + fi + #if [ "${OS}" = ubuntu ]; then + ${PAKMGR} update + DEBIAN_FRONTEND=noninteractive ${PAKMGR} install nagios4 nagios-nrpe-server nagios-plugins nagios-plugins-contrib expect libcgi-pm-perl librrds-perl libgd-gd2-perl + a2enmod authz_groupfile auth_digest + # ${PAKMGR} install autoconf gcc libc6 make wget unzip apache2 php libapache2-mod-php libgd-dev libssl-dev expect + sed -i 's/Require ip ::1\/128 fc00::\/7 fe80::\/10 10\.0\.0\.0\/8 127\.0\.0\.0\/8 169\.254\.0\.0\/16 172\.16\.0\.0\/12 192\.168\.0\.0\/16/# Require ip ::1\/128 fc00::\/7 fe80::\/10 10\.0\.0\.0\/8 127\.0\.0\.0\/8 169\.254\.0\.0\/16 172\.16\.0\.0\/12 192\.168\.0\.0\/16/g' $htpath + #sed -i 's//#/g' $htpath + sed -i 's/Require all/#Require all/g' $htpath + #sed -i 's//#/g' $htpath + sed -i 's/#Require /Require /g' $htpath + expect -f - <<-EOF + set timeout 5 + spawn htdigest -c /etc/nagios4/htdigest.users Nagios4 $NAGAD + expect "New password:" + send -- "$NAGADPASS\r" + expect "Re-type new password:" + send -- "$NAGADPASS\r" + expect eof +EOF + systemctl enable --now nagios + systemctl status nagios + if [ "${OS}" = ubuntu ]; then + systemctl enable apache2 + systemctl restart apache2 + else + systemctl enable httpd + systemctl restart httpd + fi + + } +} + +nagios_install + + +# else +# install perl-rrdtool perl-GD +# fi + +function nagiosgraph install() { + { + cd /tmp | exit 1 + tar xzvf nagiosgraph-x.y.z.tgz + + mkdir /etc/nagiosgraph + cp etc/* /etc/nagiosgraph + +# - Edit the perl scripts in the cgi and lib directories, modifying the +# "use lib" line to point to the directory from the previous step. +# vi cgi/*.cgi lib/insert.pl + +# - Copy insert.pl to a location from which it can be executed: +# cp lib/insert.pl /usr/local/nagios/libexec +# or for Homebrew: +# cp lib/insert.pl /usr/local/opt/nagios/bin + +# - Copy CGI scripts to a script directory served by the web server: +# cp cgi/*.cgi /usr/local/nagios/sbin +# or for Homebrew: +# cp cgi/*.cgi /usr/local/opt/nagios/cgi-bin + +# - Copy CSS and JavaScript files to a directory served by the web server: +# cp share/nagiosgraph.css /usr/local/nagios/share +# cp share/nagiosgraph.js /usr/local/nagios/share +# or for Homebrew: +# cp share/nagiosgraph.css /usr/local/opt/nagios/share/nagios/htdocs +# cp share/nagiosgraph.js /usr/local/opt/nagios/share/nagios/htdocs + +# - Edit /etc/nagiosgraph/nagiosgraph.conf. Set at least the following: +# logfile = /var/log/nagiosgraph.log +# cgilogfile = /var/log/nagiosgraph-cgi.log +# perflog = /var/nagios/perfdata.log +# rrddir = /var/nagios/rrd +# mapfile = /etc/nagiosgraph/map +# nagiosgraphcgiurl = /nagios/cgi-bin +# javascript = /nagios/nagiosgraph.js +# stylesheet = /nagios/nagiosgraph.css + +# - Set permissions of "rrddir" (as defined in nagiosgraph.conf) so that +# the *nagios* user can write to it and the *www* user can read it: +# mkdir /var/nagios/rrd +# chown nagios /var/nagios/rrd +# chmod 755 /var/nagios/rrd + +# - Set permissions of "logfile" so that the *nagios* user can write to it: +# touch /var/log/nagiosgraph.log +# chown nagios /var/log/nagiosgraph.log +# chmod 644 /var/log/nagiosgraph.log + +# - Set permissions of "cgilogfile" so that the *www* user can write to it: +# touch /var/log/nagiosgraph-cgi.log +# chown www /var/log/nagiosgraph-cgi.log +# chmod 644 /var/log/nagiosgraph-cgi.log + +# - Ensure that the *nagios* user can create and delete perfdata files: +# chown nagios /var/nagios +# chmod 755 /var/nagios + +# - In the Nagios configuration file (nagios.cfg) add this: + +# process_performance_data=1 +# service_perfdata_file=/var/nagios/perfdata.log +# service_perfdata_file_template=$LASTSERVICECHECK$||$HOSTNAME$||$SERVICEDESC$||$SERVICEOUTPUT$||$SERVICEPERFDATA$ +# service_perfdata_file_mode=a +# service_perfdata_file_processing_interval=30 +# service_perfdata_file_processing_command=process-service-perfdata + +# - In the Nagios commands file (commands.cfg) add this: + +# define command { +# command_name process-service-perfdata +# command_line /usr/local/nagios/libexec/insert.pl +# } + +# - Check the nagios configuration + +# /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg + +# - Restart nagios + +# /etc/init.d/nagios restart + +# - Verify that nagiosgraph is working by running showconfig.cgi + +# http://server/nagios/cgi-bin/showconfig.cgi + +# - Try graphing some data by running show.cgi + +# http://server/nagios/cgi-bin/show.cgi + +# - In the Nagios configuration, add a template for graphed services: + +# define service { +# name graphed-service +# action_url /nagiosgraph/cgi-bin/show.cgi?host=$HOSTNAME$&service=$SERVICEDESC$' onMouseOver='showGraphPopup(this)' onMouseOut='hideGraphPopup()' rel='/nagiosgraph/cgi-bin/showgraph.cgi?host=$HOSTNAME$&service=$SERVICEDESC$&period=week&rrdopts=-w+450+-j +# register 0 +# } + +# - Enable graph links for services by appending the graphed-service to existing +# service definitions in the Nagios configuration: + +# define service { +# use local-service,graphed-service +# ... +# } + +# - Replace the Nagios action icon with the nagiosgraph graph icon: +# mv /usr/local/nagios/share/images/action.gif /usr/local/nagios/share/images/action.gif-orig +# cp share/graph.gif /usr/local/nagios/share/images/action.gif + +# - In the nagiosgraph SSI file, set the URL for nagiosgraph.js: +# vi share/nagiosgraph.ssi +# src="/nagiosgraph/nagiosgraph.js" -> src="/nagios/nagiosgraph.js" + +# - Install the nagiosgraph SSI file: +# cp share/nagiosgraph.ssi /usr/local/nagios/share/ssi/common-header.ssi + +# - Add links to graphs in the Nagios sidebar (side.php or side.html): + +# + +# - Check the nagios configuration + + /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg + + systemctl restart nagios + } +} + + +# +# OUTFILE1="$nagdir/nrpe_rule.te" +# # TITLE="nrpe_rule" +# define NRPE_RULE << 'EOF' +# module nrpe_rule 1.0; + +# require { +# type nrpe_t; +# type proc_net_t; +# class file { open read }; +# class file { ioctl open read getattr }; +# } + +# #=================== nrpe_t ========================= +# allow nrpe_t proc_net_t:file open; +# allow nrpe_t proc_net_t:file read; +# allow nrpe_t proc_net_t:file { getattr ioctl }; +# EOF +# { +# printf "%s\n" "$NRPE_RULE" | cut -c 3- +# } > "$OUTFILE1" +# checkmodule -M -m -o $nagdir/nrpe_rule.mod $nagdir/nrpe_rule.te +# semodule_package -o $nagdir/nrpe_rule.pp -m $nagdir/nrpe_rule.mod +# semodule -i $nagdir/nrpe_rule.pp +# semanage permissive -a nrpe_t +# ${PAKMGR} install nrpe nrpe-selinux nagios-plugins nagios-plugins-all nagios-plugins-uptime nagios-plugins-oracle nagios-plugins-check-updates + + +# sed -i "/^allowed_hosts/c\allowed_hosts=127.0.0.1,::1,$IPADD" $nrpecfg +# sed -i "/^#command\[check_load\]/c\command[check_uptime]=$nagdir/check_uptime" $nrpecfg +# sed -i "/^command\[check_load\]/c\command\[check_load\]=$nagdir/check_load -r -w 6,4,2 -c 12,10,7" $nrpecfg +# sed -i "/^command\[check_hda1\]/c\command[check_hda1]=$nagdir/check_disk -w 15% -c 10% -p /dev/sda3" $nrpecfg +# sed -i "/^command\[check_zombie_procs\]/c\# command[check_zombie_procs]=$nagdir/check_procs -w 5 -c 10 -s Z" $nrpecfg +# sed -i "/^command\[check_total_procs\]/c\command[check_total_procs]=$nagdir/check_procs -w 250 -c 300 -s RSZDT" $nrpecfg +# sed -i "/^#command\[check_users\]/c\command[check_net]=$nagdir/check_net" $nrpecfg +# sed -i "/^#command\[check_swap\]/c\command[check_swap]=$nagdir/check_swap -w 20% -c 10%" $nrpecfg +# sed -i "/^#command\[check_mem\]/c\command[check_mem]=$nagdir/check_mem" $nrpecfg +# if [ "${OS}" = ubuntu ]; then +# sed -i "/^#command\[check_apt\]/c\command[check_apt]=$nagdir/check_apt/" $nrpecfg +# else +# sed -i "/^#command\[check_yum\]/c\command[check_yum]=$nagdir/check_updates" $nrpecfg +# fi +# sed -i "/^#command\[check_all_procs\]/c\command[check_logic]=$nagdir/check_http -p 7011" $nrpecfg +# sed -i "/^#command\[check_procs\]/c\command[check_oracle]=$nagdir/check_http -p 8010" $nrpecfg +# sed -i "/^#command\[check_disk\]/c\command[check_ping]=$nagdir/check_ping 127.0.0.1 -w 100.0,20% -c 500.0,60%" $nrpecfg +# sed -i "/^#command\[check_cpu_stats\]/c\command[check_ssh]=$nagdir/check_ssh" $nrpecfg + +# } +# } + +###################### +#### HTTP Install #### +###################### +# function install_http() { +# { +# if [ "${OS}" = ubuntu ]; then +# if [ $HTTP = apache ]; then +# echo "Apache" +# else +# echo "Nginx" +# fi +# echo "something" +# else +# if [ $HTTP = apache ]; then +# echo "Apache" +# else +# echo "Nginx" +# fi +# fi +# } +# } + +nagios_install +# install_http + + +# # SAMPLE CONFIG SNIPPETS FOR APACHE WEB SERVER +# # +# # This file contains examples of entries that need +# # to be incorporated into your Apache web server +# # configuration file. Customize the paths, etc. as +# # needed to fit your system. + +# ScriptAlias /nagios/cgi-bin "/usr/local/nagios/sbin" + +# +# # SSLRequireSSL +# Options ExecCGI +# AllowOverride None +# = 2.3> +# +# Require all granted +# # Require host 127.0.0.1 + +# AuthName "Nagios Access" +# AuthType Basic +# AuthUserFile /usr/local/nagios/etc/htpasswd.users +# Require valid-user +# +# +# +# Order allow,deny +# Allow from all +# # Order deny,allow +# # Deny from all +# # Allow from 127.0.0.1 + +# AuthName "Nagios Access" +# AuthType Basic +# AuthUserFile /usr/local/nagios/etc/htpasswd.users +# Require valid-user +# +# + +# Alias /nagios "/usr/local/nagios/share" + +# +# # SSLRequireSSL +# Options None +# AllowOverride None +# = 2.3> +# +# Require all granted +# # Require host 127.0.0.1 + +# AuthName "Nagios Access" +# AuthType Basic +# AuthUserFile /usr/local/nagios/etc/htpasswd.users +# Require valid-user +# +# +# +# Order allow,deny +# Allow from all +# # Order deny,allow +# # Deny from all +# # Allow from 127.0.0.1 + +# AuthName "Nagios Access" +# AuthType Basic +# AuthUserFile /usr/local/nagios/etc/htpasswd.users +# Require valid-user +# +# +# wget https://assets.nagios.com/downloads/nagioscore/releases/nagios-4.4.7.tar.gz +# tar xzf nagios-4.4.7.tar.gz +# cd nagios-4.4.7 || exit +# if [ "${OS}" = ubuntu ]; then +# ./configure --with-httpd-conf=/etc/apache2/sites-enabled +# else +# ./configure --with-httpd-conf=/etc/httpd/conf.d +# fi +# make all +# make install-groups-users +# if [ "${OS}" = ubuntu ]; then +# usermod -aG nagios www-data +# else +# usermod -aG nagios apache +# fi +# make install +# make install-init +# make install-daemoninit +# make install-commandmode +# make install-config +# make install-webconf +# if [ "${OS}" = ubuntu ]; then +# a2enmod rewrite cgi +# fi + +# fi +# if [ ! "$(command -v wget)" ]; then +# ${PAKMGR} install wget +# fi +# ndir1=/usr/lib/nagios/plugins +# ndir2=/usr/lib64/nagios/plugins +# #nrpecfg=/etc/nagios/nrpe.cfg +# if [ -d $ndir1 ]; then +# nagdir=$ndir1 +# elif [ -d $ndir2 ]; then +# nagdir=$ndir2 +# fi +# define () { +# IFS=$'\n' read -r -d '' "$1" +# } \ No newline at end of file diff --git a/PdnsInstall.sh b/PdnsInstall.sh new file mode 100644 index 0000000..0f15594 --- /dev/null +++ b/PdnsInstall.sh @@ -0,0 +1,1302 @@ +#!/bin/bash + +###################################################################################### +#### Version 2.2 #### +#### For questions or comments contact@mylinux.work #### +#### Author : Phil Connor #### +#### #### +#### Notes : #### +#### This script is a simple "helper" to install and configure Maria, #### +#### PowerDNS and PowerAdmin on RedHat Based servers. #### +#### There is no silver bullet. Don't expect the perfect setup, #### +#### review comments and adapt the parameters to your application usage. #### +#### #### +#### Use this script at your OWN risk. There is no guarantee whatsoever. #### +#### #### +#### Usage chmod 755 then ./PdnsInstall.sh or bash PdnsInstall.sh #### +###################################################################################### + +######################## +#### User Variables #### +######################## +MYSQL_PASS='Password@123' # <-- Your MySql root Password here +MY_PDNS_USR=pdns # <-- The username for your PowerDNS connect to DB +MY_PDNS_DB=powerdns # <-- The name for your PowerDNS DB +MY_PDNS_PW=somepassword # <-- The password you wantt for you PowerDNS DB +MY_PDNS_HOST=localhost # <-- The default here is localhost, but can be set to a remote host if you have configured that +DEL_MY_CNF=Y # <-- Place a Capital Y for yes or N for no here to delete /root/.my.cnf when db_instal function is done +WEB_HOST_NAME=test1.linuxcomputer.cloud # <-- The FQDN of your server goes here +EMAIL=admin@$WEB_HOST_NAME # <-- This is the email you want to use for Let's Encrypt registations +HTTP=nginx # <-- Choose apache or nginx --> The apache Config is in BETA TESTING please only choose nginx unless you know what your doing + +########################## +#### System Variables #### +########################## +ip4=$(/sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1) +host=$(hostname -f) + +if [ "$(command -v lsb_release)" ]; then + OS=$(lsb_release -i | awk '{print $3}' | tr '[:upper:]' '[:lower:]') + OSVER=$(lsb_release -r | awk '{print $2}' | awk -F. '{print $1}') +else + OS=$(grep PRETTY_NAME /etc/os-release | sed 's/PRETTY_NAME=//g' | tr -d '="' | awk '{print $1}' | tr '[:upper:]' '[:lower:]') + OSVER=$(grep VERSION_ID /etc/os-release | sed 's/VERSION_ID=//g' | tr -d '="' | awk -F. '{print $1}') +fi + +########################################################### +#### Detect Package Manger from OS and OSVer Variables #### +########################################################### +if [[ ${OS} = alma || ${OS} = amazon || ${OS} = centos || ${OS} = red || ${OS} = rocky || ${OS} = oracle ]]; then + if [ "${OSVER}" = 7 ]; then + PAKMGR="yum -y" + else + PAKMGR="dnf -y" + fi +elif [ "${OS}" = ubuntu ]; then + PAKMGR="apt -y" +fi + +########################## +#### Detect Root User #### +########################## +function check_RootUser() { + #if [ "$(id -u)" != "0" ]; then + if [ "$(whoami)" != 'root' ]; then + echo "You dont have permission to run $0 as non-root user. Use sudo su -" + exit 1 + fi + +} + +#################### +#### Code Start #### +#################### + +######################### +#### Install MariaDB #### +######################### +function install_mysql() { + { + if [ ! "$(command -v mysql)" ]; then + if [ "${OS}" = ubuntu ]; then + ${PAKMGR} update + ${PAKMGR} install mariadb-client mariadb-server + else + ${PAKMGR} install mariadb mariadb-server + fi + fi + systemctl enable --now mariadb + } +} + +###################### +#### Secure MySQL #### +###################### +function secure_mysql() { + { + if [ ! "$(command -v expect)" ]; then + ${PAKMGR} install expect + fi + + expect -f - <<-EOF + set timeout 10 + spawn mysql_secure_installation + expect "Enter current password for root (enter for none):" + send -- "\r" + expect "Set root password?" + send -- "y\r" + expect "New password:" + send -- "${MYSQL_PASS}\r" + expect "Re-enter new password:" + send -- "${MYSQL_PASS}\r" + expect "Remove anonymous users?" + send -- "y\r" + expect "Disallow root login remotely?" + send -- "y\r" + expect "Remove test database and access to it?" + send -- "y\r" + expect "Reload privilege tables now?" + send -- "y\r" + expect eof +EOF + } +} + +################################### +#### Install PowerDNS DataBase #### +################################### +function pdns_db_install() { + { + define () { + IFS=$'\n' read -r -d '' "$1" + } + + if [ ! -f /root/.my.cnf ]; then + { + echo '[mysql]' + echo 'user=root' + echo "password=$MYSQL_PASS" + } >/root/.my.cnf + fi + + mysql -e "CREATE DATABASE $MY_PDNS_DB /*\!40100 DEFAULT CHARACTER SET utf8 */;" + mysql -e "CREATE USER $MY_PDNS_USR@localhost IDENTIFIED BY '$MY_PDNS_PW';" + mysql -e "GRANT ALL PRIVILEGES ON $MY_PDNS_DB.* TO '$MY_PDNS_USR'@'localhost';" + mysql -e "ALTER USER '$MY_PDNS_DB'@'localhost' IDENTIFIED BY '$MY_PDNS_PW';" + mysql -e "FLUSH PRIVILEGES;" + + touch /tmp/pdns.sql + OUTFILE="/tmp/pdns.sql" + define PDNS_SQL << 'EOF' + CREATE TABLE domains ( + id INT AUTO_INCREMENT, + name VARCHAR(255) NOT NULL, + master VARCHAR(128) DEFAULT NULL, + last_check INT DEFAULT NULL, + type VARCHAR(6) NOT NULL, + notified_serial INT UNSIGNED DEFAULT NULL, + account VARCHAR(40) CHARACTER SET 'utf8' DEFAULT NULL, + PRIMARY KEY (id) + ) Engine=InnoDB CHARACTER SET 'latin1'; + + CREATE UNIQUE INDEX name_index ON domains(name); + + + CREATE TABLE records ( + id BIGINT AUTO_INCREMENT, + domain_id INT DEFAULT NULL, + name VARCHAR(255) DEFAULT NULL, + type VARCHAR(10) DEFAULT NULL, + content VARCHAR(64000) DEFAULT NULL, + ttl INT DEFAULT NULL, + prio INT DEFAULT NULL, + disabled TINYINT(1) DEFAULT 0, + ordername VARCHAR(255) BINARY DEFAULT NULL, + auth TINYINT(1) DEFAULT 1, + PRIMARY KEY (id) + ) Engine=InnoDB CHARACTER SET 'latin1'; + + CREATE INDEX nametype_index ON records(name,type); + CREATE INDEX domain_id ON records(domain_id); + CREATE INDEX ordername ON records (ordername); + + + CREATE TABLE supermasters ( + ip VARCHAR(64) NOT NULL, + nameserver VARCHAR(255) NOT NULL, + account VARCHAR(40) CHARACTER SET 'utf8' NOT NULL, + PRIMARY KEY (ip, nameserver) + ) Engine=InnoDB CHARACTER SET 'latin1'; + + + CREATE TABLE comments ( + id INT AUTO_INCREMENT, + domain_id INT NOT NULL, + name VARCHAR(255) NOT NULL, + type VARCHAR(10) NOT NULL, + modified_at INT NOT NULL, + account VARCHAR(40) CHARACTER SET 'utf8' DEFAULT NULL, + comment TEXT CHARACTER SET 'utf8' NOT NULL, + PRIMARY KEY (id) + ) Engine=InnoDB CHARACTER SET 'latin1'; + + CREATE INDEX comments_name_type_idx ON comments (name, type); + CREATE INDEX comments_order_idx ON comments (domain_id, modified_at); + + + CREATE TABLE domainmetadata ( + id INT AUTO_INCREMENT, + domain_id INT NOT NULL, + kind VARCHAR(32), + content TEXT, + PRIMARY KEY (id) + ) Engine=InnoDB CHARACTER SET 'latin1'; + + CREATE INDEX domainmetadata_idx ON domainmetadata (domain_id, kind); + + + CREATE TABLE cryptokeys ( + id INT AUTO_INCREMENT, + domain_id INT NOT NULL, + flags INT NOT NULL, + active BOOL, + published BOOL DEFAULT 1, + content TEXT, + PRIMARY KEY(id) + ) Engine=InnoDB CHARACTER SET 'latin1'; + + CREATE INDEX domainidindex ON cryptokeys(domain_id); + + + CREATE TABLE tsigkeys ( + id INT AUTO_INCREMENT, + name VARCHAR(255), + algorithm VARCHAR(50), + secret VARCHAR(255), + PRIMARY KEY (id) + ) Engine=InnoDB CHARACTER SET 'latin1'; + + CREATE UNIQUE INDEX namealgoindex ON tsigkeys(name, algorithm); +EOF + { + printf "%s\n" "$PDNS_SQL" | cut -c 2- + } > "$OUTFILE" + if [ ${DEL_MY_CNF} != N ]; then + rm -rf /root/.my.cnf + fi + mysql -D powerdns < /tmp/pdns.sql + rm /tmp/pdns.sql + } +} + +#################################### +#### Install/Configure PowerDNS #### +#################################### +function pdns_app_install() { + { + if [ "${OS}" = ubuntu ]; then + if systemctl is-enabled systemd-resolved; then + systemctl disable --now systemd-resolved + systemctl mask systemd-resolved + sed -i 's/nameserver /#nameserver /g' /etc/resolv.conf + echo -e 'nameserver 8.8.8.8 \nnameserver 8.8.4.4' >> /etc/resolv.conf + fi + DEBIAN_FRONTEND=noninteractive ${PAKMGR} install pdns-backend-mysql fpdns bind9utils + else + ${PAKMGR} install epel-release + ${PAKMGR} install http://rpms.remirepo.net/enterprise/remi-release-8.rpm + ${PAKMGR} install pdns-backend-mysql pdns bind-utils + expect -f - <<-EOF + set timeout 2 + spawn dnf module enable php:remi-7.4 + expect "Is this ok:" + send -- "y\r" + expect eof +EOF + fi + + echo "" >/etc/pdns/pdns.conf + cat >/etc/pdns/pdns.conf <' + echo " ServerAdmin admin@n$WEB_HOST_NAME" + echo " ServerName $WEB_HOST_NAME" + echo " DocumentRoot /var/www/html/$WEB_HOST_NAME" + echo ' #DirectoryIndex index.php' + echo " #ErrorLog /var/log/httpd/$WEB_HOST_NAME-error.log" + echo " #CustomLog /var/log/httpd/$WEB_HOST_NAME-access.log combined" + echo '' + echo ' ' + echo ' ' + if [ "${OS}" = ubuntu ]; then + echo ' SetHandler "proxy:unix:/run/php-fpm/www.sock|fcgi://localhost"' + else + echo ' SetHandler "proxy:unix:/var/opt/remi/php74/run/php-fpm/www.sock|fcgi://localhost"' + fi + echo ' ' + echo ' ' + echo '' + } > $path + + + if [ "${OS}" = ubuntu ]; then + if ! apachectl configtest; then + echo '' + echo -e '\e[01;37m -----------------------------------------------------------------------------------------------------' + echo -e "\e[01;31m An Error was detected with apache2, Please manually look at the configuration to comfirm it's good" >&2 + echo -e '\e[01;37m -----------------------------------------------------------------------------------------------------' + exit 1 + fi + else + if ! httpd -t; then + echo '' + echo -e '\e[01;37m ----------------------------------------------------------------------------------------------------' + echo -e "\e[01;31m An Error was detected with httpd, Please manually look at the configuration to comfirm it's good" >&2 + echo -e '\e[01;37m ----------------------------------------------------------------------------------------------------' + exit 1 + fi + fi + + if [ "${OS}" = ubuntu ]; then + systemctl enable --now php-fpm + a2dissite 000-default + a2ensite $WEB_HOST_NAME + systemctl enable apache2 + systemctl reload apache2 + else + chcon -R -t httpd_sys_content_t /var/www/html/$WEB_HOST_NAME + systemctl enable --now php74-php-fpm + systemctl enable --now httpd + fi + elif [ $HTTP = nginx ]; then + if [ "${OS}" = ubuntu ]; then + ${PAKMGR} install build-essential php php-cli php-dev php-fpm php-gd php-intl php-json php-mysql php-pear php-xml php-xmlrpc php-mbstring gettext libmcrypt-dev + pecl channel-update pecl.php.net + pecl update-channels + expect -f - <<-EOF + set timeout 10 + spawn pecl install mcrypt + expect "libmcrypt prefix?" + send -- "\r" + expect eof +EOF + sed -i 's/;extension=shmop/extension=mcrypt.so/g' /etc/php/*/cli/php.ini + sed -i 's/;extension=shmop/extension=mcrypt.so/g' /etc/php/*/apache2/php.ini + systemctl disable --now apache2 + systemctl mask apache2 + if ! php -m | grep mcrypt; then + echo '' + echo 'mcrypt did not install correctly on this Ubuntu machine...!' + exit 1 + systemctl disable --now httpd + systemctl mask httpd + fi + else + ${PAKMGR} install php php-fpm php-cli php-mysqlnd php-pecl-mcrypt php-json php-intl + chown apache:apache /var/lib/php/sessions + systemctl disable --now httpd + systemctl mask httpd + fi + fi + + ${PAKMGR} install nginx + + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + if ! grep "listen = /run/php-fpm/www.sock" /etc/php-fpm.d/www.conf; then + sed -i '/listen = */c\listen = \/run\/php-fpm\/www.sock' /etc/php-fpm.d/www.conf + fi + fi + + if [ "${OS}" = ubuntu ]; then + path=/etc/nginx/sites-available/$WEB_HOST_NAME.conf + else + path=/etc/nginx/conf.d/$WEB_HOST_NAME.conf + fi + # shellcheck disable=SC2016 + { + echo 'server {' + echo " server_name $WEB_HOST_NAME;" + echo ' listen 80;' + echo '' + echo " root /var/www/html/$WEB_HOST_NAME;" + echo " #access_log /var/log/nginx/$WEB_HOST_NAME-access_log;" + echo " #error_log /var/log/nginx/$WEB_HOST_NAME-error_log;" + echo '' + echo ' index index.php;' + echo '' + echo ' location / {' + echo ' try_files $uri $uri/ /index.php?query_string;' + echo ' }' + echo '' + echo ' location ~ \.php$ {' + echo ' fastcgi_index index.php;' + echo ' fastcgi_split_path_info ^(.+\.php)(.*)$;' + echo ' fastcgi_keep_conn on;' + echo ' include /etc/nginx/fastcgi_params;' + if [ "${OS}" = ubuntu ]; then + echo ' fastcgi_pass unix:/run/php/php-fpm.sock;' + else + echo ' fastcgi_pass unix:/run/php-fpm/www.sock;' + fi + echo ' fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;' + echo ' }' + echo '' + echo ' location ~/\.ht {' + echo ' deny all;' + echo ' }' + echo '' + echo '}' + } > $path + + if ! nginx -t; then + echo '' + echo -e '\e[01;37m --------------------------------------------------------------------------------------------------' + echo -e "\e[01;31m An Error was detected with nginx, Please manually look at the configuration to comfirm it's good" >&2 + echo -e '\e[01;37m --------------------------------------------------------------------------------------------------' + exit 1 + fi + + if [ "${OS}" = ubuntu ]; then + rm /etc/nginx/sites-enabled/default + ln -s /etc/nginx/sites-available/$WEB_HOST_NAME.conf /etc/nginx/sites-enabled/$WEB_HOST_NAME + systemctl enable --now php-fpm + systemctl enable nginx + systemctl start nginx + else + systemctl enable --now php-fpm + systemctl enable nginx + chcon -R -t httpd_sys_content_t /var/www/html/$WEB_HOST_NAME + systemctl start nginx + fi + } +} + +############################ +#### Install PowerAdmin #### +############################ +function pdns_admin_install() { + { + if [ ! -d /var/www/html/$WEB_HOST_NAME ]; then + mkdir -p /var/www/html/$WEB_HOST_NAME + fi + + ${PAKMGR} install git + cd /var/www/html/$WEB_HOST_NAME || exit + git clone https://github.com/poweradmin/poweradmin.git + mv poweradmin/* . + rm -rf poweradmin/ + find /var/www/html/$WEB_HOST_NAME/ -type d -exec chmod 755 {} \; + find /var/www/html/$WEB_HOST_NAME/ -type f -exec chmod 644 {} \; + if [ "${OS}" = ubuntu ]; then + chown www-data:www-data /var/www/html/$WEB_HOST_NAME/ + else + chown apache:apache /var/www/html/$WEB_HOST_NAME/ + chown apache:apache /var/lib/php/session + fi + } +} + +########################################## +#### Install Certbot and request Cert #### +########################################## +install_certbot() { + { + if [ $HTTP = apache ]; then + ${PAKMGR} install python3-certbot-apache + systemctl enable --now httpd + elif [ $HTTP = nginx ]; then + ${PAKMGR} install python3-certbot-nginx + systemctl enable --now nginx + fi + + ################################################################################################# + #### Be sure that your domain has the proper dns entry or this will not work. #### + #### #### + #### If your domain is not properly configured and you know it, or you just wanna #### + #### test that you can get a cert uncomment this line #### + #### #### + #### certbot certonly --redirect --agree-tos --nginx -d $WEB_HOST_NAME -m "$EMAIL" --dry-run #### #### + #### and comment out this line #### + #### certbot --non-interactive --redirect --agree-tos -d $WEB_HOST_NAME -m "$EMAIL" #### + ################################################################################################# + + if [ $HTTP = apache ]; then + certbot certonly --redirect --agree-tos --apache -d $WEB_HOST_NAME -m "$EMAIL" --dry-run -v + #certbot --non-interactive --redirect --agree-tos --apache -d $WEB_HOST_NAME -m "$EMAIL" + systemctl restart httpd + elif [ $HTTP = nginx ]; then + certbot certonly --redirect --agree-tos --nginx -d $WEB_HOST_NAME -m "$EMAIL" --dry-run -v + #certbot --non-interactive --redirect --agree-tos --nginx -d $WEB_HOST_NAME -m "$EMAIL" + systemctl restart nginx + fi + + if [ "${OS}" = ubuntu ]; then + if ! grep "certbot" /var/spool/cron/crontab/root; then + echo "0 */12 * * * root certbot -q renew" >>/etc/crontab + fi + else + if ! grep "certbot" /var/spool/cron/root; then + echo "0 */12 * * * root certbot -q renew" >>/var/spool/cron/root + fi + fi + } +} + +####################### +#### Final Message #### +####################### +function install_complete() { + { + if [ ! -d /etc/letsencrypt/live/$WEB_HOST_NAME ]; then + echo -e '\e[01;37m ----------------------------------------------------------------------------------------------------' + echo -e '\e[01;37m -----------------------------------------------------------------------------------------------------------' + echo -e "\e[01;32m You should now be able to complete the Poweradmin setup by accessing it here http://$host/install/ or by ip http://$ip4/install/" + echo -e '\e[01;37m -----------------------------------------------------------------------------------------------------------' + echo -e '\e[01;37m ----------------------------------------------------------------------------------------------------' + else + echo -e '\e[01;37m ----------------------------------------------------------------------------------------------------' + echo -e '\e[01;37m -----------------------------------------------------------------------------------------------------------' + echo -e "\e[01;32m You should now be able to complete the Poweradmin setup by accessing it here https://$host/install/ or by ip https://$ip4/install/" + echo -e '\e[01;37m -----------------------------------------------------------------------------------------------------------' + echo -e '\e[01;37m ----------------------------------------------------------------------------------------------------' + fi + } +} + +################## +#### Code End #### +################## + +check_RootUser +install_mysql +secure_mysql +pdns_db_install +pdns_app_install +webserver_install +pdns_admin_install +install_certbot +install_complete + +mysql -e "CREATE DATABASE powerdns /*\!40100 DEFAULT CHARACTER SET utf8 */;" +mysql -e "CREATE USER pdns@localhost IDENTIFIED BY '$MY_PDNS_PW';" +mysql -e "GRANT ALL PRIVILEGES ON powerdns.* TO 'pdns'@'localhost';" +# mysql -e "ALTER USER 'pdns'@'localhost' IDENTIFIED BY 'linda6!3!';" +mysql -e "FLUSH PRIVILEGES;" + + +6xt3gXm?+5D6 \ No newline at end of file diff --git a/SecureIt.sh b/SecureIt.sh new file mode 100644 index 0000000..39f5bfd --- /dev/null +++ b/SecureIt.sh @@ -0,0 +1,3984 @@ +#!/bin/bash + +############################################################################### +#### Hardening Script for Oracle Linux, Centos/Redhat and Ubuntu Servers. #### +#### Author: Phil Connor 02/10/2020 #### +#### Contact: contact@mylinux.work #### +#### Version 3.30.03.26.22 #### +#### #### +#### To Use chmod to 755 or simply type bash #### +############################################################################### + +clear +export TERM=xterm-256color + +############################ +#### User Configuration #### +############################ +RSWP=8 # <-- Set the required swap size +TCPPORTS=( 22 53 1521 5666 7001 7002 8000 9090 10000 ) # <-- Firwall ports that you need open, don't remove 22 unless you will only contecting with a console +TCP6PORTS=( 22 ) # <-- IPv6 is disabled but Nessus scans requires it configured +UDPPORTS=( 53 ) # <-- Gotta have DNS +UDP6PORTS=( 53 ) # <-- Gotta have DNS + +########################## +#### System Variables #### +########################## +BACKUP="/root/config_Backups" +BOOTLD="/boot/grub2/user.cfg" +BOOTLDCE="/boot/efi/EFI/centos/" +BOOTLDRH="/boot/efi/EFI/redhat/" +BOOTLDUB="/boot/grub/user.cfg" +CRON_RH="/var/spool/cron/root" +CRON_UB="/var/spool/cron/crontab/root" +FIREIP="echo ${VLANIP// /}" +IPTBL="/etc/sysconfig/iptables" +IP6TBL="/etc/sysconfig/ip6tables" +IPTBLUB="/etc/iptables/rules.v4" +IP6TBLUB="/etc/iptables/rules.v6" +GRUBCFG="/boot/grub2/grub.cfg" +GRUBCFGCE="/boot/efi/EFI/centos/grub.cfg" +GRUBCFGRH="/boot/efi/EFI/redhat/grub.cfg" +GRUBCFGUB="/boot/grub/grub.cfg" +HOSTNAME=$(uname -n) +LOG=${BACKUP}/install.log +MODPRO="/etc/modprobe.d/cis.conf" +MYIP=$(netstat -putan | awk '/:22 / && /ESTABLISHED/ {split($5,result,":"); print result[1]}') +NTP_FILE="/etc/ntp.conf" + +if [ "$(command -v lsb_release)" ]; then + OS=$(lsb_release -i | awk '{print $3}' | tr '[:upper:]' '[:lower:]') + OSVER=$(lsb_release -r | awk '{print $2}' | awk -F. '{print $1}') +else + OS=$(grep PRETTY_NAME /etc/os-release | sed 's/PRETTY_NAME=//g' | tr -d '="' | awk '{print $1}' | tr '[:upper:]' '[:lower:]') + OSVER=$(grep VERSION_ID /etc/os-release | sed 's/VERSION_ID=//g' | tr -d '="' | awk -F. '{print $1}') +fi + +SSHD_FILE='/etc/ssh/sshd_config' +TMPMNT="/usr/lib/systemd/system" + +######################## +#### Menu Variables #### +######################## +H1=20 +R1=3 +R2=6 +R3=11 +W1=80 + +########################################################### +#### Detect Package Manger from OS and OSVer Variables #### +########################################################### +if [[ ${OS} = alma || ${OS} = amazon || ${OS} = centos || ${OS} = red || ${OS} = rocky || ${OS} = oracle ]]; then + if [ "${OSVER}" = 7 ]; then + PAKMGR="yum -y" + else + PAKMGR="dnf -y" + fi +elif [ "${OS}" = ubuntu ]; then + PAKMGR="apt -y" +fi + +############################################## +#### Check to see if running as Root User #### +############################################## +function check_root() { + { + if [ $EUID -ne 0 ]; then + echo "" + echo "Script Installation has been Halted!" + echo "" + echo "You Must Run This Script as the \"ROOT\" User" + exit + fi + } +} + +################################# +#### Config backup directory #### +################################# +function backup() { + { + for dir in ${BACKUP}; do + [[ ! -d "$dir" ]] && mkdir "$dir" + touch ${BACKUP}/install.log + done + } +} + +####################### +#### Copy Function #### +####################### +function no_show() { + { + expand | awk 'NR == 1 {match($0, /^ */); l = RLENGTH + 1} + {print substr($0, l)}' + } +} + +########################## +#### Spinner Function #### +########################## +function _spinner() { + { + local on_success="COMPLETE" + local on_fail="ERROR" + local green="\e[1;32m" + local red="\e[1;31m" + local nc="\e[0m" + case $1 in + start) + ((column=$(tput cols)-${#2}-8)) + echo -ne "\e[7m ${2} \e[0m \n" + printf "%${column}s" + i=1 + sp='/-\|/-\:' + delay=${SPINNER_DELAY:-0.15} + while : + do + printf "\b%s${sp:i++%${#sp}:1}" + sleep "$delay" + done + ;; + stop) + if [[ -z ${3} ]]; then + echo "spinner is not running.." + exit 1 + fi + kill "$3" > /dev/null 2>&1 + echo -en "\b[" + if [[ $2 -eq 0 ]]; then + echo -en "${green}${on_success}${nc}" + else + echo -en "${red}${on_fail}${nc}" + fi + echo -e "]" + ;; + *) + echo "invalid argument, try {start/stop}" + exit 1 + ;; + esac + } +} + +####################### +#### Spinner Start #### +####################### +function start_spinner { + { + echo "" + _spinner "start" "${1}" & + _sp_pid=$! + echo "" + disown + } +} + +###################### +#### Spinner Stop #### +###################### +function stop_spinner { + { + echo "" + _spinner "stop" "$1" $_sp_pid + unset _sp_pid + echo "" + } +} + +######################### +#### Warning Message #### +######################### +function warn_message() { + { + whiptail --backtitle "SecureIt contact@mylinux.work" --title "*** WARNING ***" --yes-button "CONFIRM" --no-button "Exit" --defaultno --yesno " Running this script will harden this server to CIS Benchmark settings. + It will change server configuration and will affect server operation + + + ONLY RUN THIS SCRIPT IF YOU KNOW WHAT YOU ARE DOING! + + + You must select CONFIRM to continue." ${H1} ${W1} + exitstatus=$? + if [ ${exitstatus} = 0 ]; then + private_ip + else + exit + fi + } + +} + +############################# +#### Get VLAN IP address #### +############################# +function private_ip() { + { + VLANIP=$(whiptail --backtitle "SecureIt contact@mylinux.work" --title "Server Connect IP" --ok-button "Continue" --cancel-button "Exit" --inputbox " What is the IP/Sub or VLAN/Sub you use to connect to this server? + + Examples are 192.168.0.0/24 + or 192.168.1.21/32 + or 10.0.10.0/16 + + Your current SSH Connection IP is Shown and can be changed if required" ${H1} ${W1} "${MYIP}"/32 3>&1 1>&2 2>&3) + exitstatus=$? + if [ ${exitstatus} = 0 ]; then + time_zone + else + exit + fi + } +} + +###################### +#### Get TimeZone #### +###################### +function time_zone() { + { + # shellcheck disable=SC2046 + TIMEZONE=$(whiptail --backtitle "SecureIt contact@mylinux.work" --title "Server TimeZone" --ok-button "Continue" --cancel-button "Exit" --menu " What is your Server Timezone? + + Example Central" ${H1} ${W1} ${R3} $(find /usr/share/zoneinfo/US/* | cut -d '/' -f 6 | sort | sed "s/$/ ./" | tr '\n' ' ';) 3>&1 1>&2 2>&3) + exitstatus=$? + if [ ${exitstatus} = 0 ]; then + max_count + else + exit + fi + } +} + +################################## +#### Get Auto Disconnect Time #### +################################## +function max_count() { + { + MAXCOUNT=$(whiptail --backtitle "SecureIt contact@mylinux.work" --title "Server Disconnect" --ok-button "Continue" --cancel-button "Exit" --radiolist " What is the MAX time you want before auto disconnect?" ${H1} ${W1} ${R1} \ + "1" "5 mins" OFF \ + "2" "10 mins" OFF \ + "3" "15 mins" ON 3>&1 1>&2 2>&3) + exitstatus=$? + if [ ${exitstatus} = 0 ]; then + max_logs + else + exit + fi + } +} + +################################ +#### Get Audit logs Setting #### +################################ +function max_logs() { + { + MAXLOGS=$(whiptail --backtitle "SecureIt contact@mylinux.work" --title "Audit Logs" --ok-button "Continue" --cancel-button "Exit" --inputbox " If you plan on archiving the audit logs leave \"ignore\" here + If you have tons of room change this to \"KEEP_LOGS\"" ${H1} ${W1} ignore 3>&1 1>&2 2>&3) + exitstatus=$? + if [ ${exitstatus} = 0 ]; then + syslog_server + else + exit + fi + } +} + +########################### +#### Get Syslog Server #### +########################### +function syslog_server() { + { + SYSLOG=$(whiptail --backtitle "SecureIt contact@mylinux.work" --title "SysLog Server" --ok-button "Continue" --cancel-button "Exit" --inputbox " What is the Name or IP of your SysLog Server?" ${H1} ${W1} 3>&1 1>&2 2>&3) + exitstatus=$? + if [ ${exitstatus} = 0 ]; then + srv_type + else + exit + fi + } +} + +########################## +#### Get Server Usage #### +########################## +function srv_type() { + { + SRVTYPE=$(whiptail --backtitle "SecureIt contact@mylinux.work" --title "Server Disconnect" --ok-button "Continue" --cancel-button "Exit" --radiolist " What is the use or purpose of this server?" ${H1} ${W1} ${R1} \ + "1" "EBS Server" OFF \ + "2" "Weblogic Server" OFF \ + "3" "Regular Server" ON 3>&1 1>&2 2>&3) + exitstatus=$? + if [ ${exitstatus} = 0 ]; then + grub_password + else + exit + fi + } +} + +######################### +#### Get Grub Passwd #### +######################### +function grub_password() { + { + GPASS=$(whiptail --backtitle "SecureIt contact@mylinux.work" --title "Grub Password" --ok-button "Continue" --cancel-button "Exit" --inputbox " What do you want your Grub Password to be?" ${H1} ${W1} 3>&1 1>&2 2>&3) + exitstatus=$? + if [ ${exitstatus} = 0 ]; then + if [ "${OS}" = ubuntu ]; then + G2PASSWD="$(echo -e "${GPASS}\n$GPASS" | grub-mkpasswd-pbkdf2 2>/dev/null | tail --lines=1 | awk -F " " '{print $7}')" + main_menu + else + G2PASSWD="$(echo -e "${GPASS}\n$GPASS" | grub2-mkpasswd-pbkdf2 2>/dev/null | tail --lines=1 | awk -F " " '{print $7}')" + main_menu + fi + else + exit + fi + } +} + +############################# +#### OS Select Main Menu #### +############################# +function main_menu() { + { + while true; do + CHOICE=$(whiptail --backtitle "SecureIt contact@mylinux.work" --title "OS Select Main" --ok-button "Continue" --cancel-button "Exit" --menu " Please Select Your Linux Distro" ${H1} ${W1} ${R2} \ + "1)" "Oracle Linux" \ + "2)" "RedHat/CentOS/Rocky/Alma" \ + "3)" "Ubuntu *** Testing ***" 3>&2 2>&1 1>&3) + exitstatus=$? + if [ ${exitstatus} = 0 ]; then + case ${CHOICE} in + "1)") + oracle_menu + ;; + + "2)") + redhat_menu + ;; + + "3)") + ubuntu_menu + ;; + + "4)") + + ;; + + esac + else + exit + fi + done + } +} + +##################### +#### Oracle Menu #### +##################### +function oracle_menu() { + { + while true; do + CHOICE=$(whiptail --backtitle "SecureIt contact@mylinux.work" --title "Oracle Linux" --ok-button "Install" --cancel-button "Exit" --menu " Please Select Your Oracle Version" ${H1} ${W1} ${R2} \ + "1)" "OCI Oracle Linux 7" \ + "2)" "OCI Oracle Linux 8" \ + "3)" "Oracle Linux 7" \ + "4)" "Oracle Linux 8" 3>&2 2>&1 1>&3) + exitstatus=$? + if [ ${exitstatus} = 0 ]; then + case ${CHOICE} in + "1)") + oci_oracle_ebs_setup + oci_rh_ub_common + oci_only + complete + ;; + + "2)") + oci_oracle_ebs_setup + oci_rh_ub_common + oci_only + complete + ;; + + "3)") + oci_rh_ub_common + complete + ;; + + "4)") + oci_rh_ub_common + complete + ;; + + esac + else + exit + fi + done + } +} + +##################### +#### Redhat Menu #### +##################### +function redhat_menu() { + { + while true; do + CHOICE=$(whiptail --backtitle "SecureIt contact@mylinux.work" --title "Redhat/Centos Linux" --ok-button "Install" --cancel-button "Exit" --menu " Please Select Your Redhat/CentOS Version" ${H1} ${W1} ${R2} \ + "1)" "OCI CentOS 7" \ + "2)" "OCI CentOS 8" \ + "3)" "AWS Redhat/Centos 7" \ + "4)" "AWS Redhat/Centos 8" \ + "5)" "Redhat/CentOS/Rocky/Alma 7" \ + "6)" "Redhat/CentOS/Rocky/Alma 8" \ + "7)" "Redhat/Centos/Rocky/Alma 9" 3>&2 2>&1 1>&3) + exitstatus=$? + if [ ${exitstatus} = 0 ]; then + case ${CHOICE} in + "1)") + oci_rh_ub_common + oci_only + complete + ;; + + "2)") + oci_rh_ub_common + oci_only + complete + ;; + + "3)") + oci_rh_ub_common + aws_only + complete + ;; + + "4)") + oci_rh_ub_common + aws_only + complete + ;; + + "5)") + oci_rh_ub_common + complete + ;; + + "6)") + oci_rh_ub_common + complete + ;; + + "7)") + oci_rh_ub_common + complete + ;; + + esac + else + exit + fi + done + } +} + +##################### +#### Ubuntu Menu #### +##################### +function ubuntu_menu() { + { + while true; do + CHOICE=$(whiptail --backtitle "SecureIt contact@mylinux.work" --title "Ubuntu Linux" --ok-button "Install" --cancel-button "Exit" --menu " Please Select Your Ubuntu Version" ${H1} ${W1} ${R2} \ + "1)" "OCI Ubuntu" \ + "2)" "AWS Ubuntu" \ + "2)" "Ubuntu" 3>&2 2>&1 1>&3) + exitstatus=$? + if [ ${exitstatus} = 0 ]; then + case ${CHOICE} in + "1)") + oci_rh_ub_common + oci_only + complete + ;; + + "2)") + oci_rh_ub_common + aws_only + complete + ;; + + "3)") + oci_rh_ub_common + complete + ;; + + esac + else + exit + fi + done + } +} + +########################## +#### Install Complete #### +########################## +function complete() { + { + whiptail --backtitle "SecureIt contact@mylinux.work" --title "Configuration Complete" --msgbox " This script has configured and hardened this server to + + CIS Level 1 Benchmark settings. + + It is recommended that you try to ssh to the sever as any user + or root to make sure you can connect and once you know all is working + properly the system should be rebooted. + + + Please select \"OK\" to EXIT." ${H1} ${W1} 3>&1 1>&2 2>&3 + exitstatus=$? + if [ ${exitstatus} = 0 ]; then + exit + fi + } +} + ##################################################################### + ### The following is in line with the CIS BenchMark Manual v3.0.0 ### + ##################################################################### + +############################# +#### Make Swap if Needed #### +############################# +function make_swap() { + { + start_spinner 'Configuring Additional Swap Space...' + echo "" + if [ "${SRVTYPE}" -ne 3 ]; then + # size of swapfile in gigabytes + swpsize="$RSWP" + # how large the swap needs to be total in mb's + swpneed=$((swpsize * 1024)) + # / part dir file list + dir=$(ls -la --block-size=M /) + # does the swap file already exist? + swpexist=$(echo "$dir" | grep -i swap | awk '{ print $5 }' | tr -d 'M"') + # what is the name of the swap file if it exist + swpname=$(echo "$dir" | grep -i swap | awk '{ print $9 }') + # Is there any swap present if yes what size is it + swppres=$(free -m | sed -n '3 p' | awk '{ print $2 }') + # If the swap file already exist is it large enough? + if (( swpneed < swpexist )) || (( swpneed < swppres )); then + echo -e '\e[01;37m =======================================================================' + echo -e '\e[01;32m =====================================================================' + echo -e '\e[01;32m ==== \e[01;37m A Large Enough Swapfile was Found! No Changes Needed... \e[01;32m ====' + echo -e '\e[01;32m =====================================================================' + echo -e '\e[01;37m =======================================================================' + elif (( swpneed > swpexist )) || (( swpneed > swppres )); then + echo -e '\e[01;37m ==================================================================================' + echo -e '\e[01;31m ================================================================================' + echo -e '\e[01;31m ==== \e[01;37m A Large Enough Swapfile was not found! Creating Larger SwapFile... \e[01;31m ====' + echo -e '\e[01;31m ================================================================================' + echo -e '\e[01;37m ==================================================================================' + # Turn off existing swap if needing replacement + if echo "$dir" | grep -i swap; then + swapoff /"${swpname}" + rm -f /"$swpname" + fi + # Create the swapfile and make it active + fallocate -l ${swpsize}g /.SwapFile + chmod 600 /.SwapFile + mkswap /.SwapFile + swapon /.SwapFile + echo -e '\e[01;37m ==============================================================================' + echo -e '\e[01;32m ============================================================================' + echo -e '\e[01;32m ==== \e[01;37m Checking whether the swap space was mounted and active or not! \e[01;32m ====' + echo -e '\e[01;32m ============================================================================' + echo -e '\e[01;37m ==============================================================================' + R=$(swapon -s) + if [ -n "$R" ]; then + echo -e '\e[01;32m ============' + echo -e '\e[01;32m ============' + echo -e '\e[01;32m ============================================================================' + echo -e "\e[01;37m$R" + echo -e '\e[01;32m ============================================================================' + echo -e '\e[01;37m ==============================================================================' + else + echo -e '\e[01;31m ============' + echo -e '\e[01;31m ============' + echo -e '\e[01;31m ============================================================================' + echo -e "\e[01;37m Something Went Wrong no Swap was Loaded" + echo -e '\e[01;31m ============================================================================' + echo -e '\e[01;37m ==============================================================================' + fi + # Check to see if the created swap is losted in the fstab file + if ! grep -q "SwapFile" /etc/fstab; then + echo "/.SwapFile swap swap defaults 0 0" >> /etc/fstab + fi + fi + fi + stop_spinner $? + } | tee -a $LOG +} + +############################ +#### Set Sever TimeZone #### +############################ +function time_set() { + { + start_spinner 'Setting System TimeZone...' + echo "" + timedatectl set-timezone US/"${TIMEZONE}" + stop_spinner $? + } | tee -a $LOG +} + +######################################## +### 1.1.1 Disable Unused Filesystems ### +######################################## +function disable_filesystems() { + { + start_spinner 'Disabling Unused Filesystems...' + echo "" + touch ${MODPRO} + #### 1.1.1.1 Ensure mounting of cramfs is disabled #### + echo "install cramfs /bin/true" > ${MODPRO} + lsmod | grep -qi cramfs + if [ $? != 1 ]; then + rmmod cramfs + fi + #### 1.1.1.2 Ensure mounting of freevxf filesystem 1s disabled #### + echo "install freevxfs /bin/true" >> ${MODPRO} + lsmod | grep -qi freevxfs + if [ $? != 1 ]; then + rmmod freevxfs + fi + #### 1.1.1.3 Ensure mounting of jiffs2 filesystem is disabled #### + echo "install jffs2 /bin/true" >> ${MODPRO} + lsmod | grep -qi jffs2 + if [ $? != 1 ]; then + rmmod jffs2 + fi + #### 1.1.1.4 Ensure mounting of hfs filesystem is disabled #### + echo "install hfs /bin/true" >> ${MODPRO} + lsmod | grep -qi hfs + if [ $? != 1 ]; then + rmmod hfs + fi + #### 1.1.1.5 Ensure mounting of hfsplus filesystem is disabled #### + echo "install hfsplus /bin/true" >> ${MODPRO} + lsmod | grep -qi hfsplus + if [ $? != 1 ]; then + rmmod hfsplus + fi + #### 1.1.1.6 Ensure mounting of squashfs filesystem is disabled #### + echo "install squashfs /bin/true" >> ${MODPRO} + lsmod | grep -qi squashfs + if [ $? != 1 ]; then + rmmod squashfs + fi + #### 1.1.1.7 Ensure mounting of udf filesystem is disabled #### + echo "install udf /bin/true" >> ${MODPRO} + lsmod | grep -qi udf + if [ $? != 1 ]; then + rmmod udf + fi + #### 1.1.1.8 Ensure mounting of FAT filesystem is disabled #### + echo "install fat /bin/true" >> ${MODPRO} + lsmod | grep -qi fat + if [ $? != 1 ]; then + rmmod fat + fi + ##################################### + #### Additonal Unsed Filesystems #### + ##################################### + echo "install cifs /bin/true" >> ${MODPRO} + lsmod | grep -qi cifs + if [ $? != 1 ]; then + rmmod cifs + fi + echo "install nfs /bin/true" >> ${MODPRO} + lsmod | grep -qi nfs + if [ $? != 1 ]; then + rmmod nfs + fi + echo "install nfsv3 /bin/true" >> ${MODPRO} + lsmod | grep -qi nfsv3 + if [ $? != 1 ]; then + rmmod nfsv3 + fi + echo "install nfsv4 /bin/true" >> ${MODPRO} + lsmod | grep -qi nfsv4 + if [ $? != 1 ]; then + rmmod nfsv4 + fi + echo "install gfs2 /bin/true" >> ${MODPRO} + lsmod | grep -qi gfs2 + if [ $? != 1 ]; then + rmmod gfs2 + fi + echo "install usb-storage /bin/true" >> ${MODPRO} + lsmod | grep -qi usb-storage + if [ $? != 1 ]; then + rmmod usb-storage + fi + echo "install bnep /bin/true" >> ${MODPRO} + lsmod | grep -qi bnep + if [ $? != 1 ]; then + rmmod bnep + fi + echo "install bluetooth /bin/true" >> ${MODPRO} + lsmod | grep -qi bluetooth + if [ $? != 1 ]; then + rmmod bluetooth + fi + echo "install btusb /bin/true" >> ${MODPRO} + lsmod | grep -qi btusb + if [ $? != 1 ]; then + rmmod btusb + fi + echo "install net-pf-31 /bin/true" >> ${MODPRO} + lsmod | grep -qi net-pf-31 + if [ $? != 1 ]; then + rmmod net-pf-31 + fi + echo "install appletalk /bin/true" >> ${MODPRO} + lsmod | grep -qi appletalk + if [ $? != 1 ]; then + rmmod appletalk + fi + { + echo "blacklist usb-storage" + echo "blacklist firewire-core" + echo "options ipv6 disable=1" + } >> ${MODPRO} + stop_spinner $? + } | tee -a $LOG +} + +###################################################### +#### 1.1.2 Ensure seprate partion exists for /tmp #### +###################################################### +function tmp_directory() { + { + start_spinner 'Ensuring a Seprate Partion Exists for /tmp...' + echo "" + #### Copy Conf Files for Backup #### + xargs -n 1 cp -v /etc/fstab <<< ""${BACKUP} /etc/fstab.bak"" + #### Check to see if /tmp is a mount #### + mount | grep /tmp + if ! 1; then + umount /tmp + fi + #### /tmp Mount Changes Ubuntu #### + if [ "${OS}" = ubuntu ]; then + xargs -n 1 cp -v /usr/share/systemd/tmp.mount <<< ""${BACKUP} /usr/share/systemd/tmp.mount.bak"" + grep nosuid /usr/share/systemd/tmp.mount + if ! 1; then + sed -i 's/Options=mode=1777,strictatime,nosuid,nodev/Options=mode=1777,strictatime,nosuid,nodev,noexec/g' /usr/share/systemd/tmp.mount + else + sed -i 's/Options=mode=1777,strictatime/Options=mode=1777,strictatime,nosuid,nodev,noexec/g' /usr/share/systemd/tmp.mount + fi + #### /tmp Mount Changes RedHat #### + elif [ "${OS}" = oracle ]; then + xargs -n 1 cp -v /usr/lib/systemd/system/tmp.mount <<< ""${BACKUP} /usr/lib/systemd/system/tmp.mount.bak"" + if [ "${OSVER}" = 7 ]; then + sed -i 's/Options=mode=1777,strictatime/Options=mode=1777,strictatime,nosuid,nodev,noexec/g' $TMPMNT/tmp.mount + fi + if [ "${OSVER}" = 8 ] || [ "${OSVER}" = 9 ]; then + sed -i 's/Options=mode=1777,strictatime,nosuid,nodev/Options=mode=1777,strictatime,nosuid,nodev,noexec/g' $TMPMNT/tmp.mount + fi + elif [[ ${OS} = centos || ${OS} = red || ${OS} = rocky || ${OS} = alma ]]; then + if [ "${OSVER}" = 7 ]; then + sed -i 's/Options=mode=1777,strictatime/Options=mode=1777,strictatime,nosuid,nodev,noexec/g' $TMPMNT/tmp.mount + fi + if [ "${OSVER}" = 8 ]; then + sed -i 's/Options=mode=1777,strictatime,nosuid,nodev/Options=mode=1777,strictatime,nosuid,nodev,noexec/g' $TMPMNT/tmp.mount + fi + if [ "${OSVER}" = 9 ]; then + sed -i 's/Options=mode=1777,strictatime,nosuid,nodev,size=50%,nr_inodes=1m/Options=mode=1777,strictatime,nosuid,nodev,noexec,size=50%,nr_inodes=1m/g' $TMPMNT/tmp.mount + fi + else + xargs -n 1 cp -v /etc/systemd/system/local-fs.target.wants/tmp.mount <<< ""${BACKUP} /etc/systemd/system/local-fs.target.wants/tmp.mount.bak"" + no_show << EOF > /etc/systemd/system/local-fs.target.wants/tmp.mount + [Mount] + What=tmpfs + Where=/tmp + Type=tmpfs + Options=mode=1777,strictatime,noexec,nodev,nosuid +EOF + fi + #### Setting /tmp to persist thru reboots #### + if ! grep -w /tmp /etc/fstab; then + echo "tmpfs /tmp tmpfs defaults,nodev,nosuid,noexec 0 0" >> /etc/fstab + fi + mount /tmp + #### 1.1.3, 1.1.4 & 1.1.5 Ensure noexec, nosuid and nodev option set on /tmp partition #### + #### mount -o remount,noexec,nosuid,nodev /tmp + #### Setting /var/tmp to persist thru reboots #### + if ! grep -w /var/tmp /etc/fstab; then + echo "/tmp /var/tmp none rw,noexec,nosuid,nodev,bind 0 0" >> /etc/fstab + fi + #### Binding mount /var/tmp directory to /tmp #### + mount -o rw,noexec,nosuid,nodev,bind /tmp/ /var/tmp/ + #### 1.1.8, 1.1.9 & 1.1.10 Ensure noexec, nosuid and nodev option set on /var/tmp partition #### + mount -o remount,noexec,nosuid,nodev /var/tmp + #### Setting /dev/shm to persist thru reboots #### + if [ "${SRVTYPE}" -ne 2 ]; then + if ! grep -w /dev/shm /etc/fstab; then + echo "tmpfs /dev/shm tmpfs defaults,nodev,nosuid,noexec,relatime 0 0" >> /etc/fstab + #### 1.1.15, 1.1.16 and 1.1.17 Ensure noexec, nosuid and nodev option set on /dev/shm partition #### + mount -o remount,noexec,nosuid,nodev,relatime /dev/shm + fi + fi + #### Ensure noexec and nodev option set on /dev partition #### + mount -o remount,noexec /dev + #### Setting /dev to persist thru reboots #### + if ! grep -w devtmpfs /etc/fstab; then + echo "devtmpfs /dev devtmpfs defaults,noexec 0 0" >> /etc/fstab + fi + stop_spinner $? + } | tee -a $LOG +} + +############################################################################# +#### 1.1.21 Ensure Sticky Bit is set on "All" World-Writable Directories #### +############################################################################# +function stickybit() { + { + start_spinner 'Setting Sticky Bit on "All" World-Writable Directories...' + echo "" + df --local -P | awk '{if (NR!=1) print $6}' | xargs -I '{}' find '{}' -xdev -type d -perm -0002 2>/dev/null | xargs chmod a+t + stop_spinner $? + } | tee -a $LOG +} + +############################################## +#### 1.2.2 Ensure GPG Keys are Configured #### +############################################## +function gpgkeys() { + { + start_spinner 'Checking GPG Keys are Configured...' + echo "" + if [ "${OS}" = ubuntu ]; then + apt-cache policy + ${PKGMGR} update 2>&1 1>/dev/null | sed -ne 's/.*NO_PUBKEY //p' | + while read -r key; do + echo 'Processing key:' "$key" + apt-key adv --keyserver keyserver.ubuntu.com --recv-keys "$key" + done + apt-key adv --refresh-keys --keyserver keyserver.ubuntu.com + apt-key list + else + rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY* + rpm -q gpg-pubkey --qf '%{name}-%{version}-%{release} --> %{summary}\n' + grep ^gpgcheck /etc/yum.repos.d/* >> ${LOG} 2>&1 + ### 1.2.3 Verify that gpgcheck is Globally Activated ### + grep -Eq "^(\s*)gpgcheck\s*=\s*\S+(\s*#.*)?\s*$" /etc/yum.conf && sed -ri "s/^(\s*)gpgcheck\s*=\s*\S+(\s*#.*)?\s*$/\1gpgcheck=1\2/" /etc/yum.conf || echo "gpgcheck=1" >> /etc/yum.conf + fi + stop_spinner $? + } | tee -a $LOG +} + +######################################## +#### 1.3.1 Ensure Aide is Installed #### +######################################## +function aide_install() { + { + start_spinner 'Installing and Configuring AIDE...' + echo "" + if [ "${OS}" = ubuntu ]; then + debconf-set-selections <<< ""postfix postfix/mailname string "${HOSTNAME}""" + debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Local Only'" + ${PAKMGR} install aide aide-common --assume-yes + aideinit + update-aide.conf + if [ ! -f ${CRON_UB} ]; then + touch ${CRON_UB} + crontab ${CRON_UB} + fi + if ! grep -qi "aide" ${CRON_UB}; then + echo "0 5 * * * /usr/bin/aide.wrapper --check" >> ${CRON_UB} + fi + else + ${PAKMGR} install aide + aide --init + mv -f /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz + if [ ! -f ${CRON_RH} ]; then + touch ${CRON_RH} + crontab ${CRON_RH} + fi + if ! grep -qi "aide" ${CRON_RH}; then + echo "0 5 * * * /usr/sbin/aide --check" >> ${CRON_RH} + fi + fi + stop_spinner $? + } | tee -a $LOG +} + +########################### +#### 1.3 Sudo Commands #### +########################### +function sudo_changes() { + { + start_spinner 'Configuring Sudo Settings...' + echo "" + if [ ! -f /etc/sudoers.d/cis ]; then + touch /etc/sudoers.d/cis + chmod 440 /etc/sudoers.d/cis + fi + #### 1.3.2 Ensure Sudo Commands use Pty #### + echo "Defaults use_pty" >> /etc/sudoers.d/cis + #### 1.3.3 Ensure Sudo Log File Exists #### + echo "Defaults logfile=\"/var/log/sudo.log\"" >> /etc/sudoers.d/cis + stop_spinner $? + } | tee -a $LOG +} + +################################## +#### 1.4 Secure Boot Settings #### +################################## +function boot_load() { + { + start_spinner 'Securing Boot Settings...' + echo "" + #### 1.4.1 Ensure permissions on bootloader config are configured #### + if [ "${OS}" = "ubuntu" ]; then + touch ${BOOTLDUB} + chmod 600 ${BOOTLDUB} + chown root.root ${BOOTLDUB} + else + touch ${BOOTLD} + chmod 600 ${BOOTLD} + chown root.root ${BOOTLD} + fi + #### Config /boot/efi permissions in fstab !!! This is for OCI !!! I have not seen this on any other cloud provider #### + mount | grep /boot/efi + if [ $? != 1 ]; then + umount /boot/efi + if [ "${OS}" = oracle ]; then + if [ "${OSVER}" = 7 ]; then + sed -i 's/defaults,uid=0,gid=0,umask=0077,shortname=winnt,_netdev,_netdev,x-initrd.mount/defaults,uid=0,gid=0,umask=0077,fmask=0177,shortname=winnt,_netdev,_netdev,x-initrd.mount/g' /etc/fstab + elif [ "${OSVER}" = 8 ]; then + sed -i 's/defaults,uid=0,gid=0,umask=077,shortname=winnt/defaults,uid=0,gid=0,umask=077,fmask=0177,shortname=winnt/g' /etc/fstab + fi + fi + if [ "${OS}" = centos ]; then + sed -i 's/vfat[[:blank:]]*defaults/vfat defaults,uid=0,gid=0,umask=0077,fmask=0177/g' /etc/fstab + fi + mount /boot/efi + fi + #### 1.4.2 Ensure bootloader password is set #### + if [ "${OS}" = centos ]; then + echo GRUB2_PASSWORD="${G2PASSWD}" > ${BOOTLD} + cp ${BOOTLD} ${BOOTLDCE} + elif [ "${OS}" = ubuntu ]; then + echo GRUB2_PASSWORD="${G2PASSWD}" > ${BOOTLDUB} + else + echo GRUB2_PASSWORD="${G2PASSWD}" > ${BOOTLD} + cp ${BOOTLD} ${BOOTLDRH} + fi + stop_spinner $? + } | tee -a $LOG +} + +################################################ +#### 1.5.1 Ensure core dumps are restricted #### +################################################ +function core_dumps() { + { + start_spinner 'Restricting Core Dumps...' + echo "" + xargs -n 1 cp -v /etc/security/limits.conf <<<"${BACKUP} /etc/security/limits.conf.bak" + echo '* hard core 0' >> /etc/security/limits.conf + stop_spinner $? + } | tee -a $LOG +} + +########################################################################### +#### 1.5.3 Ensure address space layout randomization (ASLR) is enabled #### +########################################################################### +function sysctl_conf() { + { + start_spinner 'Configuring Sysctl and Tuning Kernel Parameters...' + echo "" + xargs -n 1 cp -v /etc/sysctl.conf <<< "${BACKUP} /etc/sysctl.conf.bak" + no_show << "EOF" > /etc/sysctl.conf + ################################################################################################## + #### Hardened SysCtl Configuration File edited to match CIS level 1 requirements #### + #### for questions or changles please contact Phil Connor contact@mylinux.work #### + ################################################################################################## + + #### Controls the System Request debugging functionality of the kernel + kernel.sysrq = 0 + + #### Controls whether core dumps will append the PID to the core filename. + #### Useful for debugging multi-threaded applications. + kernel.core_uses_pid = 1 + + ################################## + #### GENERAL SECURITY OPTIONS #### + ################################## + + #### Automatically Reboot Server 30 Seconds after a Kernel Panic + vm.panic_on_oom = 1 + kernel.panic = 30 + kernel.panic_on_oops = 30 + + #### Enable ExecShield + #kernel.exec-shield = 1 + + kernel.dmesg_restrict = 1 + kernel.kptr_restrict = 1 + kernel.yama.ptrace_scope = 1 + + #### 1.5.3 Ensure address space layout randomization (ASLR) is enabled + kernel.randomize_va_space = 2 + + ################################# + #### COMMUNICATIONS SECURITY #### + ################################# + + #### 3.1.1 Ensure IP forwarding is disabled + net.ipv4.ip_forward = 0 + net.ipv4.conf.all.forwarding = 0 + net.ipv4.conf.default.forwarding = 0 + net.ipv6.conf.all.forwarding = 0 + net.ipv6.conf.default.forwarding = 0 + + #### 3.1.2 Ensure packet redirect sending is disabled + net.ipv4.conf.all.send_redirects = 0 + net.ipv4.conf.default.send_redirects = 0 + + #### 3.2.1 Ensure source routed packets are not accepted + net.ipv4.conf.all.accept_source_route = 0 + net.ipv4.conf.default.accept_source_route = 0 + + #### 3.2.2 Ensure ICMP redirects are not accepted + net.ipv4.conf.all.accept_redirects = 0 + net.ipv4.conf.default.accept_redirects = 0 + + #### 3.2.3 Ensure secure ICMP redirects are not accepted + net.ipv4.conf.all.secure_redirects = 0 + net.ipv4.conf.default.secure_redirects = 0 + + #### 3.2.4 Ensure suspicious packets are logged + net.ipv4.conf.all.log_martians = 1 + net.ipv4.conf.default.log_martians = 1 + + #### 3.2.5 Ensure broadcast ICMP requests are ignored + net.ipv4.icmp_echo_ignore_broadcasts = 1 + net.ipv4.tcp_timestamps = 0 + + #### 3.2.6 Ensure bogus ICMP responses are ignored + net.ipv4.icmp_ignore_bogus_error_responses = 1 + + #### 3.2.7 Ensure Reverse Path Filtering is enabled + net.ipv4.conf.all.rp_filter = 1 + net.ipv4.conf.default.rp_filter = 1 + + #### 3.2.8 Ensure TCP SYN Cookies is enabled + net.ipv4.tcp_syncookies = 1 + net.ipv4.tcp_syn_retries = 5 + net.ipv4.tcp_synack_retries = 2 + net.ipv4.tcp_max_syn_backlog = 4096 + + #### 3.3.1 Ensure IPv6 router advertisements are not accepted + net.ipv6.conf.all.accept_ra = 0 + net.ipv6.conf.default.accept_ra = 0 + + #### 3.3.1.1 Ensure IPv6 router advertisements are not accepted + net.ipv4.conf.all.accept_source_route=0 + net.ipv6.conf.all.accept_source_route=0 + net.ipv4.conf.default.accept_source_route=0 + net.ipv6.conf.default.accept_source_route=0 + + #### 3.3.2 Ensure IPv6 redirects are not accepted + net.ipv4.conf.all.accept_redirects = 0 + net.ipv6.conf.all.accept_redirects = 0 + net.ipv4.conf.default.accept_redirects = 0 + net.ipv6.conf.default.accept_redirects = 0 + + #### 3.3.3 Ensure IPv6 is disabled + net.ipv6.conf.all.disable_ipv6 = 1 + net.ipv6.conf.default.disable_ipv6 = 1 + net.ipv6.conf.lo.disable_ipv6 = 1 + + #### Reduce KeepAlive + net.ipv4.tcp_keepalive_time = 300 + net.ipv4.tcp_keepalive_probes = 5 + net.ipv4.tcp_keepalive_intvl = 15 + + fs.suid_dumpable = 0 + + ######################### + #### Oracle Settings #### + ######################### + + # oracle-ebs-server-R12-preinstall setting for fs.file-max is 6815744 + fs.file-max = 6815744 + # oracle-ebs-server-R12-preinstall setting for kernel.sem is '256 32000 100 142' + kernel.sem = 256 32000 100 142 + # oracle-ebs-server-R12-preinstall setting for kernel.shmmni is 4096 + kernel.shmmni=4096 + # oracle-ebs-server-R12-preinstall setting for kernel.shmall is 1073741824 on x86_64 + # oracle-ebs-server-R12-preinstall setting for kernel.shmall is 2097152 on i386 + kernel.shmall=1073741824 + # oracle-ebs-server-R12-preinstall setting for kernel.shmmax is 4398046511104 on x86_64 + # oracle-ebs-server-R12-preinstall setting for kernel.shmmax is 4294967295 on i386 + kernel.shmmax=4398046511104 + # oracle-ebs-server-R12-preinstall setting for kernel.panic_on_oops is 1 + kernel.panic_on_oops=1 + # oracle-ebs-server-R12-preinstall setting for kernel.msgmax is 8192 + kernel.msgmax = 8192 + # oracle-ebs-server-R12-preinstall setting for kernel.msgmni is 2878 + kernel.msgmni=2878 + # oracle-ebs-server-R12-preinstall setting for kernel.msgmnb is 65535 + kernel.msgmnb=65535 + # oracle-ebs-server-R12-preinstall setting for net.core.rmem_default is 262144 + net.core.rmem_default=262144 + # oracle-ebs-server-R12-preinstall setting for net.core.rmem_max is 4194304 + net.core.rmem_max=4194304 + # oracle-ebs-server-R12-preinstall setting for net.core.wmem_default is 262144 + net.core.wmem_default=262144 + # oracle-ebs-server-R12-preinstall setting for net.core.wmem_max is 1048576 + net.core.wmem_max=1048576 + # oracle-ebs-server-R12-preinstall setting for fs.aio-max-nr is 1048576 + fs.aio-max-nr = 1048576 + # oracle-ebs-server-R12-preinstall setting for net.ipv4.ip_local_port_range is 9000 65500 + net.ipv4.ip_local_port_range = 9000 65500 +EOF + sysctl -p + stop_spinner $? + } | tee -a $LOG +} + +########################################## +#### 1.5.4 Ensure prelink is disabled #### +########################################## +function pre_link() { + { + start_spinner 'Disabling and removing Prelink...' + echo "" + if [ -f /usr/sbin/prelink ]; then + prelink -ua + ${PAKMGR} remove prelink + fi + stop_spinner $? + } | tee -a $LOG +} + +######################################################## +#### 1.6.1.4 Ensure SETroubleshoot is not installed #### +######################################################## +function se_troubleshoot_mcs() { + { + start_spinner 'Removing SE Troubleshoot and MCS Translation Service...' + echo "" + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + if [ -f /usr/bin/setroubleshoot ]; then + ${PAKMGR} remove setroubleshoot + fi + fi + #### 1.6.1.5 Ensure the MCS Translation Service (mcstrans) is not installed #### + if [ "${OS}" = ubuntu ]; then + systemctl list-units --type=service --all | grep mcstrans + if ! 1; then + ${PAKMGR} remove policycoreutils + fi + else + systemctl list-units --type=service --all | grep mcstrans + if ! 1; then + ${PAKMGR} remove mcstrans + fi + fi + stop_spinner $? + } | tee -a $LOG +} + +###################################################### +#### 1.6.1.6 Ensure no unconfigured daemons exist #### +###################################################### +function unconf_daemons() { + { + start_spinner 'Ensuring no unconfigered daemons exist...' + echo "" + process=$(ps -eZ) + echo "${process}" | grep -E "initrc" | grep -Evw "tr|ps|grep|bash|awk" | tr ':' ' ' | awk '{ print $NF }' + stop_spinner $? + } | tee -a $LOG +} + +########################################### +#### 1.6.2 Ensure SELinux is installed #### +########################################### +function se_linux() { + { + start_spinner 'Ensuring SELinux is installed...' + echo "" + if [ "${OS}" = ubuntu ]; then + ${PAKMGR} install libselinux1 + else + if ! rpm -qa libselinux; then + ${PAKMGR} install libselinux + fi + fi + stop_spinner $? + } | tee -a $LOG +} + +################################################################## +#### 1.7.1.1 Ensure message of the day is configured properly #### +################################################################## +function banners() { + { + start_spinner 'Configuring all Message Banners...' + echo "" + if [ "${OS}" = ubuntu ]; then + chmod -x /etc/update-motd.d/* + touch /etc/motd + else + xargs -n 1 cp -v /etc/motd <<< "${BACKUP} /etc/motd.bak" + fi + echo " All activities performed on this system will be monitored." > /etc/motd + #### 1.7.1.2 Ensure local login warning banner is configured properly #### + xargs -n 1 cp -v /etc/issue <<< "${BACKUP} /etc/issue.bak" + echo " All activities performed on this system will be monitored." > /etc/issue + #### 1.7.1.3 Ensure remote login warning banner is configured properly #### + xargs -n 1 cp -v /etc/issue.net <<< "${BACKUP} /etc/issue.net.bak" + echo " All activities performed on this system will be monitored." > /etc/issue.net + #### 1.7.1.4 Ensure permissions on /etc/motd ore configured #### + chmod 644 /etc/motd + chown root.root /etc/motd + #### 1.7.1.5 Ensure permissions on /etc/issue are configured #### + chmod 644 /etc/issue + chown root.root /etc/issue + #### 1.7.1.6 Ensure permissions on /etc/issue.net are configured #### + chmod 644 /etc/issue.net + chown root.root /etc/issue.net + stop_spinner $? + } | tee -a $LOG +} + +##################################################################################### +#### 1.8 ensure updates, patches, and additional security software are installed #### +##################################################################################### +function update_security() { + { + start_spinner 'Checking and Installing Security Updates...' + echo "" + if [ "${OS}" = ubuntu ]; then + ${PAKMGR} autoremove + ${PAKMGR} update + "${PAKMGR} install -y --only-upgrade $(apt-get --just-print upgrade | awk 'tolower($4) ~ /.*security.*/ || tolower($5) ~ /.*security.*/ {print $2}' | sort | uniq)" + else + ${PAKMGR} clean all + ${PAKMGR} check-update --security + ${PAKMGR} update --security + fi + stop_spinner $? + } | tee -a $LOG +} + +############################ +#### 2.1 inetd Services #### +############################ +function inet_service() { + { + start_spinner 'Disabling Unused/Unsecure inetd Services...' + echo "" + #### 2.1.1 Ensure chargen services are not enabled #### + if [ "${OS}" = ubuntu ]; then + grep -R "^chargen" /etc/inetd.* + if ! 2; then + systemctl stop chargen + systemctl disable chargen + fi + else + systemctl is-enabled chargen-dgram + if ! 1; then + systemctl stop chargen-dgram + systemctl disable chargen-dgram + fi + systemctl is-enabled chargen-stream + if ! 1; then + systemctl stop chargen-stream + systemctl disable chargen-stream + fi + fi + #### 2.1.2 Ensure daytime services are not enabled #### + if [ "${OS}" = ubuntu ]; then + grep -R "^daytime" /etc/inetd.* + if ! 2; then + systemctl stop daytime + systemctl disable daytime + fi + else + systemctl is-enabled daytime-dgram + if ! 1; then + systemctl stop daytime-dgram + systemctl disable daytime-dgram + fi + systemctl is-enabled daytime-stream + if ! 1; then + systemctl stop daytime-stream + systemctl disable daytime-stream + fi + fi + #### 2.1.3 Ensure discard services are not enabled #### + if [ "${OS}" = ubuntu ]; then + grep -R "^discard" /etc/inetd.* + if ! 2; then + systemctl stop discard + systemctl disable discard + fi + else + systemctl is-enabled discard-dgram + if ! 1; then + systemctl stop discard-dgram + systemctl disable discard-dgram + fi + systemctl is-enabled discard-stream + if ! 1; then + systemctl stop discard-stream + systemctl disable discard-stream + fi + fi + #### 2.1.4 Ensure echo services are not Enabled #### + if [ "${OS}" = ubuntu ]; then + grep -R "^echo" /etc/inetd.* + if ! 2; then + systemctl stop echo + systemctl disable echo + fi + else + systemctl is-enabled echo-stream + if ! 1; then + systemctl stop echo-stream + systemctl disable echo-stream + fi + fi + #### 2.1.5 Ensure time services are not enabled #### + if [ "${OS}" = ubuntu ]; then + grep -R "^time" /etc/inetd.* + if ! 2; then + systemctl stop time + systemctl disable time + fi + else + systemctl is-enabled time-dgram + if ! 1; then + systemctl stop time-dgram + systemctl disable time-dgram + fi + systemctl is-enabled time-stream + if ! 1; then + systemctl stop time-stream + systemctl disable time-stream + fi + fi + #### 2.1.6 Ensure rsh server is not enabled Ubuntu #### + if [ "${OS}" = ubuntu ]; then + grep -R "^shell" /etc/inetd.* + if ! 2; then + systemctl stop shell + systemctl disable shell + fi + grep -R "^login" /etc/inetd.* + if ! 2; then + systemctl stop login + systemctl disable login + fi + grep -R "^exec" /etc/inetd.* + if ! 2; then + systemctl stop exec + systemctl disable exec + fi + fi + #### 2.1.6 Ensure tftp server is not enabled Others #### + systemctl is-enabled tftp + if ! 1; then + systemctl stop tftp + systemctl disable tftp + fi + #### 2.1.7 Ensure talk server is not enabled Ubuntu #### + if [ "${OS}" = ubuntu ]; then + grep -R "^talk" /etc/inetd.* + if ! 2; then + systemctl stop talk + systemctl disable talk + fi + grep -R "^ntalk" /etc/inetd.* + if ! 2; then + systemctl stop ntalk + systemctl disable ntalk + fi + fi + #### 2.1.9 Ensure tftp server is not enabled Ubuntu #### + if [ "${OS}" = ubuntu ]; then + grep -R "^tftp" /etc/inetd.* + if ! 2; then + systemctl stop tftp + systemctl disable tftp + fi + fi + #### 2.1.8 Ensure telnet server is not enabled Ubuntu #### + if [ "${OS}" = ubuntu ]; then + grep -R "^telnet" /etc/inetd.* + if ! 2; then + systemctl stop telnet + systemctl disable telnet + fi + fi + #### 2.1.10 Ensure xinetd is not enabled All #### + systemctl is-enabled xinetd + if ! 1; then + systemctl stop xinetd + systemctl disable xinetd + fi + stop_spinner $? + } | tee -a $LOG +} + +####################################################### +#### 2.2.1.1 Ensure time synchronization is in use #### +####################################################### + +#### 2.2.1.2 Ensure ntp is configured #### +function ntp_config() { + { + start_spinner 'Configuring NTP Service...' + echo "" + if [ "${OS}" = ubuntu ]; then + DEBIAN_FRONTEND=noninteractive ${PAKMGR} install ntp + else + ${PAKMGR} install ntp + fi + if [ "${OS}" = centos ]; then + var1=${OS} + elif [ "${OS}" = ubuntu ]; then + var1=${OS} + else + var1=rhel + fi + if [ "${OS}" = centos ]; then + sed -i 's/OPTIONS="-g"/OPTIONS="-u ntp:ntp"/g' /etc/sysconfig/ntpd + if ! grep -qi "server 127.127.1.0" ${NTP_FILE}; then + echo "server 127.127.1.0 #local clock" >> ${NTP_FILE} + echo "fudge 127.127.1.0 stratum 10" >> ${NTP_FILE} + fi + if ! grep -qi "disable monitor" ${NTP_FILE}; then + echo "disable monitor" >> ${NTP_FILE} + fi + systemctl enable --now ntpd + elif [ "${OS}" = ubuntu ]; then + if ! grep -qi "server 127.127.1.0" ${NTP_FILE}; then + echo "server 127.127.1.0 #local clock" >> ${NTP_FILE} + echo "fudge 127.127.1.0 stratum 10" >> ${NTP_FILE} + fi + if ! grep -qi "disable monitor" ${NTP_FILE}; then + echo "disable monitor" >> ${NTP_FILE} + fi + if ! grep -qi "RUNASUSER=ntp" /etc/init.d/ntp; then + echo "RUNASUSER=ntp" >> /etc/init.d/ntp + fi + else + xargs -n 1 cp -v ${NTP_FILE} <<< ""${BACKUP} ${NTP_FILE}.bak"" + sed -i 's/restrict default nomodify notrap nopeer noquery/restrict default nomodify notrap nopeer noquery/p' ${NTP_FILE} + sed -i '8 s/restrict default nomodify notrap nopeer noquery/restrict -4 default kod nomodify notrap nopeer noquery/g' ${NTP_FILE} + sed -i '9 s/restrict default nomodify notrap nopeer noquery/restrict -6 default kod nomodify notrap nopeer noquery/g' ${NTP_FILE} + sed -i 's/OPTIONS="-g"/OPTIONS="-u ntp:ntp"/g' /etc/sysconfig/ntpd + if ! grep -qi "server 127.127.1.0" "${NTP_FILE}"; then + echo "server 127.127.1.0 #local clock" >> ${NTP_FILE} + echo "fudge 127.127.1.0 stratum 10" >> ${NTP_FILE} + fi + if ! grep -qi "disable monitor" ${NTP_FILE}; then + echo "disable monitor" >> ${NTP_FILE} + fi + systemctl enable --now ntpd + systemctl restart ntpd + fi + sed -i "s/#server 0.$var1.pool.ntp.org iburst/server 0.$var1.pool.ntp.org iburst/g" ${NTP_FILE} + sed -i "s/#server 1.$var1.pool.ntp.org iburst/server 1.$var1.pool.ntp.org iburst/g" ${NTP_FILE} + sed -i "s/#server 2.$var1.pool.ntp.org iburst/server 2.$var1.pool.ntp.org iburst/g" ${NTP_FILE} + sed -i "s/#server 3.$var1.pool.ntp.org iburst/server 3.$var1.pool.ntp.org iburst/g" ${NTP_FILE} + systemctl enable --now ntp + systemctl enable --now systemd-timesyncd + stop_spinner $? + } | tee -a $LOG +} + +#### 2.2.1.3 Ensure chrony is configured #### +function chrony_cfg() { + { + start_spinner 'Configuring Chrony Service...' + echo "" + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + if [ "${OSVER}" = 8 ] || [ "${OSVER}" = 9 ]; then + ${PAKMGR} install chrony ntpstat + fi + elif [ "${OS}" = ubuntu ]; then + DEBIAN_FRONTEND=noninteractive ${PAKMGR} install chrony + else + ${PAKMGR} install chrony + fi + if [ "${OS}" = centos ]; then + var1=${OS} + else + var1=rhel + fi + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + if [ "${OSVER}" = 7 ]; then + if ! grep $var1.pool.ntp.org /etc/chrony.conf; then + echo '#################################################################' + echo '#### Using public servers from the pool.ntp.org project. ####' + echo '#### Added for CIS Level 1 Compatibility for questions ####' + echo '#### Contact Phil Connor contact@mylinux.work ####' + echo '#################################################################' + echo "server 0.$var1.pool.ntp.org iburst" + echo "server 1.$var1.pool.ntp.org iburst" + echo "server 2.$var1.pool.ntp.org iburst" + echo "server 3.$var1.pool.ntp.org iburst" + sed -i "s/#server 0.$var1.pool.ntp.org iburst/server 0.$var1.pool.ntp.org iburst/g" /etc/chrony.conf + sed -i "s/#server 1.$var1.pool.ntp.org iburst/server 1.$var1.pool.ntp.org iburst/g" /etc/chrony.conf + sed -i "s/#server 2.$var1.pool.ntp.org iburst/server 2.$var1.pool.ntp.org iburst/g" /etc/chrony.conf + sed -i "s/#server 3.$var1.pool.ntp.org iburst/server 3.$var1.pool.ntp.org iburst/g" /etc/chrony.conf + sed -i 's/server 169.254.169.254 iburst/#server 169.254.169.254 iburst/g' /etc/chrony.conf + sed -i 's/OPTIONS=""/OPTIONS="-u chrony"/g' /etc/sysconfig/chronyd + fi + fi + fi + if [ "${OSVER}" = 8 ] || [ "${OSVER}" = 9 ]; then + if ! grep $var1.pool.ntp.org /etc/chrony.conf; then + chronyd -q 'server 2.rhel.pool.ntp.org iburst' + sed -i 's/OPTIONS="-F 2"/OPTIONS="-u chrony"/g' /etc/sysconfig/chronyd + chronyc sourcestats -v + fi + systemctl enable --now chronyd + fi + if [ "${OS}" = ubuntu ]; then + if grep -q 'OPTIONS=.*' /etc/sysconfig/chronyd; then + sed -i -E -e 's/\s*-u\s+\w+\s*/ /' -e 's/^([\s]*OPTIONS=["]?[^"]*)("?)/\1 -u chrony\2/' /etc/sysconfig/chronyd + if [ ! -f /etc/sysconfig/chronyd ]; then + touch /etc/sysconfig/chronyd + echo "OPTIONS="-u chrony"" /etc/sysconfig/chronyd + fi + fi + chronyc sourcestats -v + fi + stop_spinner $? + } | tee -a $LOG +} + +####################################################### +#### 2.2.2 Ensure X Window System is not installed #### +####################################################### +function unsecure_services() { + { + start_spinner 'Removing X11 and Disabling Insecure Protocols...' + echo "" + if [ "${OS}" = ubuntu ]; then + ${PAKMGR} remove xorg* + ${PAKMGR} remove xserver-xorg* + else + ${PAKMGR} remove xorg-x11* + fi + a=( "$(systemctl list-units --type=service --all)" ) + #### 2.2.3 Ensure Avahi Server is not installed #### + if echo "${a[@]}" | grep avahi-daemon.service; then + systemctl stop avahi-daemon + systemctl disable avahi-daemon + fi + ### 2.2.4 Ensure CUPS is not enabled ### + if echo "${a[@]}" | grep cups.service; then + systemctl stop cups + systemctl disable cups + fi + #### 2.2.5 Ensure DHCP Server is not enabled #### + if [ "${OS}" = ubuntu ]; then + if echo "${a[@]}" | grep isc-dhcp-server.service; then + systemctl stop isc-dhcp-server + systemctl disable isc-dhcp-server + fi + else + if echo "${a[@]}" | grep dhcpd.service; then + systemctl stop dhcpd + systemctl disable dhcpd + fi + fi + #### 2.2.6 Ensure LDAP Server is not enabled #### + if echo "${a[@]}" | grep slapd.service; then + systemctl stop slapd + systemctl disable slapd + fi + #### 2.2.7 Ensure NFS and RPC are not enabled #### + if [ "${OS}" = ubuntu ]; then + if echo "${a[@]}" | grep nfs-kernel-server.service; then + systemctl stop nfs-kernel-server + systemctl disable nfs-kernel-server + fi + else + if echo "${a[@]}" | grep nfs-server.service; then + systemctl stop nfs-server + systemctl disable nfs-server + fi + if echo "${a[@]}" | grep nfs.service; then + systemctl stop nfs + systemctl disable nfs + fi + fi + if echo "${a[@]}" | grep rpcbind.service; then + systemctl stop rpcbind + systemctl disable rpcbind + fi + #### 2.2.8 Ensure DNS Server is not enabled #### + if echo "${a[@]}" | grep named.service; then + systemctl stop named + systemctl disable named + fi + if [ "${OS}" = ubuntu ]; then + if echo "${a[@]}" | grep bind9.service; then + systemctl stop bind9 + systemctl disable bind9 + fi + fi + #### 2.2.9 Ensure FTP Server is not enabled #### + if echo "${a[@]}" | grep vsftpd.service; then + systemctl stop vsftpd + systemctl disable vsftpd + fi + #### 2.2.10 Ensure HTTP Server is not enabled #### + if [ "${OS}" = ubuntu ]; then + if echo "${a[@]}" | grep apache2.service; then + systemctl stop apache2 + systemctl disable apache2 + fi + else + if echo "${a[@]}" | grep httpd.service; then + systemctl stop httpd + systemctl disable httpd + fi + fi + #### 2.2.11 Ensure IMAP and POP3 server are not enabled #### + if echo "${a[@]}" | grep dovecot.service; then + systemctl stop dovecot + systemctl disable dovecot + fi + #### 2.2.12 Ensure Samba is not enabled #### + if echo "${a[@]}" | grep smb.service; then + systemctl stop smb + systemctl disable smb + fi + #### 2.2.13 Ensure HTTP Proxy Server is not enabled #### + if echo "${a[@]}" | grep squid.service; then + systemctl stop squid + systemctl disable squid + fi + #### 2.2.14 Ensure SNMP Server is not enabled #### + if echo "${a[@]}" | grep snmpd.service; then + systemctl stop snmpd + systemctl disable snmpd + fi + stop_spinner $? + } | tee -a $LOG +} + +############################################################################# +#### 2.2.15 Ensure mail transfer agent is configured for local-only mode #### +############################################################################# +function mail_config() { + { + start_spinner 'Configuring Postfix MTA...' + echo "" + if [ "${OS}" = ubuntu ]; then + debconf-set-selections <<< ""postfix postfix/mailname string "${HOSTNAME}""" + debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Local Only'" + DEBIAN_FRONTEND=noninteractive ${PAKMGR} install postfix --assume-yes + sed -i 's/inet_interfaces = all/inet_interfaces = localhost/g' /etc/postfix/main.cf + else + ${PAKMGR} install postfix + sed -i 's/inet_interfaces = localhost/inet_interfaces = loopback-only/g' /etc/postfix/main.cf + fi + # shellcheck disable=SC2016 + sed -i 's/#smtpd_banner = $myhostname ESMTP $mail_name/smtpd_banner = $myhostname ESMTP/g' /etc/postfix/main.cf + # shellcheck disable=SC2016 + sed -i 's/smtpd_banner = $myhostname ESMTP ($mail_version)/#smtpd_banner = $myhostname ESMTP $mail_name ($mail_version)/g' /etc/postfix/main.cf + if ! grep -qi "mailbox_size_limit" /etc/postfix/main.cf; then + echo "mailbox_size_limit = 0" >> /etc/postfix/main.cf + fi + postconf -e message_size_limit=0 + postconf -e mailbox_size_limit = 0 + systemctl enable --now postfix + stop_spinner $? + } | tee -a $LOG +} + +################################################ +#### 2.2.x Disable Additional inet Services #### +################################################ +function addon_inet_services() { + { + start_spinner 'Disabling Additional Unsecure Services...' + echo "" + a=( "$(systemctl list-units --type=service --all)" ) + ### 2.2.16 Ensure NIS Server is not enabled ### + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + if echo "${a[@]}" | grep ypserv.service; then + systemctl stop ypserv + systemctl disable ypserv + fi + ### 2.2.16 Ensure rsync service is not enabled Ubuntu ### + elif [ "${OS}" = ubuntu ]; then + if echo "${a[@]}" | grep rsync.service; then + systemctl stop rsync + systemctl disable rsync + fi + fi + ### 2.1.17 Ensure rsh server is not enabled ### + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle ]]; then + if echo "${a[@]}" | grep rsh.socket.service; then + systemctl stop rsh.socket + systemctl disable rsh.socket + fi + if echo "${a[@]}" | grep rlogin.socket.service; then + systemctl stop rlogin.socket + systemctl disable rlogin.socket + fi + if echo "${a[@]}" | grep rexec.socket.service; then + systemctl stop rexec.socket + systemctl disable rexec.socket + fi + ### 2.2.17 Ensure NIS Server is not enabled Ubuntu ### + elif [ "${OS}" = ubuntu ]; then + if echo "${a[@]}" | grep nis.service; then + systemctl stop nis + systemctl disable nis + fi + fi + ### 2.2.18 Ensure talk server is not enabled ### + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle ]]; then + if echo "${a[@]}" | grep ntalk.service; then + systemctl stop ntalk + systemctl disable ntalk + fi + ### 2.2.19 Ensure telnet server is not enabled ### + if echo "${a[@]}" | grep telnet.socket.service; then + systemctl stop telnet.socket + systemctl disable telnet-socket + fi + ### 2.2.20 Ensure tftp server is not enabled ### + if echo "${a[@]}" | grep tftp.socket.service; then + systemctl stop tftp.socket + systemctl disable tftp-socket + fi + ### 2.2.21 Ensure rsync service is not enabled ### + if echo "${a[@]}" | grep rsyncd.service; then + systemctl stop rsyncd + systemctl disable rsyncd + fi + fi + stop_spinner $? + } | tee -a $LOG +} + +############################################################### +#### 2.3 Ensure Insecure Service Clients are not Installed #### +############################################################### +function service_clients() { + { + start_spinner 'Removing Insecure Service Clients...' + echo "" + a=( "$(systemctl list-units --type=service --all)" ) + #### 2.3.1 Ensure NIS Client is not installed #### + if [ "${OS}" = ubuntu ]; then + if echo "${a[@]}" | grep nis.service; then + ${PAKMGR} remove nis + fi + else + if echo "${a[@]}" | grep ypbind.service; then + ${PAKMGR} remove ypbind + fi + fi + #### 2.3.2 Ensure rsh client is not installed #### + if [ "${OS}" = ubuntu ]; then + if echo "${a[@]}" | grep rsh-client.service; then + ${PAKMGR} remove rsh-client rsh-redone-client + fi + else + if echo "${a[@]}" | grep rsh.service; then + ${PAKMGR} remove rsh + fi + fi + #### 2.3.3 Ensure talk client is not installed #### + if echo "${a[@]}" | grep talk.service; then + ${PAKMGR} remove talk + fi + #### 2.3.4 Ensure telnet client is not installed #### + if echo "${a[@]}" | grep telnet.service; then + ${PAKMGR} remove telnet + fi + #### 2.3.5 Ensure LDAP client is not installed #### + if [ "${OS}" = ubuntu ]; then + if echo "${a[@]}" | grep libnss-ldap.service; then + ${PAKMGR} remove libnss-ldap + fi + if echo "${a[@]}" | grep libpam-ldap.service; then + ${PAKMGR} remove libpam-ldap + fi + if echo "${a[@]}" | grep ldap-utils.service; then + ${PAKMGR} remove ldap-utils + fi + else + if echo "${a[@]}" | grep openldap-clients.service; then + ${PAKMGR} remove openldap-clients + fi + fi + stop_spinner $? + } | tee -a $LOG +} + +########################## +#### 3.4 TCP Wrappers #### +########################## +function tcp_wrappers() { + { + start_spinner 'Configuring TCP Wrappers...' + echo "" + #### 3.4.1 Ensure TCP Wrappers is installed #### + if [ "${OS}" = ubuntu ]; then + ${PAKMGR} install tcpd + else + ${PAKMGR} list | grep tcp_wrappers + if ! 1; then + ${PAKMGR} install tcp_wrappers + fi + fi + #### 3.4.2 Ensure /etc/hosts.allow is configured #### + echo ALL:"${VLANIP}" > /etc/hosts.allow + #### 3.4.3 Ensure /etc/hosts.deny is configured #### + echo "ALL:ALL" >> /etc/hosts.deny + #### 3.4.4 Ensure permissions on /etc/hosts.allow are configured #### + chown root.root /etc/hosts.allow + chmod 644 /etc/hosts.allow + #### 3.4.5 Ensure permissions on /etc/hosts.deny are configured #### + chown root.root /etc/hosts.deny + chmod 644 /etc/hosts.deny + stop_spinner $? + } +} + +######################################## +#### 3.5 Uncommon Network Protocols #### +######################################## +function uncommon_protocols() { + { + start_spinner 'Disabling Uncommon Network Protocols...' + echo "" + MODPRO="/etc/modprobe.d/cis.conf" + #### 3.5.1 Ensure DCCP is disabled #### + echo "install dccp /bin/true" >> ${MODPRO} + lsmod | grep -qi dccp + if ! 1; then + rmmod dccp + fi + #### 3.5.2 Ensure SCTP is disabled #### + echo "install sctp /bin/true" >> ${MODPRO} + lsmod | grep -qi sctp + if ! 1; then + rmmod sctp + fi + #### 3.5.3 ensure RDS is disabled #### + echo "install rds /bin/true" >> ${MODPRO} + lsmod | grep -qi rds + if ! 1; then + rmmod rds + fi + #### 3.5.4 Ensure TIPC is disabled #### + echo "install tipc /bin/true" >> ${MODPRO} + lsmod | grep -qi tipc + if ! 1; then + rmmod tipc + fi + stop_spinner $? + } | tee -a $LOG +} + +######################################## +#### 3.6 Firewall Configuration AWS #### +######################################## +function iptables_config() { + { + start_spinner 'Configuring IP Tables...' + echo "" + ### 3.6.1 Ensure iptables is installed ### + if [ "${OS}" = ubuntu ]; then + ufw --force disable + debconf-set-selections <<< "iptables-persistent iptables-persistent/autosave_v4 boolean true" + debconf-set-selections <<< "iptables-persistent iptables-persistent/autosave_v6 boolean true" + DEBIAN_FRONTEND=noninteractive ${PAKMGR} install iptables + DEBIAN_FRONTEND=noninteractive ${PAKMGR} install iptables-persistent --assume-yes + service netfilter-persistent start + service netfilter-persistent save + else + systemctl stop firewalld.service + systemctl mask firewalld.service + systemctl daemon-reload + ${PAKMGR} install iptables-utils iptables-services + fi + #### 3.6.2 Ensure default deny firewall policy #### + #### Configure IPv4 #### + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + systemctl enable --now iptables + cp $IPTBL $BACKUP + mv -f ${IPTBL} ${IPTBL}.bak + touch ${IPTBL} + fi + # Flush Iptables rules + iptables -F + # Forcing SYN packets check + iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP + # Forcing Fragments packets check + iptables -A INPUT -f -j DROP + # Dropping malformed XMAS packets + iptables -A INPUT -p tcp --tcp-flags ALL FIN,PSH,URG -j DROP + # Drop all NULL packets + iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP + # Limiting pings to 1 per second + iptables -N PACKET + iptables -A DEFAULT_RULES -p icmp -m limit --limit 3/sec --limit-burst 25 -j ACCEPT + # Setup Connection Tracking + iptables -N STATE_TRACK + iptables -A STATE_TRACK -m state --state RELATED,ESTABLISHED -j ACCEPT + iptables -A STATE_TRACK -m state --state INVALID -j DROP + # Discouraging Port Scanning + iptables -N PORTSCAN + iptables -A PORTSCAN -p tcp --tcp-flags ACK,FIN FIN -j DROP + iptables -A PORTSCAN -p tcp --tcp-flags ACK,PSH PSH -j DROP + iptables -A PORTSCAN -p tcp --tcp-flags ACK,URG URG -j DROP + iptables -A PORTSCAN -p tcp --tcp-flags FIN,RST FIN,RST -j DROP + iptables -A PORTSCAN -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP + iptables -A PORTSCAN -p tcp --tcp-flags SYN,RST SYN,RST -j DROP + iptables -A PORTSCAN -p tcp --tcp-flags ALL ALL -j DROP + iptables -A PORTSCAN -p tcp --tcp-flags ALL NONE -j DROP + iptables -A PORTSCAN -p tcp --tcp-flags ALL FIN,PSH,URG -j DROP + iptables -A PORTSCAN -p tcp --tcp-flags ALL SYN,FIN,PSH,URG -j DROP + iptables -A PORTSCAN -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP + iptables -N COMMON + iptables -A COMMON -j STATE_TRACK + iptables -A COMMON -j PORTSCAN + iptables -A COMMON -j PACKET + iptables -A INPUT -j COMMON + iptables -A OUTPUT -j COMMON + iptables -A FORWARD -j COMMON + iptables -A FORWARD -j PACKET + # Ensure loopback traffic is configured + iptables -A INPUT -i lo -j ACCEPT + iptables -A INPUT -s 127.0.0.0/8 -j DROP + iptables -A OUTPUT -o lo -j ACCEPT + # Ensure outbound and established connections are configured + iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + iptables -A INPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT + iptables -A INPUT -p udp -m state --state NEW,ESTABLISHED -j ACCEPT + iptables -A INPUT -p icmp -m state --state NEW,ESTABLISHED -j ACCEPT + iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT + iptables -A OUTPUT -p udp -m state --state NEW,ESTABLISHED -j ACCEPT + iptables -A OUTPUT -p icmp -m state --state NEW,ESTABLISHED -j ACCEPT + iptables -A OUTPUT -j LOG --log-prefix "iptables_output " + # Add Network Connection IP + iptables -A INPUT -s "${FIREIP}" -d "${FIREIP}" -m state --state NEW,ESTABLISHED -j ACCEPT + iptables -A OUTPUT -s "${FIREIP}" -d "${FIREIP}" -m state --state NEW,ESTABLISHED -j ACCEPT + # Open inbound ssh(22) connections and linit connects to 10 every 10 seconds + iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set + iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 10 --hitcount 10 -j DROP + iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT + # Default deny Firewall policy + iptables -P INPUT DROP + iptables -P OUTPUT DROP + iptables -P FORWARD DROP + for port in "${TCPPORTS[@]}" + do + echo "Opening TCP Port $port" + /sbin/iptables -A INPUT -p tcp -m tcp --dport "$port" -j ACCEPT + done + # Open UDP Ports + for port in "${UDPPORTS[@]}" + do + echo "Opening UDP Port $port" + /sbin/iptables -A INPUT -p udp -m udp --dport "$port" -j ACCEPT + done + # Save and Start IPTables + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + iptables-save > ${IPTBL} + systemctl restart iptables + elif [ "${OS}" = ubuntu ]; then + iptables-save > ${IPTBLUB} + sed -i '/:ufw-/d' ${IPTBLUB} + sed -i '/-j ufw-/d' ${IPTBLUB} + iptables-restore < ${IPTBLUB} + fi + # Configure IPv6 Firewall Ensure Default Deny Policy + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + cp $IPTBL $BACKUP + mv -f $IP6TBL $IP6TBL.bak + touch $IP6TBL + systemctl enable ip6tables + fi + # Flush Iptables rules + ip6tables -F + # Default deny Firewall policy + ip6tables -P INPUT DROP + ip6tables -P OUTPUT DROP + ip6tables -P FORWARD DROP + ip6tables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP + # Forcing Fragments packets check + ip6tables -A INPUT -f -j DROP + # Dropping malformed XMAS packets + ip6tables -A INPUT -p tcp --tcp-flags ALL FIN,PSH,URG -j DROP + # Drop all NULL packets + ip6tables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP + # Limiting pings to 1 per second + ip6tables -N PACKET + ip6tables -A DEFAULT_RULES -p icmp -m limit --limit 3/sec --limit-burst 25 -j ACCEPT + # Setup Connection Tracking + ip6tables -N STATE_TRACK + ip6tables -A STATE_TRACK -m state --state RELATED,ESTABLISHED -j ACCEPT + ip6tables -A STATE_TRACK -m state --state INVALID -j DROP + # Discouraging Port Scanning + ip6tables -N PORTSCAN + ip6tables -A PORTSCAN -p tcp --tcp-flags ACK,FIN FIN -j DROP + ip6tables -A PORTSCAN -p tcp --tcp-flags ACK,PSH PSH -j DROP + ip6tables -A PORTSCAN -p tcp --tcp-flags ACK,URG URG -j DROP + ip6tables -A PORTSCAN -p tcp --tcp-flags FIN,RST FIN,RST -j DROP + ip6tables -A PORTSCAN -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP + ip6tables -A PORTSCAN -p tcp --tcp-flags SYN,RST SYN,RST -j DROP + ip6tables -A PORTSCAN -p tcp --tcp-flags ALL ALL -j DROP + ip6tables -A PORTSCAN -p tcp --tcp-flags ALL NONE -j DROP + ip6tables -A PORTSCAN -p tcp --tcp-flags ALL FIN,PSH,URG -j DROP + ip6tables -A PORTSCAN -p tcp --tcp-flags ALL SYN,FIN,PSH,URG -j DROP + ip6tables -A PORTSCAN -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP + ip6tables -N COMMON + ip6tables -A COMMON -j STATE_TRACK + ip6tables -A COMMON -j PORTSCAN + ip6tables -A COMMON -j PACKET + ip6tables -A INPUT -j COMMON + ip6tables -A OUTPUT -j COMMON + ip6tables -A FORWARD -j COMMON + ip6tables -A FORWARD -j PACKET + # Ensure loopback traffic is configured + ip6tables -A INPUT -i lo -j ACCEPT + ip6tables -A INPUT -s 127.0.0.0/8 -j DROP + ip6tables -A OUTPUT -o lo -j ACCEPT + # Ensure outbound and established connections are configured + ip6tables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + ip6tables -A INPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT + ip6tables -A INPUT -p udp -m state --state NEW,ESTABLISHED -j ACCEPT + ip6tables -A INPUT -p icmp -m state --state NEW,ESTABLISHED -j ACCEPT + ip6tables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + ip6tables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT + ip6tables -A OUTPUT -p udp -m state --state NEW,ESTABLISHED -j ACCEPT + ip6tables -A OUTPUT -p icmp -m state --state NEW,ESTABLISHED -j ACCEPT + ip6tables -A OUTPUT -j LOG --log-prefix "iptables_output " + for port in "${TCP6PORTS[@]}" + do + echo "Opening TCP Port $port" + ip6tables -A INPUT -p tcp -m tcp --dport "$port" -j ACCEPT + done + # Open UDP Ports + for port in "${UDP6PORTS[@]}" + do + echo "Opening UDP Port $port" + ip6tables -A INPUT -p udp -m udp --dport "$port" -j ACCEPT + + done + # Save and Start IPTables + if [[ ${OS} = ubuntu ]]; then + ip6tables-save > ${IP6TBLUB} + sed -i '/:ufw6-/d' ${IP6TBLUB} + sed -i '/-j ufw6-/d' ${IPTBLUB} + ip6tables-restore < ${IP6TBLUB} + else + ip6tables-save > ${IP6TBL} + systemctl restart ip6tables + fi + stop_spinner $? + } | tee -a $LOG +} + +################################################## +#### 3.6a Addional Firewall Configuration AWS #### +################################################## +function iptables_aws() { + { + start_spinner 'Adding AWS Required Rules to IP Tables...' + echo "" + iptables -t nat -A PREROUTING -p tcp -d 169.254.170.2 --dport 80 -j DNAT --to-destination 127.0.0.1:51679 + iptables -t nat -A OUTPUT -d 169.254.170.2 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 51679 + iptables-save > /etc/sysconfig/iptables + systemctl restart iptables + stop_spinner $? + } | tee -a $LOG +} + +################################################## +#### 3.6b Addional Firewall Configuration OCI #### +################################################## +function oci_iptables() { + { + start_spinner 'Adding OCI Required Rules to IP Tables...' + echo "" + iptables -A OUTPUT -d 169.254.0.0/16 -m state --state NEW,ESTABLISHED -p tcp -m tcp -j REJECT --reject-with tcp-reset -m comment --comment "OCI Required - DO NOT REMOVE" + iptables -A OUTPUT -d 169.254.0.0/16 -m state --state NEW,ESTABLISHED -p udp -m udp -j REJECT -m comment --comment "OCI Required - DO NOT REMOVE" + iptables -A OUTPUT -d 169.254.0.2/32 -m state --state NEW,ESTABLISHED -p tcp -m tcp --dport 80 -j ACCEPT -m comment --comment "OCI Required - DO NOT REMOVE" + iptables -A OUTPUT -d 169.254.0.2/32 -m state --state NEW,ESTABLISHED -p tcp -m owner --uid-owner root -m tcp --dport 3260 -j ACCEPT -m comment --comment "OCI Required - DO NOT REMOVE" + iptables -A OUTPUT -d 169.254.0.3/32 -m state --state NEW,ESTABLISHED -p tcp -m owner --uid-owner root -m tcp --dport 80 -j ACCEPT -m comment --comment "OCI Required - DO NOT REMOVE" + iptables -A OUTPUT -d 169.254.0.4/32 -m state --state NEW,ESTABLISHED -p tcp -m tcp --dport 80 -j ACCEPT -m comment --comment "OCI Required - DO NOT REMOVE" + iptables -A OUTPUT -d 169.254.2.0/24 -m state --state NEW,ESTABLISHED -p tcp -m owner --uid-owner root -m tcp --dport 3260 -j ACCEPT -m comment --comment "OCI Required - DO NOT REMOVE" + iptables -A OUTPUT -d 169.254.4.0/24 -m state --state NEW,ESTABLISHED -p tcp -m owner --uid-owner root -m tcp --dport 3260 -j ACCEPT -m comment --comment "OCI Required - DO NOT REMOVE" + iptables -A OUTPUT -d 169.254.5.0/24 -m state --state NEW,ESTABLISHED -p tcp -m owner --uid-owner root -m tcp --dport 3260 -j ACCEPT -m comment --comment "OCI Required - DO NOT REMOVE" + iptables -A OUTPUT -d 169.254.169.254/32 -m state --state NEW,ESTABLISHED -p tcp -m tcp --dport 53 -j ACCEPT -m comment --comment "OCI Required - DO NOT REMOVE" + iptables -A OUTPUT -d 169.254.169.254/32 -m state --state NEW,ESTABLISHED -p udp -m udp --dport 53 -j ACCEPT -m comment --comment "OCI Required - DO NOT REMOVE" + iptables -A OUTPUT -d 169.254.169.254/32 -m state --state NEW,ESTABLISHED -p udp -m udp --dport 67 -j ACCEPT -m comment --comment "OCI Required - DO NOT REMOVE" + iptables -A OUTPUT -d 169.254.169.254/32 -m state --state NEW,ESTABLISHED -p udp -m udp --dport 69 -j ACCEPT -m comment --comment "OCI Required - DO NOT REMOVE" + iptables -A OUTPUT -d 169.254.169.254/32 -m state --state NEW,ESTABLISHED -p udp -m udp --dport 80 -j ACCEPT -m comment --comment "OCI Required - DO NOT REMOVE" + iptables -A OUTPUT -d 169.254.169.254/32 -m state --state NEW,ESTABLISHED -p udp -m udp --dport 123 -j ACCEPT -m comment --comment "OCI Required - DO NOT REMOVE" + # Save and Start IPTables + if [ "${OS}" = ubuntu ]; then + iptables-save > ${IPTBLUB} + sed -i '/:ufw-/d' ${IPTBLUB} + sed -i '/-j ufw-/d' ${IPTBLUB} + iptables-restore < ${IPTBLUB} + else + iptables-save > ${IPTBL} + systemctl restart iptables + fi + stop_spinner $? + } | tee -a $LOG +} + +######################################### +#### 4.1 Configure System Accounting #### +######################################### +function auditd_accounting() { + { + start_spinner 'Configuring Auditd Service...' + echo "" + #### 4.1.1.1 Ensure audit log storage size is configured #### + #### !!! Our current default configuration is 8MB !!! #### + #### 4.1.1.2 Ensure system is disabled when audit logs are full #### + if [ "${OS}" = ubuntu ]; then + debconf-set-selections <<< ""postfix postfix/mailname string "${HOSTNAME}""" + debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Local Only'" + DEBIAN_FRONTEND=noninteractive ${PAKMGR} install auditd --assume-yes + else + ${PAKMGR} install audit + fi + xargs -n 1 cp -v /etc/audit/auditd.conf <<< ""${BACKUP} /etc/audit/auditd.conf.bak"" + ### 4.1.1.3 Ensure audit logs are not automaticlly deleted ### + sed -i 's/^space_left_action.*$/space_left_action = email/' /etc/audit/auditd.conf + sed -i 's/^action_mail_acct.*$/action_mail_acct = root/' /etc/audit/auditd.conf + sed -i 's/^admin_space_left_action.*$/admin_space_left_action = halt/' /etc/audit/auditd.conf + # shellcheck disable=SC2086 + sed -i ""s/max_log_file_action = ROTATE/max_log_file_action = \"${MAXLOGS}\"/g"" /etc/audit/auditd.conf + ### 4.1.2 Ensure auditd service is enabled #### + service auditd reload + if ! systemctl is-enabled auditd; then + systemctl enable --now auditd + fi + ### 4.1.3 Ensure auditing for processes that start prior to auditd is enabled" + xargs -n 1 cp -v /etc/default/grub <<< ""${BACKUP} /etc/default/grub.bak"" + if ! grep "audit=1" /etc/default/grub; then + sed -i '/^GRUB_CMDLINE_LINUX=/ s/\(\"[^\"]*\)$/ audit=1 &/' /etc/default/grub + fi + if [ "${OS}" = ubuntu ]; then + grub-mkconfig -o ${BACKUP}/grub.cfg + else + grub2-mkconfig -o ${BACKUP}/grub.cfg + fi + if [[ ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + cp ${BACKUP}/grub.cfg ${GRUBCFGRH} + cp ${BACKUP}/grub.cfg ${GRUBCFG} + elif [ "${OS}" = ubuntu ]; then + cp ${BACKUP}/grub.cfg ${GRUBCFGUB} + elif [ "${OS}" = centos ]; then + cp ${BACKUP}/grub.cfg ${GRUBCFGCE} + cp ${BACKUP}/grub.cfg ${GRUBCFG} + fi + if ! dmesg | grep '[NX|DX]*Execute Disable'; then + echo 0 > /proc/sys/kernel/exec-shield + fi + ### 4.1.4 Ensure events that modify date and time information are collected ### + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + sed -i 's/RefuseManualStop=yes/RefuseManualStop=no/g' /lib/systemd/system/auditd.service + systemctl daemon-reload + fi + xargs -n 1 cp -v /etc/audit/rules.d/audit.rules <<< ""${BACKUP} /etc/audit/rules.d/audit.rules.bak"" + sed -i 's/RefuseManualStop=yes/RefuseManualStop=no/g' /lib/systemd/system/auditd.service + systemctl daemon-reload + { + echo '##################################################################################################' + echo '#### Audit Rules File edited to match CIS level 1 requirements ####' + echo '#### for questions or changes please contact Phil Connor contact@mylinux.work ####' + echo '##################################################################################################' + echo '' + echo '#### First rule - delete all rules ####' + echo '-D' + echo '' + echo '#### 4.1.4 Ensure events that modify date and time information are collected ####' + echo '-a always,exit -F arch=b64 -S adjtimex -S settimeofday -k time-change' + echo '-a always,exit -F arch=b32 -S adjtimex -S settimeofday -S stime -k time-change' + echo '-a always,exit -F arch=b64 -S clock_settime -k time-change' + echo '-a always,exit -F arch=b32 -S clock_settime -k time-change' + echo '-w /etc/localtime -p wa -k time-change' + echo '' + echo '#### 4.1.5 Ensure events that modify user/group information are collected ####' + echo '-w /etc/group -p wa -k identity' + echo '-w /etc/passwd -p wa -k identity' + echo '-w /etc/gshadow -p wa -k identity' + echo '-w /etc/shadow -p wa -k identity' + echo '-w /etc/security/opasswd -p wa -k identity' + echo '' + echo '#### 4.1.6 Ensure events that modify the system'\''s network environment are collected ####' + echo '-a always,exit -F arch=b32 -S sethostname -S setdomainname -k system-locale' + echo '-a always,exit -F arch=b64 -S sethostname -S setdomainname -k system-locale' + echo '-w /etc/issue -p wa -k system-locale' + echo '-w /etc/issue.net -p wa -k system-locale' + echo '-w /etc/hosts -p wa -k system-locale' + echo '-w /etc/network -p wa -k system-locale' + echo '-w /etc/networks -p wa -k system-locale' + echo '' + echo '#### 4.1.7 Ensure events that modify the system'\''s Mandatory Access Controls (MAC'\''s) are collected ####' + echo '-w /etc/selinux/ -p wa -k MAC-policy' + echo '-w /etc/apparmor/ -p wa -k MAC-policy' + echo '-w /etc/apparmor.d/ -p wa -k MAC-policy' + echo '' + echo '#### 4.1.8 Ensure login and logout events are collected ####' + echo '-w /var/log/faillog -p wa -k logins' + echo '-w /var/log/lastlog -p wa -k logins' + echo '-w /var/log/tallylog -p wa -k logins' + echo '' + echo '#### 4.1.9 Ensure session initiation information is collected ###' + echo '-w /var/run/utmp -p wa -k session' + echo '-w /var/run/wtmp -p wa -k session' + echo '-w /var/run/btmp -p wa -k session' + echo '' + echo '#### 4.1.10 Ensure discretionary access control permission modification events are collected ####' + echo '-a always,exit -F arch=b64 -S chmod -S fchmod -S fchmodat -F auid>=1000 -F auid!=4294967295 -k perm_mod' + echo '-a always,exit -F arch=b32 -S chmod -S fchmod -S fchmodat -F auid>=1000 -F auid!=4294967295 -k perm_mod' + echo '-a always,exit -F arch=b64 -S chown -S fchown -S fchownat -S lchown -F auid>=1000 -F auid!=4294967295 -k perm_mod' + echo '-a always,exit -F arch=b32 -S chown -S fchown -S fchownat -S lchown -F auid>=1000 -F auid!=4294967295 -k perm_mod' + echo '-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' + echo '-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' + echo '' + echo '#### 4.1.11 Ensure unsuccessful unauthorized file access attempts are collected ####' + echo '-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' + echo '-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' + echo '-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' + echo '-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' + echo '' + echo '#### 4.1.12 Ensure use of privileged commands is collected ####' + echo "$RULES" + echo '' + echo '#### 4.1.13 Ensure successful file system mounts are collected ####' + echo '-a always,exit -F arch=b64 -S mount -F auid>=1000 -F auid!=4294967295 -k mounts' + echo '-a always,exit -F arch=b32 -S mount -F auid>=1000 -F auid!=4294967295 -k mounts' + echo '' + echo '#### 4.1.14 Ensure file deletion events by users are collected ####' + echo '-a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295 -k delete' + echo '-a always,exit -F arch=b32 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295 -k delete' + echo '' + echo '#### 4.1.15 Ensure changes to system administration scope (sudoers) is collected ####' + echo '-w /etc/sudoers -p wa -k scope' + echo '-w /etc/sudoers.d -p wa -k scope' + echo '' + echo '#### 4.1.16 Ensure system administrator actions (sudolog) are collected ####' + echo '-w /var/log/sudo.log -p wa -k actions' + echo '' + echo '#### 4.1.17 Ensure kernel module loading and unloading is collected ####' + echo '-w /sbin/insmod -p x -k modules' + echo '-w /sbin/rmmod -p x -k modules' + echo '-w /sbin/modprobe -p x -k modules' + echo '-a always,exit -F arch=b64 -S init_module -S delete_module -k modules' + echo '' + echo '#### 4.1.18 Ensure the audit configuration is immutable ####' + echo '-e 2' + } > /etc/audit/rules.d/audit.rules + service auditd restart + stop_spinner $? + } | tee -a $LOG +} + +################################# +#### 4.2.1 Configure rsyslog #### +################################# +function rsyslog_service() { + { + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + if [ "${OSVER}" = 7 ]; then + os7_rsyslog + elif [[ ${OSVER} = 8 || ${OSVER} = 9 ]]; then + os8_rsyslog + fi + elif [ "${OS}" = ubuntu ]; then + ub_rsyslog + + fi + } +} + +function os7_rsyslog() { + { + start_spinner 'Configuring Rsyslog Service...' + echo "" + ### 4.2.1.1 Ensure rsyslog Service is enabled ### + systemctl enable --now rsyslog + ### 4.2.1.2 Ensure logging is configured ### + xargs -n 1 cp -v /etc/rsyslog.conf <<< ""${BACKUP} /etc/rsyslog.conf.bak"" + cat > /etc/rsyslog.conf << 'EOF' + ################################################################################################## + #### Hardened Rsyslog Configuration File edited to match CIS level 1 requirements #### + #### for questions or changles please contact Phil Connor contact@mylinux.work #### + ################################################################################################## + + ################# + #### MODULES #### + ################# + + # The imjournal module bellow is now used as a message source instead of imuxsock. + $ModLoad imuxsock # provides support for local system logging (e.g. via logger command) + $ModLoad imjournal # provides access to the systemd journal + #$ModLoad imklog # reads kernel messages (the same are read from journald) + #$ModLoad immark # provides --MARK-- message capability + + # Provides UDP syslog reception + #$ModLoad imudp + #$UDPServerRun 514 + + # Provides TCP syslog reception + #$ModLoad imtcp + #$InputTCPServerRun 514 + + # Enable non-kernel facility klog messages + # $KLogPermitNonKernelFacility on + + ########################### + #### GLOBAL DIRECTIVES #### + ########################### + + # Reset UMASK + $umask 0000 + + # Set file creation pewrmissions + $FileCreateMode 0640 + + # Set previously cleared UMASK + $umask 0177 + + # Where to place auxiliary files + $WorkDirectory /var/lib/rsyslog + + # Use default timestamp format + $ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat + + # File syncing capability is disabled by default. This feature is usually not required, + # not useful and an extreme performance hit + #$ActionFileEnableSync on + + # Include all config files in /etc/rsyslog.d/ + $IncludeConfig /etc/rsyslog.d/*.conf + + # Turn off message reception via local log socket; + # local messages are retrieved through imjournal now. + $OmitLocalLogging on + + # File to store the position in the journal + $IMJournalStateFile imjournal.state + + ############### + #### RULES #### + ############### + + # ### Log Anything of Level WARN or Higher. ### + *.warn;mail.none;news.none;authpriv.none;cron.none /var/log/messages + + # ### Secure Logging Anything of Level WARN or Higher ### + authpriv.* /var/log/secure + + # ### All Mail Logs ### + mail.* -/var/log/mail + + # ### Cron Log ### + cron.* /var/log/cron + + # ### Everybody Gets Emergency Messages ### + *.emerg :omusrmsg:* + *.=warning;*.=err -/var/log/warn + *.crit /var/log/warn + + # ### News Error Logs ### + news.crit -/var/log/news/news.crit + news.err -/var/log/news/news.err + news.notice -/var/log/news/news.notice + + # ### Local and Boot Messages ### + local0,local1.* -/var/log/localmessages + local2,local3.* -/var/log/localmessages + local4,local5.* -/var/log/localmessages + local6.* -/var/log/localmessages + local7.* /var/log/boot.log + + ############################### + #### Begin Forwarding Rule #### + ############################### + + # ### The Remote SysLog Server host is: name/ip:port, e.g. 192.168.0.1:514, port optional ### + #*.* @@syslog +EOF + echo " + *.* @@${SYSLOG} + + #################################### + #### End of the Forwarding Rule #### + #################################### + " >> /etc/rsyslog.conf + sed -i 's/^[\t]*//' /etc/rsyslog.conf + touch /var/log/warn /var/log/news.crit /var/log/news.err /var/log/news.notice /var/log/localmessages + chmod og-rwx /var/log/warn /var/log/news.crit /var/log/news.err /var/log/news.notice /var/log/localmessages + chown root:root /var/log/warn /var/log/news.crit /var/log/news.err /var/log/news.notice /var/log/localmessages + sed -i 's/*.* @@/#*.* @@/g' /etc/rsyslog.conf + pkill -hup rsyslog + stop_spinner $? + } +} + +function os8_rsyslog() { + { + start_spinner 'Configuring Rsyslog Service...' + echo "" + ### 4.2.1.1 Ensure rsyslog Service is enabled ### + systemctl enable rsyslog + ### 4.2.1.2 Ensure logging is configured ### + xargs -n 1 cp -v /etc/rsyslog.conf <<< ""${BACKUP} /etc/rsyslog.conf.bak"" + cat > /etc/rsyslog.conf << 'EOF' + ################################################################################################## + #### Hardened Rsyslog Configuration File edited to match CIS level 1 requirements #### + #### for questions or changles please contact Phil Connor contact@mylinux.work #### + ################################################################################################## + + ################# + #### MODULES #### + ################# + + module(load="imuxsock" # provides support for local system logging (e.g. via logger command) + SysSock.Use="off") # Turn off message reception via local log socket; + # local messages are retrieved through imjournal now. + module(load="imjournal" # provides access to the systemd journal + StateFile="imjournal.state") # File to store the position in the journal + #module(load="imklog") # reads kernel messages (the same are read from journald) + #module(load"immark") # provides --MARK-- message capability + + # Provides Rsyslog Forwarding + module(load="omfwd") + + # Provides UDP syslog reception + # for parameters see http://www.rsyslog.com/doc/imudp.html + #module(load="imudp") # needs to be done just once + #input(type="imudp" port="514") + + # Provides TCP syslog reception + # for parameters see http://www.rsyslog.com/doc/imtcp.html + #module(load="imtcp") # needs to be done just once + #input(type="imtcp" port="514") + + ########################### + #### GLOBAL DIRECTIVES #### + ########################### + + # Reset UMASK + $umask 0000 + + # Set file creation pewrmissions + $FileCreateMode 0640 + + # Set previously cleared UMASK + $umask 0177 + + # Where to place auxiliary files + global(workDirectory="/var/lib/rsyslog") + + # Use default timestamp format + module(load="builtin:omfile" Template="RSYSLOG_TraditionalFileFormat") + + # Include all config files in /etc/rsyslog.d/ + include(file="/etc/rsyslog.d/*.conf" mode="optional") + + ############### + #### RULES #### + ############### + + # ### Log Anything of Level WARN or Higher. ### + *.warn;mail.none;news.none;authpriv.none;cron.none /var/log/messages + + # ### Secure Logging Anything of Level WARN or Higher ### + authpriv.* /var/log/secure + + # ### All Mail Logs ### + mail.* -/var/log/mail + + # ### Cron Log ### + cron.* /var/log/cron + + # ### Everybody Gets Emergency Messages ### + *.emerg :omusrmsg:* + *.=warning;*.=err -/var/log/warn + *.crit /var/log/warn + + # ### News Error Logs ### + news.crit -/var/log/news/news.crit + news.err -/var/log/news/news.err + news.notice -/var/log/news/news.notice + + # ### Local and Boot Messages ### + local0,local1.* -/var/log/localmessages + local2,local3.* -/var/log/localmessages + local4,local5.* -/var/log/localmessages + local6.* -/var/log/localmessages + local7.* /var/log/boot.log + + + ############################### + #### Begin Forwarding Rule #### + ############################### + + #action(type="omfwd" + # An on-disk queue is created for this action. If the remote host is + # down, messages are spooled to disk and sent when it is up again. + #queue.filename="fwdRule1" # unique name prefix for spool files + #queue.maxdiskspace="1g" # 1gb space limit (use as much as possible) + #queue.saveonshutdown="on" # save messages to disk on shutdown + #queue.type="LinkedList" # run asynchronously + #action.resumeRetryCount="-1" # infinite retries if host is down + # Remote Logging (we use TCP for reliable delivery) + # remote_host is: name/ip, e.g. 192.168.0.1, port optional e.g. 10514 + # Target="remote_host" Port="XXX" Protocol="tcp") + +EOF + echo " + Target=\"${SYSLOG}" Port="514" Protocol="tcp\" + + #################################### + #### End of the Forwarding Rule #### + #################################### + " >> /etc/rsyslog.conf + sed -i 's/^[\t]*//' /etc/rsyslog.conf + touch /var/log/warn /var/log/news.crit /var/log/news.err /var/log/news.notice /var/log/localmessages + chmod og-rwx /var/log/warn /var/log/news.crit /var/log/news.err /var/log/news.notice /var/log/localmessages + chown root:root /var/log/warn /var/log/news.crit /var/log/news.err /var/log/news.notice /var/log/localmessages + sed -i 's/Target="" Port="514" Protocol="tcp"/#Target="" Port="514" Protocol="tcp"/g' /etc/rsyslog.conf + pkill -hup rsyslog + stop_spinner $? + } +} + +function ub_rsyslog() { + { + start_spinner 'Configuring Rsyslog Service...' + echo "" + service rsyslog stop + mknod -m 640 /dev/xconsole c 1 3 + chown syslog:adm /dev/xconsole + ### 4.2.1.1 Ensure rsyslog Service is enabled ### + systemctl enable rsyslog + ### 4.2.1.2 Ensure logging is configured ### + xargs -n 1 cp -v /etc/rsyslog.conf <<< ""${BACKUP} /etc/rsyslog.conf.bak"" + no_show << "EOF" > /etc/rsyslog.conf + ################################################################################################## + #### Hardened Rsyslog Configuration File edited to match CIS level 1 requirements #### + #### for questions or changles please contact Phil Connor contact@mylinux.work #### + ################################################################################################## + + ################# + #### MODULES #### + ################# + + module(load="imuxsock") # provides support for local system logging + #module(load="immark") # provides --MARK-- message capability + + # provides UDP syslog reception + #module(load="imudp") + #input(type="imudp" port="514") + + # provides TCP syslog reception + #module(load="imtcp") + #input(type="imtcp" port="514") + + # provides kernel logging support and enable non-kernel klog messages + module(load="imklog" permitnonkernelfacility="on") + + ########################### + #### GLOBAL DIRECTIVES #### + ########################### + + # Use default timestamp format + $ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat + + # Use traditional timestamp format. + # To enable high precision timestamps, comment out the following line. + $ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat + + # Filter duplicated messages + $RepeatedMsgReduction on + + # Reset UMASK + $Umask 0000 + + # Set the default permissions for all log files. + $FileOwner syslog + $FileGroup adm + $FileCreateMode 0640 + $DirCreateMode 0755 + $Umask 0177 + $PrivDropToUser syslog + $PrivDropToGroup syslog + + # Where to place spool and state files + $WorkDirectory /var/spool/rsyslog + + # Include all config files in /etc/rsyslog.d/ + $IncludeConfig /etc/rsyslog.d/*.conf + + ############################### + #### Begin Forwarding Rule #### + ############################### + $PreserveFQDN on + $ActionQueueFileName queue + $ActionQueueMaxDiskSpace 1g + $ActionQueueSaveOnShutdown on + $ActionQueueType LinkedList + $ActionResumeRetryCount -1 + # ### The Remote SysLog Server host is: name/ip:port, e.g. 192.168.0.1:514, port optional ### + #*.* @@syslog + +EOF + echo " + *.* @@${SYSLOG}:514 + + #################################### + #### End of the Forwarding Rule #### + #################################### + " >> /etc/rsyslog.conf + sed -i 's/^[\t]*//' /etc/rsyslog.conf + xargs -n 1 cp -v /etc/rsyslog.d/50-default.conf <<< ""${BACKUP} /etc/rsyslog.d/50-default.conf.bak"" + no_show << "EOF" > /etc/rsyslog.d/50-default.conf + ################################################################################################## + #### Hardened Rsyslog Configuration File edited to match CIS level 1 requirements #### + #### for questions or changles please contact Phil Connor contact@mylinux.work #### + ################################################################################################## + + + ############### + #### RULES #### + ############### + + # Default rules for rsyslog. + # + # For more information see rsyslog.conf(5) and /etc/rsyslog.conf + + # + # First some standard log files. Log by facility. + # + auth,authpriv.* /var/log/auth.log + *.*;auth,authpriv.none -/var/log/syslog + #cron.* /var/log/cron.log + #daemon.* -/var/log/daemon.log + kern.* -/var/log/kern.log + #lpr.* -/var/log/lpr.log + mail.* -/var/log/mail.log + #user.* -/var/log/user.log + + # + # Logging for the mail system. Split it up so that + # it is easy to write scripts to parse these files. + # + #mail.info -/var/log/mail.info + #mail.warn -/var/log/mail.warn + mail.err /var/log/mail.err + + # + # Logging for INN news system. + # + news.crit /var/log/news/news.crit + news.err /var/log/news/news.err + news.notice -/var/log/news/news.notice + + # + # Some "catch-all" log files. + # + #*.=debug;\ + # auth,authpriv.none;\ + # news.none;mail.none -/var/log/debug + #*.=info;*.=notice;*.=warn;\ + # auth,authpriv.none;\ + # cron,daemon.none;\ + # mail,news.none -/var/log/messages + + # + # Emergencies are sent to everybody logged in. + # + *.emerg :omusrmsg:* + + # + # I like to have messages displayed on the console, but only on a virtual + # console I usually leave idle. + # + #daemon,mail.*;\ + # news.=crit;news.=err;news.=notice;\ + # *.=debug;*.=info;\ + # *.=notice;*.=warn /dev/tty8 + + # The named pipe /dev/xconsole is for the `xconsole' utility. To use it, + # you must invoke `xconsole' with the `-file' option: + # + # $ xconsole -file /dev/xconsole [...] + # + # NOTE: adjust the list below, or you'll go crazy if you have a reasonably + # busy site.. + # + daemon.*;mail.*;\ + news.err;\ + *.=debug;*.=info;\ + *.=notice;*.=warn |/dev/xconsole +EOF + touch /var/log/warn /var/log/news.crit /var/log/news.err /var/log/news.notice /var/log/localmessages + chmod og-rwx /var/log/warn /var/log/news.crit /var/log/news.err /var/log/news.notice /var/log/localmessages + chown root:root /var/log/warn /var/log/news.crit /var/log/news.err /var/log/news.notice /var/log/localmessages + sed -i 's/*.* @@[[:blank:]]*:514/#*.* @@/g' /etc/rsyslog.conf + systemctl start rsyslog + pkill -hup rsyslog + stop_spinner $? + } | tee -a $LOG +} + +#################################################### +#### 4.2.1.2 Ensure Journald Service is enabled #### +#################################################### +function journald_config() { + { + start_spinner 'Configuring Journald Log Retension...' + echo "" + ### 4.2.2.1 Ensure journald is configured to send logs to rsyslog ### + sed -i 's/#ForwardToSyslog=yes/ForwardToSyslog=yes/g' /etc/systemd/journald.conf + ### 4.2.2.2 Ensure journald is configured to compress large log files ### + sed -i 's/#Compress=yes/Compress=yes/g' /etc/systemd/journald.conf + ### 4.2.2.3 Ensure journald is configured to write logfiles to persistent disk ### + sed -i 's/#Storage=auto/Storage=persistent/g' /etc/systemd/journald.conf + stop_spinner $? + } | tee -a $LOG +} + +################################## +#### 4.2.2 Configure journald #### +################################## +function logfile_permissions() { + { + start_spinner 'Configuring Permissions on all Logfiles...' + echo "" + ### 4.2.4 Ensure permissions on all logfiles are configured ### + find /var/log -type f -exec chmod g-wx,o-rwx {} + + ### 4.3 Ensure logrotate is configured ### + cp /etc/logrotate.conf $BACKUP + sed -i 's/ create 0664 root utmp/ create 0640 root utmp/g' /etc/logrotate.conf + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle ]]; then + if [ "${OSVER}" = 8 ]; then + sed -i 's/ create 0664 root utmp/ create 0640 root utmp/g' /etc/logrotate.d/btmp + sed -i 's/ create 0664 root utmp/ create 0640 root utmp/g' /etc/logrotate.d/wtmp + fi + fi + stop_spinner $? + } | tee -a $LOG +} + +############################################# +#### 5.1.1 Ensure cron daemon is enabled #### +############################################# +function crond_enabled() { + { + start_spinner 'Configuring Permissions on Cron Daemon...' + echo "" + ### 5.1.1.1 Ensure cron daemon is enabled ### + if [ "${OS}" = ubuntu ]; then + if ! systemctl is-enabled cron; then + systemctl enable cron + fi + else + if ! systemctl is-enabled crond; then + systemctl enable crond + fi + fi + ### Ensure permissions on /etc/crontab are configured ### + chown root.root /etc/crontab + chmod og-rwx /etc/crontab + ### 5.1.3 Ensure permissions on /etc/cron.hourly are configured ### + chown root.root /etc/cron.hourly + chmod og-rwx /etc/cron.hourly + ### 5.1.4 Ensure permissions on /etc/cron.daily are configured ### + chown root.root /etc/cron.daily + chmod og-rwx /etc/cron.daily + ### 5.1.5 Ensure permissions on /etc/cron.weekly are configured ### + chown root.root /etc/cron.weekly + chmod og-rwx /etc/cron.weekly + ### 5.1.6 Ensure permissions on ?etc/cron.monthly are configured ### + chown root.root /etc/cron.monthly + chmod og-rwx /etc/cron.monthly + ### 5.1.7 Ensure permissions on /etc/cron.d are configured ### + chown root.root /etc/cron.d + chmod og-rwx /etc/cron.d + ### 5.1.8 Ensure at/cron is restricted to authorized users ### + stat /etc/cron.deny + if [ $? != 1 ]; then + rm -rf /etc/cron.deny + fi + stat /etc/at.deny + if [ $? != 1 ]; then + rm -rf /etc/at.deny + fi + if ! stat /etc/cron.allow; then + touch /etc/cron.allow + chown root.root /etc/cron.allow + chmod og-rwx /etc/cron.allow + fi + if ! stat /etc/at.allow; then + touch /etc/at.allow + chown root.root /etc/at.allow + chmod og-rwx /etc/cron.allow + fi + stop_spinner $? + } | tee -a $LOG +} + +###################################### +#### 5.2 SSH Server Configuration #### +###################################### +function config_sshd() { + { + start_spinner 'Configuring SSh Server...' + echo "" + ### 5.2.1 Ensure permissions on /etc/ssh/sshd_config are configured ### + xargs -n 1 cp -v ${SSHD_FILE} <<< ""${BACKUP} ${SSHD_FILE}.bak"" + chown root.root ${SSHD_FILE} + chmod og-rwx ${SSHD_FILE} + ### 5.2.2. Ensure SSH Protocol is set to 2 ### + if ! grep -qi "Protocol 2" ${SSHD_FILE}; then + echo 'Protocol 2' >> ${SSHD_FILE} + else + sed -i 's/#Protocol 2/Protocol 2/g' ${SSHD_FILE} + fi + ### 5.2.3 Ensure SSH LogLevel is set to info ### + if ! grep -qi "LogLevel INFO" ${SSHD_FILE}; then + echo "LogLevel INFO" ${SSHD_FILE} + else + sed -i 's/#LogLevel INFO/LogLevel INFO/g' ${SSHD_FILE} + fi + ### 5.2.4 Ensure SSH X11 forwarding is disabled ### + if ! grep -qi "X11Forwarding yes" ${SSHD_FILE}; then + echo "X11Forwarding no" ${SSHD_FILE} + else + sed -i 's/X11Forwarding yes/X11Forwarding no/g' ${SSHD_FILE} + fi + ### 5.2.5 Ensure SSH MaxAuthTries is set to 4 or less ### + if ! grep -qi "MaxAuthTries 6" ${SSHD_FILE}; then + echo "MaxAuthTries 4" >> ${SSHD_FILE} + else + sed -i 's/#MaxAuthTries 6/MaxAuthTries 4/g' ${SSHD_FILE} + fi + ### 5.2.6 Ensure SSH IgnoreRhosts is enabled ### + if ! grep -qi "IgnoreRhosts yes" ${SSHD_FILE}; then + echo "IgnoreRhosts yes" >> ${SSHD_FILE} + else + sed -i 's/#IgnoreRhosts yes/IgnoreRhosts yes/g' ${SSHD_FILE} + fi + ### 5.2.7 Ensure SSH HostbasedAuthentication is disabled ### + if ! grep -qi "HostbasedAuthentication no" ${SSHD_FILE}; then + echo "HostbasedAuthentication no" >> ${SSHD_FILE} + else + sed -i 's/#HostbasedAuthentication no/HostbasedAuthentication no/g' ${SSHD_FILE} + fi + ### 5.2.8 Ensure SSH root login is disabled ### + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle ]]; then + if ! grep -qi "#PermitRootLogin" ${SSHD_FILE}; then + sed -i 's/PermitRootLogin yes/PermitRootLogin no/g' ${SSHD_FILE} + else + sed -i 's/#PermitRootLogin yes/PermitRootLogin no/g' ${SSHD_FILE} + fi + elif [ "${OS}" = ubuntu ]; then + if ! grep -qi "prohibit-password" ${SSHD_FILE}; then + sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin no/g' ${SSHD_FILE} + fi + fi + ### Ensure SSH PermitEmptyPasswords is disabled ### + sed -i 's/#PermitEmptyPasswords no/PermitEmptyPasswords no/g' ${SSHD_FILE} + ### 5.2.10 Ensure SSH PermitUserEnvironment is disables ### + if ! grep -qi "#PermitUserEnvironment" ${SSHD_FILE}; then + echo "PermitUserEnvironment no" >> ${SSHD_FILE} + else + sed -i 's/#PermitUserEnvironment no/PermitUserEnvironment no/g' ${SSHD_FILE} + fi + ### 5.2.11 Ensure ony approved MAC algorithms are used ### + if ! grep -qi "MACs" ${SSHD_FILE}; then + echo "MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512,hmac-sha2-256" >> ${SSHD_FILE} + else + sed -i 's/MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,umac-128@openssh.com/MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512,hmac-sha2-256/g' ${SSHD_FILE} + fi + if ! grep -qi "#ClientAliveInterval" ${SSHD_FILE}; then + echo "ClientAliveInterval 300" >> ${SSHD_FILE} + else + sed -i 's/#ClientAliveInterval 0/ClientAliveInterval 300/g' ${SSHD_FILE} + fi + if ! grep -qi "#ClientAliveCountMax" ${SSHD_FILE}; then + echo "ClientAliveCountMax ${MAXCOUNT}" >> ${SSHD_FILE} + else + sed -i "s/#ClientAliveCountMax 3/ClientAliveCountMax \"${MAXCOUNT}\"/g" ${SSHD_FILE} + fi + ### 5.2.13 Ensure SSH LoginGraceTime is set to one minute or less ### + if ! grep -qi "LoginGraceTime 120" ${SSHD_FILE}; then + sed -i 's/#LoginGraceTime 2m/LoginGraceTime 60/g' ${SSHD_FILE} + else + sed -i 's/LoginGraceTime 120/LoginGraceTime 60/g' ${SSHD_FILE} + fi + ### 5.2.14 Ensure SSH access is limited ### + echo 'AllowUsers *@*' >> ${SSHD_FILE} + ### 5.2.15 Ensure SSH warning banner is configured ### + if ! grep -qi "#Banner none" ${SSHD_FILE}; then + sed -i 's/#Banner \/etc\/issue.net/Banner \/etc\/issue.net/g' ${SSHD_FILE} + else + sed -i 's/#Banner none/Banner \/etc\/issue.net/g' ${SSHD_FILE} + fi + ### 5.2.16 Ensure only strong Key Exchange algorithms are used ### + if ! grep -qi "kexalgorithms" ${SSHD_FILE}; then + echo "KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group-exchange-sha256" >> ${SSHD_FILE} + fi + ### 5.2.21 Ensure SSH MaxStartups is configured ### + if ! grep -qi "maxstartups" ${SSHD_FILE}; then + echo "MaxStartups 10:30:60" >> ${SSHD_FILE} + else + sed -i 's/#MaxStartups 10:30:100/MaxStartups 10:30:60/g' ${SSHD_FILE} + fi + ### Configuring additional SSH settings ### + if ! grep -qi "#MaxSessions" ${SSHD_FILE}; then + echo "MaxSessions 2" >> ${SSHD_FILE} + else + sed -i 's/#MaxSessions 10/MaxSessions 2/g' ${SSHD_FILE} + fi + if ! grep -qi "#AllowAgentForwarding" ${SSHD_FILE}; then + echo "AllowAgentForwarding no" >> ${SSHD_FILE} + else + sed -i 's/#AllowAgentForwarding yes/AllowAgentForwarding no/g' ${SSHD_FILE} + fi + if ! grep -qi "#AllowTcpForwarding" ${SSHD_FILE}; then + echo "AllowTcpForwarding no" >> ${SSHD_FILE} + else + sed -i 's/#AllowTcpForwarding yes/AllowTcpForwarding no/g' ${SSHD_FILE} + fi + sed -i 's/#PrintMotd yes/PrintMotd no/g' ${SSHD_FILE} + if ! grep -qi "PrintLastLog" ${SSHD_FILE}; then + echo "PrintLastLog no" >> ${SSHD_FILE} + else + sed -i 's/#PrintLastLog yes/PrintLastLog no/g' ${SSHD_FILE} + fi + if ! grep -qi "TCPKeepAlive" ${SSHD_FILE}; then + sed -i 's/TCPKeepAlive yes/TCPKeepAlive no/g' ${SSHD_FILE} + else + sed -i 's/#TCPKeepAlive yes/TCPKeepAlive no/g' ${SSHD_FILE} + fi + if ! grep -qi "Compression" ${SSHD_FILE}; then + echo "Compression no" >> ${SSHD_FILE} + else + sed -i 's/#Compression delayed/Compression no/g' ${SSHD_FILE} + fi + if ! grep -qi "UseDNS" ${SSHD_FILE}; then + echo "UseDNS no" >> ${SSHD_FILE} + else + sed -i 's/#UseDNS yes/UseDNS no/g' ${SSHD_FILE} + sed -i 's/#UseDNS no/UseDNS no/g' ${SSHD_FILE} + fi + if ! grep -qi "#PasswordAuthentication" ${SSHD_FILE}; then + sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' ${SSHD_FILE} + else + sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/g' ${SSHD_FILE} + fi + echo 'Ciphers aes128-ctr,aes192-ctr,aes256-ctr' >> ${SSHD_FILE} + systemctl restart sshd + stop_spinner $? + } | tee -a $LOG +} + +########################### +#### 5.3 Configure PAM #### +########################### +function config_pam() { + { + start_spinner 'Configuring PAM Server...' + echo "" + ### 5.3.1 Ensure password creation requirements are configured ### + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle ]]; then + xargs -n 1 cp -v /etc/security/pwquality.conf <<< ""${BACKUP} /etc/security/pwquality.conf.bak"" + sed -i 's/minlen = 8/minlen = 14/g' /etc/security/pwquality.conf + ### 5.3.2 Ensure lockout for failed password attempts is configured ### + xargs -n 1 cp -v /etc/pam.d/password-auth <<< ""${BACKUP} /etc/pam.d/password-auth.bak"" + no_show << EOF > /etc/pam.d/password-auth + ######################################################################################## + #### This password-auth file edited to match CIS level 1 requirements for questions #### + #### or changes please contact Phil Connor contact@mylinux.work #### + #### Please don't edit it unless you know what your doing #### + ######################################################################################## + #%PAM-1.0 + # User changes will be destroyed the next time authconfig is run. + auth required pam_env.so + auth required pam_faildelay.so delay=2000000 + auth required pam_faillock.so preauth audit silent deny=5 unlock_time=900 + auth [success=1 default=bad] pam_unix.so + auth sufficient pam_fprintd.so + auth sufficient pam_unix.so nullok try_first_pass + auth [default=die] pam_faillock.so authfail audit deny=5 unlock_time=900 + auth sufficient pam_faillock.so authsucc audit deny=5 unlock_time=900 + auth requisite pam_succeed_if.so uid >= 1000 quiet_success + auth required pam_deny.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 + account required pam_faillock.so + + password requisite pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type= enforce_for_root + password required pam_pwhistory.so remember=5 use_authlok + password sufficient pam_unix.so remember=5 sha512 shadow try_first_pass use_authtok + password required pam_deny.so + + session optional pam_keyinit.so revoke + session required pam_limits.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 + ########################################## + #### Logging key strokes of all USERS #### + ########################################## + session required pam_tty_audit.so disable=* enable=* log_passwd +EOF + xargs -n 1 cp -v /etc/pam.d/system-auth <<< ""${BACKUP} /etc/pam.d/system-auth.bak"" + no_show << EOF > /etc/pam.d/system-auth + ###################################################################################### + #### This system-auth file edited to match CIS level 1 requirements for questions #### + #### or changes please contact Phil Connor contact@mylinux.work #### + #### Please don't edit it unless you know what your doing #### + ###################################################################################### + #%PAM-1.0 + # User changes will be destroyed the next time authconfig is run. + auth required pam_env.so + auth required pam_faildelay.so delay=2000000 + auth required pam_faillock.so preauth audit silent deny=5 unlock_time=900 + auth [success=1 default=bad] pam_unix.so + auth sufficient pam_fprintd.so + auth sufficient pam_unix.so nullok try_first_pass + auth [default=die] pam_faillock.so authfail audit deny=5 unlock_time=900 + auth sufficient pam_faillock.so authsucc audit deny=5 unlock_time=900 + auth requisite pam_succeed_if.so uid >= 1000 quiet_success + auth required pam_deny.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 + account required pam_faillock.so + + password requisite pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type= enforce_for_root + password required pam_pwhistory.so remember=5 use_authlok + password sufficient pam_unix.so remember=5 sha512 shadow try_first_pass use_authtok + password required pam_deny.so + + session optional pam_keyinit.so revoke + session required pam_limits.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 + ########################################## + #### Logging key strokes of all USERS #### + ########################################## + session required pam_tty_audit.so disable=* enable=* log_passwd +EOF + fi + if [ "${OS}" = ubuntu ]; then + debconf-set-selections <<< ""postfix postfix/mailname string "${HOSTNAME}""" + debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Local Only'" + ${PAKMGR} remove libpam-cracklib + ${PAKMGR} install libpam-pwquality --assume-yes + xargs -n 1 cp -v /etc/pam.d/common-password<<< ""${BACKUP} /etc/pam.d/common-password.bak"" + #sed -i 's/password[[:blank:]]*requisite[[:blank:]]*pam_pwquality.so retry=3/password requisite pam_pwquality.so retry=3 difok=3 reject_username enforce_for_root/g' /etc/pam.d/common-password + sed -i 's/# minlen = 8/minlen = 14/g' /etc/security/pwquality.conf + sed -i 's/# dcredit = 0/dcredit=-1/g' /etc/security/pwquality.conf + sed -i 's/# ucredit = 0/ucredit=-1/g' /etc/security/pwquality.conf + sed -i 's/# ocredit = 0/ocredit=-1/g' /etc/security/pwquality.conf + sed -i 's/# lcredit = 0/lcredit=-1/g' /etc/security/pwquality.conf + no_show << EOF >> /etc/pam.d/common-password + ################################################ + #### 5.3.3 Ensure password reuse is limited #### + ################################################ + password required pam_unix.so remember=5 + +EOF + no_show << EOF >> /etc/pam.d/common-auth + ######################################################################### + #### 5.3.2 Ensure lockout for failed password attempts is configured #### + ######################################################################### + auth required pam_tally2.so onerr=fail audit silent deny=5 unlock_time=900 + + ########################################## + #### Logging key strokes of all USERS #### + ########################################## + session required pam_tty_audit.so disable=* enable=* log_passwd +EOF + fi + stop_spinner $? + } | tee -a $LOG +} + +############################################ +#### 5.4 User Accounts and Environments #### +############################################ +function accounts() { + { + start_spinner 'Configuring User Accts and Environments...' + echo "" + LODEFS="/etc/login.defs" + #### 5.4.1.1 Ensure password expiration is 90 days or less #### + #### 5.4.1.2 Ensure minimum days between password changes is 7 days or more #### + #### 5.4.1.3 Ensure password expiration warning days is 7 or more #### + if [ -e ${LODEFS} ]; then + cp ${LODEFS} ${LODEFS}.tmp + awk '($1 ~ /^PASS_MAX_DAYS/) { $2="90" } + ($1 ~ /^PASS_MIN_DAYS/) { $2="7" } + ($1 ~ /^PASS_WARN_AGE/) { $2="10" } + ($1 ~ /^PASS_MIN_LEN/) { $2="14" } + { print }' ${LODEFS}.tmp > ${LODEFS} + rm ${LODEFS}.tmp + fi + cut -d: -f1 /etc/passwd | while read -r NAME + do + uid=$(id -u "${NAME}") + if [ "${uid}" -ge 1000 ] && [ "${uid}" != 65534 ]; then + chage -M 90 -m 7 -W 10 -I 30 "${NAME}" + fi + done + if [ "${OS}" = ubuntu ]; then + no_show << EOF >> ${LODEFS} + ################################################################## + #### Make it More Difficult to Bruteforce the Hashed Password #### + ################################################################## + SHA_CRYPT_MIN_ROUNDS 5000 + SHA_CRYPT_MAX_ROUNDS 10000 +EOF + sed -i 's/pam_faildelay.so delay=3000000/pam_faildelay.so delay=300000000/g' /etc/pam.d/login + else + no_show << EOF >> ${LODEFS} + ############################################################################ + #### Establish a forced five-second minimum delay between failed logins #### + ############################################################################ + FAIL_DELAY 5 + + ################################################################## + #### Make it More Difficult to Bruteforce the Hashed Password #### + ################################################################## + SHA_CRYPT_MIN_ROUNDS 5000 + SHA_CRYPT_MAX_ROUNDS 10000 +EOF + fi + chown root:root ${LODEFS} + chmod 0640 ${LODEFS} + #### 5.4.1.4 Ensure inactive password lock is 30 days or less #### + useradd -D -f 30 + stop_spinner $? + } | tee -a $LOG +} + +###################################################### +#### 5.4 User Accounts and Environments Continued #### +###################################################### +function config_users_permissions() { + { + start_spinner 'Configuring User Permissions...' + echo "" + #### 5.4.2 Ensure system accounts are non-login #### + awk -F: '($3 < 1000) {print $1 }' /etc/passwd | while read -r user + do + if [ "$user" != "root" ]; then + usermod -L "$user" + if [ "$user" != "sync" ] && [ "$user" != "shutdown" ] && [ "$user" != "halt" ]; then + usermod -s /usr/sbin/nologin "$user" + fi + fi + done + #### 5.4.3 Ensure default group for the root account is GID 0 #### + usermod -g 0 root + groupadd dev + groupadd dba + touch /etc/sudoers.d/cis_conf + chmod 440 /etc/sudoers.d/cis_conf + if [ "${OS}" = ubuntu ]; then + sed -i 's/sudo:x:27:/sudo:x:27:root,ubuntu/g' /etc/group + sed -i 's/sudo:*::/sudo:*::root,ubuntu/g' /etc/gshadow + sed -i 's/%sudo[[:blank:]]*ALL=(ALL:ALL)[[:blank:]]*ALL/%sudo ALL=\(ALL:ALL\) NOPASSWD:ALL/g' /etc/sudoers + else + grep -qi "wheel" /etc/group + if [ $? != 1 ]; then + sed -i 's/%wheel[[:blank:]]*ALL=(ALL)[[:blank:]]*ALL/# %wheel ALL=\(ALL\) ALL/g' /etc/sudoers + sed -i 's/^#\s*\(%wheel\s*ALL=(ALL)\s*NOPASSWD:\s*ALL\)/\1/' /etc/sudoers + sed -i 's/wheel:x:10:opc/wheel:x:10:root,opc/g' /etc/group + sed -i 's/wheel:::opc/wheel:::root,opc/g' /etc/gshadow + fi + fi + { + echo "####################" + echo "#### Networking ####" + echo "####################" + } >> /etc/sudoers.d/local_conf + if [ "${OS}" = ubuntu ]; then + { + echo "Cmnd_Alias NETWORKING = /sbin/route, /sbin/ifconfig, /bin/ping, /sbin/dhclient, /sbin/iptables, /sbin/mii-tool" + echo "" + } >> /etc/sudoers.d/local_conf + else + { + echo "Cmnd_Alias NETWORKING = /sbin/route, /sbin/ifconfig, /bin/ping, /sbin/dhclient, /usr/bin/net, /sbin/iptables, /usr/bin/rfcomm, /usr/bin/wvdial, /sbin/iwconfig, /sbin/mii-tool" + echo "" + } >> /etc/sudoers.d/local_conf + fi + { + echo "#################################################" + echo "#### Installation and management of software ####" + echo "#################################################" + } >> /etc/sudoers.d/cis_conf + if [ "${OS}" = ubuntu ]; then + { + echo "Cmnd_Alias SOFTWARE = usr/bin/apt, /usr/bin/dpkg, /usr/bin/apt-get" + echo "" + } >> /etc/sudoers.d/local_conf + else + { + echo "Cmnd_Alias SOFTWARE = /bin/rpm, /usr/bin/up2date, /usr/bin/yum" + echo "" + } >> /etc/sudoers.d/local_conf + fi + { + echo "##################" + echo "#### Services ####" + echo "##################" + echo "Cmnd_Alias SERVICES = /sbin/service, /sbin/chkconfig, /usr/bin/systemctl start, /usr/bin/systemctl stop, /usr/bin/systemctl reload, /usr/bin/systemctl restart, /usr/bin/systemctl status, /usr/bin/systemctl enable, /usr/bin/systemctl disable" + echo "" + echo "######################################" + echo "#### Updating the locate database ####" + echo "######################################" + echo "Cmnd_Alias LOCATE = /usr/bin/updatedb" + echo "" + echo "#################" + echo "#### Storage ####" + echo "#################" + echo "Cmnd_Alias STORAGE = /sbin/fdisk, /sbin/sfdisk, /sbin/parted, /sbin/partprobe, /bin/mount, /bin/umount" + echo "" + echo "################################" + echo "#### Delegating permissions ####" + echo "################################" + echo "Cmnd_Alias DELEGATING = /usr/sbin/visudo, /bin/chown, /bin/chmod, /bin/chgrp" + echo "" + echo "###################" + echo "#### Processes ####" + echo "###################" + echo "Cmnd_Alias PROCESSES = /bin/nice, /bin/kill, /usr/bin/kill, /usr/bin/killall" + echo "" + echo "#################" + echo "#### Drivers ####" + echo "#################" + echo "Cmnd_Alias DRIVERS = /sbin/modprobe" + echo "" + echo "###########################################################################" + echo "#### Reboot and ShutDown removed from DBA's and Developers 3/4/20 - PC ####" + echo "###########################################################################" + echo "Cmnd_Alias SHUTDOWN = /sbin/shutdown, /sbin/reboot, /sbin/halt, /sbin/poweroff" + echo "" + echo "###########################" + echo "#### Our System Groups ####" + echo "###########################" + echo "%dba ALL= NOPASSWD: /usr/bin/su - applmgr, /usr/bin/su - oracle, !NETWORKING, !SOFTWARE, !SERVICES, !STORAGE, !DELEGATING, !PROCESSES, !LOCATE, !DRIVERS, !SHUTDOWN" + echo "%dev ALL= NOPASSWD: /usr/bin/su - applmgr, !NETWORKING, !SOFTWARE, !SERVICES, !STORAGE, !DELEGATING, !PROCESSES, !LOCATE, !DRIVERS, !SHUTDOWN" + } >> /etc/sudoers.d/local_conf + #### 5.4.4 Ensure default user umask is 027 or more restrictive #### + if [ "${OS}" = "ubuntu" ]; then + grep -Eq "^(\s*)umask\s+\S+(\s*#.*)?\s*$" /etc/bash.bashrc && sed -ri "s/^(\s*)umask\s+\S+(\s*#.*)?\s*$/\1umask 027\2/" /etc/bash.bashrc || echo "umask 027" >> /etc/bash.bashrc + else + grep -Eq "^(\s*)umask\s+\S+(\s*#.*)?\s*$" /etc/bashrc && sed -ri "s/^(\s*)umask\s+\S+(\s*#.*)?\s*$/\1umask 027\2/" /etc/bashrc || echo "umask 027" >> /etc/bashrc + fi + grep -Eq "^(\s*)umask\s+\S+(\s*#.*)?\s*$" /etc/profile && sed -ri "s/^(\s*)umask\s+\S+(\s*#.*)?\s*$/\1umask 027\2/" /etc/profile || echo "umask 027" >> /etc/profile + #### 5.4.5 Ensure default user shell timeout is 900 seconds or less #### + if grep TMOUT=900 /etc/bashrc; then + sed -i 's/TMOUT=900/#TMOUT=900/g' /etc/bashrc + fi + + if grep TMOUT=900 /etc/profile; then + sed -i 's/TMOUT=900/#TMOUT=900/g' /etc/profile + fi + cat >> /etc/profile << 'EOF' + if [ "$(id -nu)" == "root" ] || [ "$(id -nu)" == "opc" ]; then + TMOUT=3600 + readonly TMOUT + export TMOUT + else + TMOUT=900 + readonly TMOUT + export TMOUT + fi +EOF + cat >> /etc/bashrc << 'EOF' + if [ "$(id -nu)" == "root" ] || [ "$(id -nu)" == "opc" ]; then + if ! echo $TMOUT | grep -q 3600; then + TMOUT=3600 + readonly TMOUT + export TMOUT + fi + else + if ! echo $TMOUT | grep -q 900; then + TMOUT=900 + readonly TMOUT + export TMOUT + fi + fi +EOF + #### 5.4.5A Ensure default user umask is configured - system wide #### + sed -ri 's/^([^#]+\s+)?(umask\s+)(\S+\s*)(\s+.*)?$/\1\2 027\4/' /etc/login.defs + sed -ri 's/^([^#]+\s+)?(umask\s+)(\S+\s*)(\s+.*)?$/\1\2 027\4/' /etc/profile + sed -ri 's/^([^#]+\s+)?(umask\s+)(\S+\s*)(\s+.*)?$/\1\2 027\4/' /etc/bashrc + touch /etc/profile.d/cis_profile.sh + chmod 644 /etc/profile.d/cis_profile.sh + echo " + ################################ + ### Added for CIS Compliance ### + ################################ + umask 077 + " > /etc/profile.d/cis_profile.sh + #### 5.5 Ensure root login is restricted to system console #### + xargs -n 1 cp -v /etc/securetty <<< ""${BACKUP} /etc/securetty.bak"" + echo "console" > /etc/securetty + ### 5.6 Ensure access to the su command is restricted ### + PAMSU="/etc/pam.d/su" + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle ]]; then + xargs -n 1 cp -v ${PAMSU} <<< ""${BACKUP} ${PAMSU}.bak"" + if [ -e ${PAMSU} ]; then + cp ${PAMSU} ${PAMSU}.tmp + awk '( $1=="#auth" && $2=="required" && $3~"pam_wheel.so" ) { print "auth\t\trequired\t",$3,"\tuse_uid"; next }; + { print }' ${PAMSU}.tmp > ${PAMSU} + chown root:root ${PAMSU} + chmod 0644 ${PAMSU} + rm ${PAMSU}.tmp + fi + elif [ "${OS}" = ubuntu ]; then + sed -i 's/# auth[[:blank:]]*required[[:blank:]]*pam_wheel.so/auth required pam_wheel.so use_uid/g' /etc/pam.d/su + sed -i 's/auth required pam_wheel.so use_uid deny group=nosu/#auth required pam_wheel.so deny group=nosu/g' /etc/pam.d/su + fi + stop_spinner $? + } | tee -a $LOG +} + +################################ +#### 6.1 System Permissions #### +################################ +function audit_file_permissions() { + { + start_spinner 'Auditing File Permissions...' + echo "" + ### 6.1.1 Audit system file permissions ### + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle ]]; then + rpm -Va --nomtime --nosize --nomd5 --nolinkto + elif [ "${OS}" = ubuntu ]; then + ${PAKMGR} install debsums + debsums -s + fi + ### 6.1.2 Ensure permissions on /etc/passwd are configured ### + chmod 644 /etc/passwd + chown root.root /etc/passwd + ### 6.1.3 Ensure permissions on /etc/shadow are configured ### + chmod 000 /etc/shadow + chown root.root /etc/shadow + ### 6.1.4 Ensure permissions on /etc/group are configured ### + chmod 644 /etc/group + chown root.root /etc/group + ### 6.1.5 Ensure permissions on /etc/gshadow are configured ### + chmod 000 /etc/gshadow + chown root:root /etc/gshadow + ### 6.1.6 Ensure permissions on /etc/passwd- are configured ### + chmod 644 /etc/passwd- + chown root.root /etc/passwd- + ### 6.1.7 Ensure permissions on /etc/shadow- are configured ### + chmod 000 /etc/shadow- + chown root.root /etc/shadow- + ### 6.1.4 Ensure permissions on /etc/group- are configured ### + chmod 644 /etc/group- + chown root.root /etc/group- + ### 6.1.5 Ensure permissions on /etc/gshadow- are configured ### + chmod 000 /etc/gshadow- + chown root:root /etc/gshadow- + stop_spinner $? + } | tee -a $LOG +} + +#################################### +#### 6.1.1 World Writable Files #### +#################################### +function world_writable_files() { + { + start_spinner 'Resetting Permissions on all World Writable, Unowned and Ungrouped Files...' + echo "" + #### 6.1.10 Ensure no world writable files exist #### + df --local -P | awk '{if (NR!=1) print $6}' | xargs -I '{}' find '{}' -xdev -type f -perm -0002 + #### 6.1.11 Ensure no unowned files or directories exist #### + df --local -P | awk '{if (NR!=1) print $6}' | xargs -I '{}' find '{}' -xdev -nouser -ls + #### 6.1.12 Ensure no ungrouped files or directories exist #### + df --local -P | awk '{if (NR!=1) print $6}' | xargs -I '{}' find '{}' -xdev -nogroup -ls + #### 6.1.12 Audit SUID executables #### + df --local -P | awk '{if (NR!=1) print $6}' | xargs -I '{}' find '{}' -xdev -type f -perm -4000 -print + #### 6.1.14 Audit SGID executables #### + df --local -P | awk '{if (NR!=1) print $6}' | xargs -I '{}' find '{}' -xdev -type f -perm -2000 -print + stop_spinner $? + } | tee -a $LOG +} + +##################################### +#### 6.2 User and Group Settings #### +##################################### +function user_group_settings() { + { + start_spinner 'Configuring User and Group Settings...' + echo "" + #### 6.2.1 Ensure password fields are not empty #### + awk -F: '($2 == "" ) { print $1 " does not have a password "}' /etc/shadow + #### 6.2.2 Ensure no legacy "+" entries exist in /etc/passwd #### + grep '^+:' /etc/passwd + #### 6.2.3 Ensure no legacy "+" entries exist in /etc/shadow #### + grep '^+:' /etc/shadow + #### 6.2.4 Ensure no legacy "+" entries exist in /etc/group #### + grep '^+:' /etc/group + #### 6.2.5 Ensure root is the only UID 0 account #### + awk -F: '($3 == 0) { print $1 }' /etc/passwd + #### 6.2.6 Ensure root PATH Intergrity #### + if [ "$(echo "$PATH" | grep ::)" != "" ]; then + echo "Empty Directory in PATH (::)" + fi + if [ "$(echo "$PATH" | grep :$)" != "" ]; then + echo "Trailing : in PATH" + fi + p=$(echo "$PATH" | sed -e 's/::/:/' -e 's/:$//' -e 's/:/ /g') + set -- "$p" + while [ "$1" != "" ]; + do + if [ "$1" = "." ]; then + echo "PATH contains ." + shift + continue + fi + if [ -d "$1" ]; then + # shellcheck disable=SC2012 + dirperm=$(ls -ldH "$1" | cut -f1 -d" ") + if [ "$(echo "${dirperm}" | cut -c6)" != "-" ]; then + echo "Group Write permission set on directory $1" + fi + if [ "$(echo "${dirperm}" | cut -c9)" != "-" ]; then + echo "Other Write permission set on directory $1" + fi + # shellcheck disable=SC2012 + dirown=$(ls -ldH "$1" | awk '{print $3}') + if [ "${dirown}" != "root" ] ; then + echo "$1 is not owned by root" + fi + else + echo "$1 is not a directory" + fi + shift + done + stop_spinner $? + } | tee -a $LOG +} + +######################################################## +#### 6.2 User and Group Settings Continued - Part 1 #### +######################################################## +function home_directories() { + { + start_spinner 'Checking and Configuring User Directories...' + echo "" + #### 6.2.7 Ensure all users' home directories exist #### + awk -F: '{ print $1 " " $3 " " $6 }' /etc/passwd | while read -r user uid dir + do + if [ "${uid}" -ge 500 ] && [ -d "${dir}" ] && [ "${user}" != "nfsnobody" ]; then + owner=$(stat -L -c "%U" "${dir}") + if [ "${owner}" != "${user}" ]; then + echo "The home directory (${dir}) of user ${user} is owned by ${owner}." + fi + fi + done + #### 6.2.8 Ensure users' home directories permissions are 750 or more restrictive #### + grep -Ev '(root|halt|sync|shutdown)' /etc/passwd | awk -F: '($8 == "PS" && $7 != "/sbin/nologin") { print $6 }' | while read -r dir + do + # shellcheck disable=SC2012 + dirperm=$(ls -ld "${dir}" | cut -f1 -d" ") + if [ "$( echo "${dirperm}" | cut -c6 )" != "-" ]; then + echo "Group Write permission set on directory $dir" + fi + if [ "$( echo "${dirperm}" | cut -c8 )" != "-" ]; then + echo "Other Read permission set on directory $dir" + fi + if [ "$( echo "${dirperm}" | cut -c9 )" != "-" ]; then + echo "Other Write permission set on directory $dir" + fi + if [ "$( echo "${dirperm}" | cut -c10 )" != "-" ]; then + echo "Other Execute permission set on directory $dir" + fi + done + #### 6.2.9 Ensure users own their home directories #### + awk -F: '{ print $1 " " $3 " " $6 }' /etc/passwd | while read -r user uid dir + do + if [ "$uid" -ge 500 ] && [ ! -d "$dir" ] && [ "$user" != "nfsnobody" ]; then + echo "The home directory ($dir) of user $user does not exist." + fi + done + stop_spinner $? + } | tee -a $LOG +} + +######################################################## +#### 6.2 User and Group Settings Continued - Part 2 #### +######################################################## +function dot_files() { + { + start_spinner 'Checking and Configuring Hidden Files and Directories...' + echo "" + #### 6.2.10 Ensure users' dot files are not group or world writable #### + grep -Ev '(root|sync|halt|shutdown)' /etc/passwd | awk -F: '($7 != "/sbin/nologin") { print $6 }' | while read -r dir + do + for file in "$dir"/.[A-Za-z0-9]* + do + if [ ! -h "${file}" ] && [ -f "${file}" ]; then + # shellcheck disable=SC2012 + fileperm=$(ls -ld "$file" | cut -f1 -d" ") + if [ "$(echo "$fileperm" | cut -c6 )" != "-" ]; then + echo "Group Write permission set on file $file" + fi + if [ "$(echo "$fileperm" | cut -c9 )" != "-" ]; then + echo "Other Write permission set on file $file" + fi + fi + done + done + awk -F: '($3 >= 500) { print $6 }' /etc/passwd | while read -r DIR + do + for FILE in "$DIR"/.[A-Za-z0-9]* + do + if [ ! -h "$FILE" ] && [ -f "$FILE" ]; then + chmod go-w "$FILE" + fi + done + done + #### 6.2.11 Ensure no users have .forward files #### + awk -F: '{ print $6 }' /etc/passwd | while read -r dir + do + if [ ! -h "$dir/.forward" ] && [ -f "$dir/.forward" ]; then + echo ".forward file $dir/.forward exists" + fi + done + #### 6.2.12 Ensure no users have .netrc files #### + awk -F: '{ print $6 }' /etc/passwd | while read -r dir + do + if [ ! -h "$dir/.netrc" ] && [ -f "$dir/.netrc" ]; then + echo ".netrc file $dir/.netrc exists" + fi + done + #### Ensure users' .netrc Files are not group or world accessible #### + grep -Ev '(root|halt|sync|shutdown)' /etc/passwd | awk -F: '($7 != "/sbin/nologin") { print $6 }' | while read -r dir + do + for file in $dir/.netrc + do + if [ ! -h "$file" ] && [ -f "$file" ]; then + # shellcheck disable=SC2012 + fileperm=$(ls -ld "$file" | cut -f1 -d" ") + if [ "$(echo "$fileperm" | cut -c5 )" != "-" ]; then + echo "Group Read set on $file" + fi + if [ "$(echo "$fileperm" | cut -c6 )" != "-" ]; then + echo "Group Write set on $file" + fi + if [ "$(echo "$fileperm" | cut -c7 )" != "-" ]; then + echo "Group Execute set on $file" + fi + if [ "$(echo "$fileperm" | cut -c8 )" != "-" ]; then + echo "Other Read set on $file" + fi + if [ "$(echo "$fileperm" | cut -c9 )" != "-" ]; then + echo "Other Write set on $file" + fi + if [ "$(echo "$fileperm" | cut -c10 )" != "-" ]; then + echo "Other Execute set on $file" + fi + fi + done + done + #### Ensure no users have .rhosts files #### + grep -Ev '(root|halt|sync|shutdown)' /etc/passwd | awk -F: '($7 != "/sbin/nologin") { print $6 }' | while read -r dir + do + for file in $dir/.rhosts; do + if [ ! -h "$file" ] && [ -f "$file" ]; then + echo ".rhosts file in $dir" + fi + done + done + stop_spinner $? + } | tee -a $LOG +} + +######################################################## +#### 6.2 User and Group Settings Continued - Part 3 #### +######################################################## +function group_gid_uid() { + { + start_spinner 'Checking that all Group and UserIDs are valid...' + echo "" + #### Ensure all groups in etc/passwd exist in /etc/group #### + cut -s -d: -f4 /etc/passwd | sort -u | while read -r i + do + if ! grep -q -P "^.*?:x:$i:" /etc/group; then + echo "Group $i is referenced by /etc/passwd but does not exist in /etc/group" + fi + done + #### Ensure no duplicate UIDs exist #### + cut -f3 -d":" /etc/passwd | sort -n | uniq -c | while read -r x + do + [ -z "${x}" ] && break + # shellcheck disable=SC2086 + set - ${x} + if [ "$1" -gt 1 ]; then + users=$(awk -F: '($3 == n) { print $1 }' n="$2" /etc/passwd | xargs) + echo "Duplicate UID ($2): ${users}" + fi + done + #### 6.2.17 Ensure no duplicate GIDs exist #### + cut -f3 -d":" /etc/group | sort -n | uniq -c | while read -r x + do + [ -z "${x}" ] && break + # shellcheck disable=SC2086 + set - ${x} + if [ "$1" -gt 1 ]; then + grps=$(gawk -F: '($3 == n) { print $1 }' n="$2" /etc/group | xargs) + echo "Duplicate GID ($2): ${grps}" >> ${LOG} 2>&1 + fi + done + #### 6.2.18 Ensure no duplicate user names exist #### + cut -f1 -d":" /etc/passwd | sort -n | /usr/bin/uniq -c | while read -r x + do + [ -z "${x}" ] && break + # shellcheck disable=SC2086 + set - ${x} + if [ "$1" -gt 1 ]; then + uids=$(gawk -F: '($1 == n) { print $3 }' n="$2" /etc/passwd | xargs) + echo "Duplicate User Name ($2): ${uids}" + fi + done + #### 6.2.19 Ensure no duplicate group names exist #### + cut -f1 -d":" /etc/group | sort -n | uniq -c | while read -r x + do + [ -z "${x}" ] && break + set - "${x}" + if [ "$1" -gt 1 ]; then + gids=$(gawk -F: '($1 == n) { print $3 }' n="$2" /etc/group | xargs) + echo "Duplicate Group Name ($2): ${gids}" + fi + done + stop_spinner $? + } | tee -a $LOG +} + +######################################### +#### Auto Unattended Security Upates #### +######################################### +function auto_updates() { + { + start_spinner 'Configuring Auto Security Updates...' + echo "" + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle || ${OS} = rocky || ${OS} = alma ]]; then + if [ "${OSVER}" = 7 ]; then + ${PAKMGR} install yum-cron + sed -i 's/update_cmd = default/update_cmd = security/g' /etc/yum/yum-cron.conf + sed -i 's/apply_updates = no/apply_updates = yes/g' /etc/yum/yum-cron.conf + sed -i 's/download_updates = no/download_updates = yes/g' /etc/yum/yum-cron-hourly.conf + systemctl enable yum-cron + systemctl start yum-cron + fi + if [ "${OSVER}" = 8 ]; then + ${PAKMGR} install dnf-automatic + sed -i 's/upgrade_type = default/upgrade_type = security/g' /etc/dnf/automatic.conf + sed -i 's/apply_updates = no/apply_updates = yes/g' /etc/dnf/automatic.conf + systemctl enable --now dnf-automatic.timer + fi + elif [ "${OS}" = ubuntu ]; then + ${PAKMGR} install unattended-upgrades apticron + touch /etc/apt/apt.conf.d/20auto-upgrades + no_show << EOF > /etc/apt/apt.conf.d/20auto-upgrades + APT::Periodic::Update-Package-Lists "1"; + APT::Periodic::Download-Upgradeable-Packages "1"; + APT::Periodic::AutocleanInterval "7"; + APT::Periodic::Unattended-Upgrade "1"; +EOF + sed -i 's/\/\/Unattended-Upgrade\:\:Mail "root";/Unattended-Upgrade\:\:Mail "root";/g' /etc/apt/apt.conf.d/50unattended-upgrades + fi + stop_spinner $? + } | tee -a $LOG +} + +####################################################### +#### Install SysStat Redhat/CentOS 7 and 8, Ubuntu #### +####################################################### +function install_sysstat() { + { + start_spinner 'Installing and Configuring SysStat...' + echo "" + ${PAKMGR} install sysstat + if [ "${OS}" = ubuntu ]; then + sed -i 's/ENABLED="false"/ENABLED="true"/g' /etc/default/sysstat + no_show << EOF > /etc/cron.d/sysstat + # The first element of the path is a directory where the debian-sa1 + # script is located + PATH=/usr/lib/sysstat:/usr/sbin:/usr/sbin:/usr/bin:/sbin:/bin + + # Activity reports every 10 minutes everyday + 5-55/10 * * * * root command -v debian-sa1 > /dev/null && debian-sa1 1 1 + + # Additional run at 23:59 to rotate the statistics file + 59 23 * * * root command -v debian-sa1 > /dev/null && debian-sa1 60 2 +EOF + else + if [ ! -d /var/log/sa ]; then + mkdir /var/log/sa + fi + fi + systemctl enable sysstat + systemctl start sysstat + stop_spinner $? + } | tee -a $LOG +} + +############################################################## +#### Install RootKit Hunter Redhat/CentOS 7 and 8, Ubuntu #### +############################################################## +function install_rkhunter() { + { + start_spinner 'Installing and Configuring RKHunter...' + echo "" + if [[ ${OS} = centos || ${OS} = red || ${OS} = rocky || ${OS} = alma ]]; then + ${PAKMGR} install epel-release + ${PAKMGR} install rkhunter + elif [ "${OS}" = oracle ]; then + if [ "${OSVER}" = 7 ]; then + ${PAKMGR} install oracle-epel-release-el7 + sed -i 's/enabled=0/enabled=1/g' /etc/yum.repos.d/oracle-epel-ol7.repo + fi + if [ "${OSVER}" = 8 ]; then + ${PAKMGR} install oracle-epel-release-el8 + sed -i 's/enabled=0/enabled=1/g' /etc/yum.repos.d/oracle-epel-ol8.repo + fi + ${PAKMGR} install rkhunter + elif [ "${OS}" = ubuntu ]; then + debconf-set-selections <<< ""postfix postfix/mailname string "${HOSTNAME}""" + debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Local Only'" + DEBIAN_FRONTEND=noninteractive ${PAKMGR} install rkhunter >> ${LOG} 2>&1 + fi + rkhunter --update + rkhunter --propupd + sed -i 's/ALLOW_SSH_ROOT_USER=unset/ALLOW_SSH_ROOT_USER=no/g' /etc/rkhunter.conf + stop_spinner $? + } | tee -a $LOG +} + +################################################### +#### Install LMD Redhat/CentOS 7 and 8, Ubuntu #### +################################################### +function install_lmd() { + { + start_spinner 'Installing and Configuring MalDetect...' + echo "" + if [[ ${OS} = centos || ${OS} = red || ${OS} = rocky || ${OS} = alma ]]; then + ${PAKMGR} install epel-release + ${PAKMGR} install mailx inotify-tools tar wget + elif [ "${OS}" = oracle ]; then + if [ "${OSVER}" = 7 ]; then + ${PAKMGR} install oracle-epel-release-el7 + sed -i 's/enabled=0/enabled=1/g' /etc/yum.repos.d/oracle-epel-ol7.repo + fi + if [ "${OSVER}" = 8 ]; then + ${PAKMGR} install oracle-epel-release-el8 + sed -i 's/enabled=0/enabled=1/g' /etc/yum.repos.d/oracle-epel-ol8.repo + fi + ${PAKMGR} install mailx inotify-tools tar wget + elif [ "${OS}" = ubuntu ]; then + export DEBIAN_FRONTEND=noninteractive + ${PAKMGR} install inotify-tools wget + fi + wget http://www.rfxn.com/downloads/maldetect-current.tar.gz + tar -xvzf maldetect-current.tar.gz + cd maldetect-1* || return $? + ./install.sh + cd .. || return $? + rm -rf maldetect-* + if [ "${OS}" = ubuntu ]; then + ln -s /usr/local/maldetect/maldet /bin/maldet + hash -r + fi + sed -i 's/email_alert="0"/email_alert="1"/g' /usr/local/maldetect/conf.maldet + sed -i 's/email_addr="you@domain.com"/email_addr="root@localhost"/g' /usr/local/maldetect/conf.maldet + sed -i 's/quarantine_hits="0"/quarantine_hits="1"/g' /usr/local/maldetect/conf.maldet + sed -i 's/quarantine_clean="0"/quarantine_clean="1"/g' /usr/local/maldetect/conf.maldet + if [[ ${OS} = centos || ${OS} = red || ${OS} = oracle ]]; then + ${PAKMGR} install clamav clamav-devel + elif [ "${OS}" = ubuntu ]; then + export DEBIAN_FRONTEND=noninteractive + ${PAKMGR} install clamav clamav-daemon clamdscan clamav-freshclam + fi + freshclam + stop_spinner $? + } | tee -a $LOG +} + +########################## +#### Install Logwatch #### +########################## +function install_logwatch() { + { + start_spinner 'Installing and Configuring LogWatch...' + ${PAKMGR} install logwatch + LOG_ZZ=/usr/share/logwatch/default.conf/services/zz-disk_space.conf + # shellcheck disable=SC2016 + sed -i 's/#$show_home_dir_sizes = 1/$show_home_dir_sizes = 1/g' $LOG_ZZ + # shellcheck disable=SC2016 + sed -i 's/#$home_dir = "\/home"/$home_dir = "\/home"/g' $LOG_ZZ + # shellcheck disable=SC2016 + sed -i 's/#$show_mail_dir_sizes = 1/#$show_mail_dir_sizes = 1/g' $LOG_ZZ + # shellcheck disable=SC2016 + sed -i 's/#$mail_dir = "\/var\/spool\/mail/$mail_dir = "\/var\/spool\/mail/g' $LOG_ZZ + # shellcheck disable=SC2016 + sed -i 's/#$show_disk_usage = 1/$show_disk_usage = 1/g' $LOG_ZZ + # shellcheck disable=SC2016 + sed -i 's/$HTTP_IGNORE_ERROR_HACKS = 0/$HTTP_IGNORE_ERROR_HACKS = 1/g' /usr/share/logwatch/default.conf/services/http.conf + sed -i 's/Detail = Low/Detail = Med/g' /usr/share/logwatch/default.conf/logwatch.conf + stop_spinner $? + } | tee -a $LOG +} + +############################### +#### Oracle EBS PreInstall #### +############################### +function oci_oracle_ebs_setup() { + { + start_spinner 'Configuring Server for Oracle EBS/WebLogic...' + if [ "${SRVTYPE}" != 3 ]; then + if [[ ${OS} = centos || ${OS} = red || ${OS} = rocky || ${OS} = alma ]]; then + ${PAKMGR} install oracle-ebs-server-R12-preinstall openmotif21 + oci-network-config -X ens3 + sed -i 's/PRESERVE_HOSTINFO=0/PRESERVE_HOSTINFO=2/g' /etc/oci-hostname.conf + groupadd dba + groupadd dev + touch /etc/oraInst.loc + chmod 600 /etc/oraInst.loc + chown applmgr. /etc/oraInst.loc + elif [ "${OS}" = ubuntu ]; then + echo "" + echo -e "\e[7m**** !EBS PreInstall for Ubuntu is not supported! ****\e[0m" + echo "" + fi + fi + if [ "${SRVTYPE}" == 3 ]; then + oci-network-config -X ens3 + sed -i 's/PRESERVE_HOSTINFO=0/PRESERVE_HOSTINFO=2/g' /etc/oci-hostname.conf + fi + } | tee -a $LOG +} + +######################## +#### Function Calls #### +######################## +function oci_rh_ub_common() { + { + check_root + backup + make_swap + time_set + disable_filesystems + tmp_directory + stickybit + gpgkeys + aide_install + sudo_changes + boot_load + core_dumps + sysctl_conf + pre_link + se_troubleshoot_mcs + unconf_daemons + se_linux + banners + inet_service + ntp_config + chrony_cfg + update_security + unsecure_services + mail_config + addon_inet_services + service_clients + tcp_wrappers + auto_updates + uncommon_protocols + iptables_config + audit_accounting + rsyslog_service + journald_config + logfile_permissions + crond_enabled + compress_auditd + config_sshd + config_pam + accounts + config_users_permissions + audit_file_permissions + world_writable_files + user_group_settings + home_directories + dot_files + group_gid_uid + install_sysstat + install_rkhunter + install_lmd + install_logwatch + } +} + +################## +#### OCI Only #### +################## +function oci_only() { + { + oci_iptables + } +} + +################## +#### AWS Only #### +################## +function aws_only() { + { + aws_iptables + } +} + +warn_message \ No newline at end of file diff --git a/Update_CodeSVR.sh b/Update_CodeSVR.sh new file mode 100644 index 0000000..a497956 --- /dev/null +++ b/Update_CodeSVR.sh @@ -0,0 +1,98 @@ +#!/bin/bash + +#################################################################### +#### Code-Server update script for Oracle Linux, Centos/Redhat #### +#### and Ubuntu Servers. #### +#### Author: Phil Connor 02/10/2020 #### +#### Contact: contact@mylinux.work #### +#### Version 1.23 #### +#### #### +#### To use this script chmod it to 755 ./UpDateCodeSVR.sh #### +#### or simply type bash UpDateCodeSVR.sh #### +#################################################################### + +############################# +#### User Configurations #### +############################# +SERVDIR=/usr/local/code-server # where you want the code-server installed + +######################## +#### System Configs #### +######################## +if [ "$(command -v lsb_release)" ]; then + OS=$(lsb_release -i | awk '{print $3}' | tr '[:upper:]' '[:lower:]') + OSVER=$(lsb_release -r | awk '{print $2}' | awk -F. '{print $1}') +else + OS=$(grep PRETTY_NAME /etc/os-release | sed 's/PRETTY_NAME=//g' | tr -d '="' | awk '{print $1}' | tr '[:upper:]' '[:lower:]') + OSVER=$(grep VERSION_ID /etc/os-release | sed 's/VERSION_ID=//g' | tr -d '="' | awk -F. '{print $1}') +fi + +CSVER=$(code-server --version | awk '{print $1}') + +########################################################### +#### Detect Package Manger from OS and OSVer Variables #### +########################################################### +if [[ ${OS} = alma || ${OS} = amazon || ${OS} = centos || ${OS} = red || ${OS} = rocky || ${OS} = oracle ]]; then + if [ "${OSVER}" = 7 ]; then + PAKMGR="yum -y" + else + PAKMGR="dnf -y" + fi +elif [ "${OS}" = ubuntu ]; then + PAKMGR="apt -y" +fi + +################### +#### Update OS #### +################### +function update_os() { + { + if [ "${OS}" = ubuntu ]; then + ${PAKMGR} update + ${PAKMGR} upgrade + else + ${PAKMGR} update + fi + } +} +############################################### +#### Get the latest version of Code Server #### +############################################### +get_latest_version() { + { + version="$(curl -fsSLI -o /dev/null -w "%{url_effective}" https://github.com/coder/code-server/releases/latest)" + version="${version#https://github.com/coder/code-server/releases/tag/}" + version="${version#v}" + echo "$version" + #### Compare Code-Server versions #### + if [ "$version" \> "$CSVER" ]; then + compare=1 + else + compare=0 + fi + } +} + +######################################### +#### Download and Update Codeserver #### +######################################### +install_codeserver() { + { + if [ $compare = 1 ]; then + systemctl stop code-server + # check if command wget exists + if ! command -v wget >/dev/null 2>&1; then + ${PAKMGR} install wget + fi + cd ~/ || exit + wget "https://github.com/coder/code-server/releases/download/v$version/code-server-$version-linux-amd64.tar.gz" + tar xvf "code-server-$version-linux-amd64.tar.gz" + cp -r ~/code-server-"$version"-linux-amd64/* ${SERVDIR} + systemctl start code-server + fi + } +} + +update_os +get_latest_version +install_codeserver diff --git a/auto_pkg_update.sh b/auto_pkg_update.sh new file mode 100644 index 0000000..eee1837 --- /dev/null +++ b/auto_pkg_update.sh @@ -0,0 +1,74 @@ +#!/bin/bash + +###################################################################################### +#### #### +#### Version 2.21.020524 #### +#### For questions or comments pconnor@ara.com #### +#### Author : Phil Connor #### +#### #### +#### Notes : #### +#### This script is a simple "helper" to configure Auto Updates on linux #### +#### servers. #### +#### #### +###################################################################################### + +########################### +#### System Variables #### +########################### +if [ "$(command -v lsb_release)" ]; then + OS=$(lsb_release -i | awk '{print $3}' | tr '[:upper:]' '[:lower:]') + OSVER=$(lsb_release -r | awk '{print $2}' | awk -F. '{print $1}') +else + OS=$(grep PRETTY_NAME /etc/os-release | sed 's/PRETTY_NAME=//g' | tr -d '="' | awk '{print $1}' | tr '[:upper:]' '[:lower:]') + OSVER=$(grep VERSION_ID /etc/os-release | sed 's/VERSION_ID=//g' | tr -d '="' | awk -F. '{print $1}') +fi + +aptcnf="/etc/apt/apt.conf.d" +dnfcnf="/etc/dnf/automatic.conf" +yumcnf="/etc/yum/yum-cron.conf" + +########################################################### +#### Detect Package Manger from OS and OSVer Variables #### +########################################################### +if [[ ${OS} = amazon || ${OS} = red ]]; then + if [[ ${OSVER} = 2 || ${OSVER} = 7 ]]; then + PAKMGR="yum -y" + else + PAKMGR="dnf -y" + fi +elif [ "${OS}" = ubuntu ]; then + PAKMGR="apt -y" +fi + +##################################### +#### Install Auto Update Service #### +##################################### +if [[ ${OS} = amazon || ${OS} = red ]]; then + if [[ ${OSVER} = 2 || ${OSVER} = 7 ]]; then + ${PAKMGR} update + ${PAKMGR} install yum-cron + #sed -i 's/update_cmd = default/update_cmd = security/g' $yum7cnf #<-- comment this out for ALL available upgrades + sed -i 's/apply_updates = no/apply_updates = yes/g' $yumcnf + sed -i 's/download_updates = no/download_updates = yes/g' $yumcnf + systemctl enable --now yum-cron + fi + if [[ ${OSVER} = 8 || ${OSVER} = 9 ]]; then + ${PAKMGR} update + ${PAKMGR} install dnf-automatic + sed -i 's/upgrade_type = default/upgrade_type = security/g' $dnfcnf #<-- comment this out for ALL available upgrades + sed -i 's/apply_updates = no/apply_updates = yes/g' $dnfcnf + systemctl enable --now dnf-automatic.timer + fi +elif [ "${OS}" = ubuntu ]; then + ${PAKMGR} upgrade + ${PAKMGR} install unattended-upgrades + dpkg-reconfigure --priority=medium unattended-upgrades + + touch $aptcnf/20auto-upgrades + { + echo 'APT::Periodic::Update-Package-Lists "1";' + echo 'APT::Periodic::Download-Upgradeable-Packages "1";' + echo 'APT::Periodic::AutocleanInterval "7";' + echo 'APT::Periodic::Unattended-Upgrade "1";' + } > $aptcnf/20auto-upgrades +fi diff --git a/create_swap.sh b/create_swap.sh new file mode 100644 index 0000000..ec4959f --- /dev/null +++ b/create_swap.sh @@ -0,0 +1,231 @@ +#! /bin/bash + +#check permissions +if [[ $EUID -ne 0 ]]; then + echo "" + echo "This script must be run as root! Login as root, sudo or su." + echo "" + exit 1; +fi + +# #load code functions +# source create_swap_salt.sh + +# #setup permissions for functions +# chmod 500 create_swap_salt.sh + +# echo "" +# echo "--------------------------------------------------------------------------" +# echo "setupSwap - creates swap space on your server based on AWS guidelines" +# echo "--------------------------------------------------------------------------" +# echo "" +# echo "This will remove an existing swap file and then create a new one. " +# echo "Please read the disclaimer and review the code before proceeding." +# echo "" + +# echo -n " Do you want to proceed? (y/n): "; read proceed +# if [ "$proceed" == "y" ]; then +# echo "" + +# swapSetup + +# else + +# echo "You chose to exit. Bye!" + +# fi + +# echo "" +# echo "--------------------------------------------------------------------------" +# echo "" + +# exit 0 + + +removeSwap() { + echo "Will remove swap and backup fstab." + echo "" + + #get the date time to help the scripts + backupTime=$(date +%y-%m-%d--%H-%M-%S) + + #get the swapfile name + swapSpace=$(swapon -s | tail -1 | awk '{print $1}' | cut -d '/' -f 2) + #debug: echo $swapSpace + + #turn off swapping + swapoff /"$swapSpace" + + #make backup of fstab + cp /etc/fstab /etc/fstab."$backupTime" + + #remove swap space entry from fstab + sed -i "/swap/d" /etc/fstab + + #remove swapfile + rm -f "/$swapSpace" + + echo "" + echo "--> Done" + echo "" +} + +############### +### Spinner ### +############### +function spinner() { + { + spinner="/|\\-/|\\-" + while : + do + for i in $(seq 0 7) + do + echo -n "${spinner:$i:1}" + echo -en "\010" + sleep 1 + done + done + } +} + +######################################## +### Add Swappiness setting to sysctl ### +######################################## +if ! grep swappiness /etc/sysctl.conf; then + echo 80 > /proc/sys/vm/swappiness + echo 'vm.swappiness = 80' >> /etc/sysctl.conf +fi + +################################################################################################ +### This function identifies available ram, calculates the swap file size and configures it #### +################################################################################################ +function createSwap() { + { + echo "Will create a swap and setup fstab." + echo "" + + ### Get available physical ram + availMemMb=$(grep MemTotal /proc/meminfo | awk '{print $2}') + ### Debug: echo $availMemMb + + ### Convert from kb to mb to gb + gb=$(awk "BEGIN {print $availMemMb/1024/1024}") + ### to debug: echo $gb + + ### Round the number to nearest gb + gb=$(echo "$gb" | awk '{print ($0-int($0)<0.499)?int($0):int($0)+1}') + ### to debug: echo $gb + + echo "-> Available Physical RAM: $gb Gb" + echo "" + if [ "$gb" -eq 0 ]; then + echo "Something went wrong! Memory cannot be 0!" + exit 1; + fi + + if [ "$gb" -le 2 ]; then + echo " Memory is less than or equal to 2 Gb" + swapSizeGb=$(( gb * 2 )) + echo " -> Set swap size to $swapSizeGb Gb" + fi + if [ "$gb" -gt 2 ] && [ "$gb" -lt 32 ]; then + echo " Memory is more than 2 Gb and less than to 32 Gb." + swapSizeGb=$(( gb + 4 - 2 )) + echo " -> Set swap size to $swapSizeGb Gb." + fi + if [ "$gb" -gt 32 ]; then + echo " Memory is more than or equal to 32 Gb." + swapSizeGb=$gb + echo " -> Set swap size to $swapSizeGb Gb." + fi + echo "" + + echo "Creating the swap file! This may take a few minutes." + echo "" + + ############################ + ### Create the swap file ### + ############################ + + ### start the spinner: + spinner & + + ### Note its PID: + SPIN_PID=$! + + ### Kill the spinner on any signal, including our own exit. + trap "kill -9 $SPIN_PID" $(seq 0 15) + + ### Convert gb to mb to avoid error: + mb=$(( gb * 1024 )) + + ### Create a swap file on root system and set file size to mb variable + echo "-> Create swap file." + echo "" + dd if=/dev/zero of=/swapfile bs=1M count=$mb + + ### Set the rw permissions + echo "-> Set swap file permissions." + echo "" + chmod 600 /swapfile + + ### Mkswap file + echo "-> Creating swap." + echo "" + mkswap /swapfile + + ### Enable the swap file for use + echo "-> Turn on swap." + echo "" + swapon /swapfile + + echo "" + + ### Check and update (if needed) the fstab + if grep -q "swap" /etc/fstab; then + echo "-> The fstab contains a swap entry." + #do nothing + else + echo "-> The fstab does not contain a swap entry. Adding an entry." + echo "/swapfile swap swap defaults 0 0" >> /etc/fstab + fi + + echo "" + echo "--> Done" + echo "" + + exit 1 + } +} + +function swapSetup() { + { + #check if swap is on + isSwapOn=$(swapon -s | tail -1) + + if [[ "$isSwapOn" == "" ]]; then + echo "No swap has been configured! Will create." + echo "" + + createSwap + else + echo "Swap has been configured. Will remove and then re-create the swap." + echo "" + + removeSwap + createSwap + fi + + echo 'Setup swap complete! Check output to confirm everything is good.' + } +} + +swapSetup + +##### Notes ##### +#Root +# lvresize /swap -L +2G (to increase swap by 2G) +# lvreduce /swap -L -1G (to reduce the swap by 1Gb) +#Drive +# lvresize /dev/swap -L +2G (to increase swap by 2G) +# lvreduce /dev/swap -L -1G (to reduce the swap by 1Gb) \ No newline at end of file diff --git a/docker_cleanup.sh b/docker_cleanup.sh new file mode 100644 index 0000000..6fc35f9 --- /dev/null +++ b/docker_cleanup.sh @@ -0,0 +1,116 @@ +#!/bin/bash + +############################################################################ +#### docker_cleanup.sh #### +#### Version 2.09.27.22 #### +#### #### +#### This Script is for Cleaning Docker on GitLab Runner #### +#### #### +#### This script just views and prunes unused and dangling docker #### +#### images, networks and unlinks pulls to clear disk space #### +#### #### +#### This script can be manually ran if needed, but is configured in #### +#### in cron to run once a week #### +#### #### +#### 0 4 * * 0 /usr/local/bin/docker_cleanup.sh #### +#### #### +#### Questions or Comments Contact: contact@mylinux.work #### +############################################################################ + + +######################## +### System Variables ### +######################## +max_weeks=4 +tstamp=$(date +%Y%m%d_%H%M%S) +log_path=/var/log +filename=gitlab-runner-clean_$tstamp.log +log=$log_path/$filename + +############################ +### Check Space PreClean ### +############################ +docker_space_pre() { + cspace=$(docker system df) + { + echo "PrePruned Docker Space:" + echo '' + echo "$cspace" + + } >>"$log" + docker_find +} + +########################################## +### Find and List Docker Images in Log ### +########################################## +docker_find() { + { + echo '#####################################################################' + echo ' Finding Images' + echo '#####################################################################' + + } >> "$log" + + lsimages=$(docker image ls) + + { + echo '' + echo 'listing all Docker Images:' + echo '' + echo "$lsimages" + + } >> "$log" + docker_cleanup +} + +###################################### +### Check, Clean and Remove Images ### +###################################### +docker_cleanup() { + { + echo '#####################################################################' + echo ' Cleaning Images' + echo '#####################################################################' + echo '' + + } + + docker image ls | awk 'NR>1 {print $0}' | while read -r list + do + id_img=$(echo "$list" | awk '{print $3}') + + is_month=$(echo "$list" | grep 'month') + if [ -n "$is_month" ]; then + echo "$id_img" + docker rmi -f "$id_img" + continue + fi + + num_week=$(echo "$list" | grep "week" | awk '{print $4}') + if [ -n "$num_week" ] && [ "$num_week" -ge $max_weeks ]; then + echo "$id_img" + docker rmi -f "$id_img" + fi + done + + docker_space_post +} >> "$log" + +############################## +### Check Space Post Clean ### +############################## +docker_space_post() { + cspace=$(docker system df) + { + echo "Current Docker Space, after Pruning:" + echo '' + echo "$cspace" + + } >>"$log" +} + +##################### +### Function Call ### +##################### +docker_space_pre diff --git a/gitlab_update.sh b/gitlab_update.sh new file mode 100644 index 0000000..cd5cff4 --- /dev/null +++ b/gitlab_update.sh @@ -0,0 +1,516 @@ +#!/bin/bash + +############################################################################# +#### gitlab_update.sh #### +#### Version 2.7.7-71123 #### +#### #### +#### This Script is for updating GitLab and GitLab Runner #### +#### #### +#### Before running this script you must ensure that you have plenty of #### +#### disk space for all migrations to run, also due to amount of time #### +#### required for this script to run I recommend using screen so that #### +#### you are not timed out when some of the migrations are running #### +#### #### +#### Questions or Comments Contact: contact@mylinux.work #### +############################################################################# + +######################## +### System Variables ### +######################## +if [ "$(command -v lsb_release)" ]; then + OS=$(lsb_release -i | awk '{print $3}' | tr '[:upper:]' '[:lower:]') + OSVER=$(lsb_release -r | awk '{print $2}' | awk -F. '{print $1}') +else + OS=$(grep PRETTY_NAME /etc/os-release | sed 's/PRETTY_NAME=//g' | tr -d '="' | awk '{print $1}' | tr '[:upper:]' '[:lower:]') + OSVER=$(grep VERSION_ID /etc/os-release | sed 's/VERSION_ID=//g' | tr -d '="' | awk -F. '{print $1}') +fi + +######################################### +### Simple GitLab CE/EE Versions Array ### +########################################## +a1=(12.0.0 12.0.0-ee 12.0.1 12.0.1-ee 12.0.2 12.0.2-ee 12.0.3 12.0.3-ee 12.0.4 12.0.4-ee 12.0.6 12.0.6-ee 12.0.8 12.0.8-ee) +a2=(12.0.12 12.0.12-ee 12.1.0 12.1.0-ee 12.1.1 12.1.1-ee 12.1.2 12.1.2-ee 12.1.3 12.1.3-ee 12.1.4 12.1.4-ee 12.1.6 12.1.6-ee 12.1.8 12.1.8-ee 12.1.9 12.1.9-ee 12.1.11 12.1.11-ee 12.1.12 12.1.12-ee 12.1.13 12.1.13-ee 12.1.14 12.1.14-ee) +a3=(12.1.17 12.1.17-ee 12.2.0 12.2.0-ee 12.2.1 12.2.1-ee 12.2.3 12.2.3-ee 12.2.4 12.2.4-ee 12.2.5 12.2.5-ee 12.2.6 12.2.6-ee 12.2.7 12.2.7-ee 12.2.8 12.2.8-ee 12.2.9 12.2.9-ee 12.2.12 12.2.12-ee 12.3.0 12.3.0-ee 12.3.1 12.3.1-ee 12.3.2 12.3.2-ee 12.3.3 12.3.3-ee 12.3.4 12.3.4-ee 12.3.5 12.3.5-ee 12.3.6 12.3.6-ee 12.3.7 12.3.7-ee 12.3.8 12.3.8-ee 12.3.9 12.3.9-ee 12.4.0 12.4.0-ee 12.4.1 12.4.1-ee 12.4.2 12.4.2-ee 12.4.3 12.4.3-ee 12.4.4 12.4.4-ee 12.4.5 12.4.5-ee 12.4.6 12.4.6-ee 12.4.7 12.4.7-ee 12.4.8 12.4.8-ee 12.5.0 12.5.0-ee 12.5.1 12.5.1-ee 12.5.2 12.5.2-ee 12.5.3 12.5.3-ee 12.5.4 12.5.4-ee 12.5.5 12.5.5-ee 12.5.6 12.5.6-ee 12.5.7 12.5.7-ee 12.5.9 12.5.9-ee 12.5.10 12.5.10-ee 12.6.0 12.6.0-ee 12.6.1 12.6.1-ee 12.6.2 12.6.2-ee 12.6.3 12.6.3-ee 12.6.4 12.6.4-ee 12.6.6 12.6.6-ee 12.6.7 12.6.7-ee 12.6.8 12.6.8-ee 12.7.0 12.7.0-ee 12.7.2 12.7.2-ee 12.7.4 12.7.4-ee 12.7.5 12.7.5-ee 12.7.6 12.7.6-ee 12.7.7 12.7.7-ee 12.7.8 12.7.8-ee 12.7.9 12.7.9-ee 12.8.0 12.8.0-ee 12.8.1 12.8.1-ee 12.8.2 12.8.2-ee 12.8.5 12.8.5-ee 12.8.6 12.8.6-ee 12.8.7 12.8.7-ee 12.8.8 12.8.8-ee 12.8.9 12.8.9-ee 12.8.10 12.8.10-ee 12.9.0 12.9.0-ee 12.9.1 12.9.1-ee 12.9.2 12.9.2-ee 12.9.3 12.9.3-ee 12.9.4 12.9.4-ee 12.9.5 12.9.5-ee 12.9.7 12.9.7-ee 12.9.8 12.9.8-ee 12.9.9 12.9.9-ee 12.9.10 12.9.10-ee 12.10.0 12.10.0-ee 12.10.1 12.10.1-ee 12.10.2 12.10.2-ee 12.10.3 12.10.3-ee 12.10.5 12.10.5-ee 12.10.6 12.10.6-ee 12.10.7 12.10.7-ee 12.10.8 12.10.8-ee 12.10.9 12.10.9-ee 12.10.10 12.10.10-ee 12.10.11 12.10.11-ee 12.10.12 12.10.12-ee 12.10.13 12.10.13-ee) +a4=(12.10.14 12.10.14-ee 13.0.0 13.0.0-ee 13.0.1 13.0.1-ee 13.0.3 13.0.3-ee 13.0.4 13.0.4-ee 13.0.5 13.0.5-ee 13.0.6 13.0.6-ee 13.0.7 13.0.7-ee 13.0.8 13.0.8-ee 13.0.9 13.0.9-ee 13.0.10 13.0.10-ee 13.0.12 13.0.12-ee 13.0.13 13.0.13-ee) +a5=(13.0.14 13.0.14-ee 13.1.0 13.1.0-ee 13.1.1 13.1.1-ee 13.1.2 13.1.2-ee 13.1.3 13.1.3-ee 13.1.4 13.1.4-ee 13.1.5 13.1.5-ee 13.1.6 13.1.6-ee 13.1.7 13.1.7-ee 13.1.8 13.1.8-ee 13.1.9 13.1.9-ee 13.1.10 13.1.10-ee) +a6=(13.1.11 13.1.11-ee 13.2.0 13.2.0-ee 13.2.1 13.2.1-ee 13.2.2 13.2.2-ee 13.2.3 13.2.3-ee 13.2.4 13.2.4-ee 13.2.5 13.2.5-ee 13.2.6 13.2.6-ee 13.2.7 13.2.7-ee 13.2.8 13.2.8-ee 13.2.9 13.2.9-ee 13.2.10 13.2.10-ee 13.3.0 13.3.0-ee 13.3.1 13.3.1-ee 13.3.2 13.3.2-ee 13.3.3 13.3.3-ee 13.3.4 13.3.4-ee 13.3.5 13.3.5-ee 13.3.6 13.3.6-ee 13.3.7 13.3.7-ee 13.3.8 13.3.8-ee 13.3.9 13.3.9-ee 13.4.0 13.4.0-ee 13.4.1 13.4.1-ee 13.4.2 13.4.2-ee 13.4.3 13.4.3-ee 13.4.4 13.4.4-ee 13.4.5 13.4.5-ee 13.4.6 13.4.6-ee 13.4.7 13.4.7-ee 13.5.0 13.5.0-ee 13.5.1 13.5.1-ee 13.5.2 13.5.2-ee 13.5.3 13.5.3-ee 13.5.4 13.5.4-ee 13.5.5 13.5.5-ee 13.5.6 13.5.6-ee 13.5.7 13.5.7-ee 13.6.0 13.6.0-ee 13.6.1 13.6.1-ee 13.6.2 13.6.2-ee 13.6.3 13.6.3-ee 13.6.4 13.6.4-ee 13.6.5 13.6.5-ee 13.6.6 13.6.6-ee 13.6.7 13.6.7-ee 13.7.0 13.7.0-ee 13.7.1 13.7.1-ee 13.7.2 13.7.2-ee 13.7.3 13.7.3-ee 13.7.4 13.7.4-ee 13.7.5 13.7.5-ee 13.7.6 13.7.6-ee 13.7.7 13.7.7-ee 13.7.8 13.7.8-ee 13.7.9 13.7.9-ee 13.8.0 13.8.0-ee 13.8.1 13.8.1-ee 13.8.2 13.8.2-ee 13.8.4 13.8.4-ee 13.8.5 13.8.5-ee 13.8.6 13.8.6-ee 13.8.7 13.8.7-ee) +a7=(13.8.8 13.8.8-ee 13.9.0 13.9.0-ee 13.9.1 13.9.1-ee 13.9.2 13.9.2-ee 13.9.3 13.9.3-ee 13.9.4 13.9.4-ee 13.9.5 13.9.5-ee 13.9.6 13.9.6-ee 13.9.7 13.9.7-ee 13.10.0 13.10.0-ee 13.10.1 13.10.1-ee 13.10.2 13.10.2-ee 13.10.3 13.10.3-ee 13.10.4 13.10.4-ee 13.10.5 13.10.5-ee 13.11.0 13.11.0-ee 13.11.1 13.11.1-ee 13.11.2 13.11.2-ee 13.11.3 13.11.3-ee 13.11.4 13.11.4-ee 13.11.5 13.11.5-ee 13.11.6 13.11.6-ee 13.11.7 13.11.7-ee 13.12.0 13.12.0-ee 13.12.1 13.12.1-ee 13.12.2 13.12.2-ee 13.12.3 13.12.3-ee 13.12.4 13.12.4-ee 13.12.5 13.12.5-ee 13.12.6 13.12.6-ee 13.12.7 13.12.7-ee 13.12.8 13.12.8-ee 13.12.9 13.12.9-ee 13.12.10 13.12.10-ee 13.12.11 13.12.11-ee 13.12.12 13.12.12-ee) +a8=(13.12.15 13.12.15-ee 14.0.0 14.0.0-ee 14.0.1 14.0.1-ee 14.0.2 14.0.2-ee 14.0.3 14.0.3-ee 14.0.4 14.0.4-ee 14.0.5 14.0.5-ee 14.0.6 14.0.6-ee 14.0.7 14.0.7-ee 14.0.8 14.0.8-ee 14.0.9 14.0.9-ee 14.0.10 14.0.10-ee 14.10.11 14.10.11-ee) +a9=(14.0.12 14.0.12-ee 14.1.0 14.1.0-ee 14.1.1 14.1.1-ee 14.1.2 14.1.2-ee 14.1.3 14.1.3-ee 14.1.4 14.1.4-ee 14.1.5 14.1.5-ee 14.1.6 14.1.6-ee 14.1.7 14.1.7-ee 14.1.8 14.1.8-ee 14.2.0 14.2.0-ee 14.2.1 14.2.1-ee 14.2.2 14.2.2-ee 14.2.3 14.2.3-ee 14.2.4 14.2.4-ee 14.2.5 14.2.5-ee 14.2.6 14-2.6-ee 14.2.7 14.2.7-ee 14.3.0 14.3.0-ee 14.3.1 14.3.1-ee 14.3.2 14.3.2-ee 14.3.3 14.3.3-ee 14.3.4 14.3.4-ee 14.3.5 14.3.5-ee) +a10=(14.3.6 14.3.6-ee 14.4.0 14.4.0-ee 14.4.1 14.4.1-ee 14.4.2 14.4.2-ee 14.4.3 14.4.3-ee 14.4.4 14.4.4-ee 14.4.5 14.4.5-ee 14.5.0 14.5.0-ee 14.5.1 14.5.1-ee 14.5.2 14.5.2-ee 14.5.3 14.5.3-ee 14.5.4 14.5.4-ee 14.6.0 14.6.0-ee 14.6.1 14.6.1-ee 14.6.2 14.6.2-ee 14.6.3 14.6.3-ee 14.6.4 14.6.4-ee 14.6.5 14.6.5-ee 14.6.6 14.6.6-ee 14.6.7 14.6.7-ee 14.7.0 14.7.0-ee 14.7.1 14.7.1-ee 14.7.2 14.7.2-ee 14.7.3 14.7.3-ee 14.7.4 14.7.4-ee 14.7.5 14.7.5-ee 14.7.6 14.7.6-ee 14.7.7 14.7.7-ee 14.8.0 14.8.0-ee 14.8.1 14.8.1-ee 14.8.2 14.8.2-ee 14.8.3 14.8.3-ee 14.8.4 14.8.4-ee 14.8.5 14.8.5-ee 14.9.0 14.9.0-ee 14.9.1 14.9.1-ee 14.9.2 14.9.2-ee 14.9.3 14.9.3-ee 14.9.4 14.9.4-ee) +a11=(14.9.5 14.9.5-ee 14.10.0 14.10.0-ee 14.10.1 14.10.1-ee 14.10.2 14.10.2-ee 14.10.3 14.10.3-ee 14.10.4 14.10.4-ee) +a12=(14.10.5 14.10.5-ee 15.0.0 15.0.0-ee 15.0.1 15.0.1-ee 15.0.2 15.0.2-ee 15.0.3 15.0.3-ee 15.0.4 15.0.4-ee) +a13=(15.0.5 15.0.5-ee 15.1.0 15.1.0-ee 15.1.1 15.1.1-ee 15.1.2 15.1.2-ee 15.1.3 15.1.3-ee 15.1.4 15.1.4-ee 15.1.5 15.1.5-ee) +a14=(15.1.6 15.1.6-ee 15.2.0 15.2.0-ee 15.2.1 15.2.1-ee 15.2.2 15.2.2-ee 15.2.3 15.2.3-ee 15.2.4 15.2.4-ee 15.3.0 15.3.0-ee 15.3.1 15.3.1-ee 15.3.2 15.3.2-ee 15.3.3 15.3.3-ee 15.3.4 15.3.4-ee 15.3.5 15.3.5-ee 15.4.0 15.4.0-ee 15.4.2 15.4.2-ee 15.4.3 15.4.3-ee 15.4.4 15.4.4-ee 15.4.5 15.4.5-ee) +a15=(15.4.6 15.4.6-ee 15.5.0 15.5.0-ee 15.5.1 15.5.1-ee 15.5.2 15.5.2-ee 15.5.3 15.5.3-ee 15.5.4 15.5.4-ee 15.5.5 15.5.5-ee 15.5.6 15.5.6-ee 15.5.7 15.5.7-ee 15.5.8 15.5.8-ee 15.5.9 15.5.9-ee 15.6.0 15.6.0-ee 15.6.1 15.6.1-ee 15.6.2 15.6.2-ee 15.6.3 15.6.3-ee 15.6.4 15.6.4-ee 15.6.5 15.6.5-ee 15.6.6 15.6.6-ee 15.6.7 15.6.7-ee 15.6.8 15.6.8-ee 15.7.0 15.7.0-ee 15.7.1 15.7.1-ee 15.7.2 15.7.2-ee 15.7.3 15.7.3-ee 15.7.4 15.7.4-ee 15.7.5 15.7.5-ee 15.7.6 15.7.6-ee 15.7.7 15.7.7-ee 15.7.8 15.7.8-ee 15.7.9 15.7.9-ee 15.8.0 15.8.0-ee 15.8.1 15.8.1-ee 15.8.2 15.8.2-ee 15.8.3 15.8.3-ee 15.8.4 15.8.4-ee 15.8.5 15.8.5-ee 15.8.6 15.8.6-ee 15.9.0 15.9.0-ee 15.9.1 15.9.1-ee 15.9.2 15.9.2-ee 15.9.3 15.9.3-ee 15.9.4 15.9.4-ee 15.9.5 15.9.5-ee 15.9.6 15.9.6-ee 15.9.7 15.9.7-ee 15.9.8 15.9.8-ee 15.10.0 15.10.0-ee 15.10.1 15.10.1-ee 15.10.2 15.10.2-ee 15.10.3 15.10.3-ee 15.10.4 15.10.4-ee 15.10.5 15.10.5-ee 15.10.6 15.10.6-ee 15.10.7 15.10.7-ee 15.11.0 15.11.1-ee 15.11.1-ee 15.11.2-ee 15.11.2-ee 15.11.3 15.11.3-ee 15.11.4 15.11.4-ee 15.11.5 15.11.5-ee 15.11.6 15.11.6-ee 15.11.7 15.11.7-ee 15.11.8 15.11.8-ee 15.11.9 15.11.9-ee 15.11.9 15.11.9-ee 15.11.10 15.11.10-ee 15.11.11 15.11.11-ee 16.0.0 16.0.0-ee 16.0.1 16.0.1-ee 16.0.2 16.0.2-ee 16.0.3 16.0.3-ee 16.0.4 16.0.4-ee 16.0.5 16.0.5-ee 16.0.6 16.0.6-ee 16.0.7 16.0.7-ee 16.1.0 16.1.0-ee 16.1.1 16.1.1-ee) +a16=(16.1.2 16.1.2-ee) + +#################################################### +### Simple Color/Message Functions and Variables ### +#################################################### +ESC=$(printf '\033') +RST="${ESC}[0m" +RED="${ESC}[1;31m" +RFL="${ESC}[1;31;5;31m" +GRN="${ESC}[1;32m" +WHT="${ESC}[1;37m" +ERR='ERROR!' +GME1='There are still' +GME2='Queued' +GME3='Background' +GME4='Migration tasks running' +GME5='This script will wait 5 mins before re-checking and continuing with the upgrade' +GERR='- GitLab or GitLab Runner does not appear to be installed on this server' +MQMS='Checking for Scheduled, Queued and Currently Running Background Migrations' +GRM='This script has completed -' +GRMS='The Server is running the latest version of' +GRMS1='GitLab' +GRMS2='GitLab-Runner' +RERR='- Please run this script as root' + +fn_grn() { + printf "${GRN}%s${RST}\n" "$1"; +} + +fn_red() { + printf "${RED}%s${RST}\n" "$1"; +} + +fn_rfl() { + printf "${RFL}%s${RST}\n" "$1"; +} + +fn_wht() { + printf "${WHT}%s${RST}\n" "$1"; +} + +fn_runerr() { + echo -ne " + + $(fn_rfl "$ERR") $(fn_red "$RERR") + + " + exit 2 +} + +fn_glgrerr() { + echo -ne " + + $(fn_rfl "$ERR") $(fn_red "$GERR") + + " +} + +fn_glm() { + echo -ne " + + $(fn_grn "$GRM") $(fn_grn "$GRMS") $(fn_wht "$GRMS1" ) + + " +} + +fn_grm() { + echo -ne " + + $(fn_grn "$GRM") $(fn_grn "$GRMS") $(fn_wht "$GRMS2" ) + + " +} + +fn_mrun() { + echo -ne " + $(fn_red "$GME1") $(fn_wht "$glrun") $(fn_red "$GME3") $(fn_red "$GME4") + + $(fn_wht "$GME5") + + " +} + +fn_mqms() { + echo -ne " + + $(fn_wht "$MQMS") + " +} + +fn_mque() { + echo -ne " + $(fn_red "$GME1") $(fn_wht "$glque") $(fn_red "$GME2") $(fn_red "$GME4") + + $(fn_wht "$GME5") + " +} + +fn_snooze() { + sleep 5m & + pid=$! + + frames="┤ ┘ ┴ └ ├ ┌ ┬ ┐" + while kill -0 $pid > /dev/null 2>&1 + do + for frame in $frames + do + time=$(date +%r) + printf "%s\r ... $frame Waiting 5 Mins ... " "Current Server Time: $time" + sleep 0.1 + done + done + gitlab_check +} + +############################################## +### Checking if GitLab-Runner is Installed ### +############################################## +# shellcheck disable=SC2317 # Don't warn about unreachable commands in this function +runner_installed() { + { + if ! [ -x "$(command -v gitlab-runner)" ]; then + gitlab_installed + else + $pkgmgr install gitlab-runner + fn_grm + exit 0 + fi + } +} + +########################################################### +#### Detect Package Manger from OS and OSVer Variables #### +########################################################### +if [ "${OS}" = ubuntu ]; then + pkgmgr="apt -y --allow-change-held-packages" + $pkgmgr update +elif [ "${OS}" = amazon ]; then + if [ "${OSVER}" = 2 ]; then + pkgmgr="yum -y" + fi +elif [ "${OS}" = red ]; then + if [ "${OSVER}" = 7 ]; then + pkgmgr="yum -y" + else + pkgmgr="dnf -y" + fi +fi + +############################################## +### Checking if GitLab-Runner is Installed ### +############################################## +runner_installed() { + { + if ! [ -x "$(command -v gitlab-runner)" ]; then + gitlab_installed + else + $pkgmgr install gitlab-runner + fn_grm + exit 0 + fi + } +} + +####################################### +### Checking if GitLab is installed ### +####################################### +gitlab_installed() { + { + if ! [ -x "$(command -v gitlab-ctl)" ]; then + fn_glgrerr + exit 1 + else + ### Detect if GitLab is CE or EE ### + if ! grep -ow "gitlab-ce" /opt/gitlab/version-manifest.txt; then + glt=ee + else + glt=ce + fi + export glt + gitlab_check + fi + } +} + +###################################### +### Migration Backgound Check Loop ### +###################################### +function gitlab_check() { + { + fn_mqms + glver=$(cat /var/opt/gitlab/gitlab-rails/VERSION) + if [[ "$glver" > 14.0.0 ]];then + for glque in $(gitlab-rails runner -e production 'puts Gitlab::Database::BackgroundMigration::BatchedMigration.queued.count') + do + if [[ $glque != 0 ]]; then + fn_mque + fn_snooze + fi + done + fi + for glrun in $(gitlab-rails runner -e production 'puts Gitlab::BackgroundMigration.remaining') + do + if [[ $glrun != 0 ]]; then + fn_mrun + fn_snooze + fi + done + gitlab_update + } +} + +################################ +### Simple Update for GitLab ### +################################ +function gitlab_update() { + { + glver=$(cat /var/opt/gitlab/gitlab-rails/VERSION) + + if [ ! -d /root/gitlab_backups ]; then + mkdir /root/gitlab_backups + cp -ar /etc/gitlab/* /root/gitlab_backups + fi + + for a in "${a1[@]}" + do + if [[ $glver = "$a" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=12.0.12-$glt.0 + else + $pkgmgr install gitlab-$glt-12.0.12 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + gitlab_check + fi + done + + for b in "${a2[@]}" + do + if [[ $glver = "$b" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=12.1.17-$glt.0 + else + $pkgmgr install gitlab-$glt-12.1.17 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + gitlab_check + fi + done + + for c in "${a3[@]}" + do + if [[ $glver = "$c" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=12.10.14-$glt.0 + else + $pkgmgr install gitlab-$glt-12.10.14 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + gitlab_check + fi + done + + for d in "${a4[@]}" + do + if [[ $glver = "$d" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=13.0.14-$glt.0 + else + $pkgmgr install gitlab-$glt-13.0.14 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + gitlab_check + fi + done + + for e in "${a5[@]}" + do + if [[ $glver = "$e" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=13.1.11-$glt.0 + else + $pkgmgr install gitlab-$glt-13.1.11 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + gitlab_check + fi + done + + for f in "${a6[@]}" + do + if [[ $glver = "$f" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=13.8.8-$glt.0 + else + $pkgmgr install gitlab-$glt-13.8.8 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + gitlab_check + fi + done + + for g in "${a7[@]}" + do + if [[ $glver = "$g" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=13.12.15-$glt.0 + else + $pkgmgr install gitlab-$glt-13.12.15 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + gitlab_check + fi + done + + for h in "${a8[@]}" + do + if [[ $glver = "$h" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=14.0.12-$glt.0 + else + $pkgmgr install gitlab-$glt-14.0.12 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + # gitlab-ctl restart postgresql # <-- Use only for standalone, not needed for rds + gitlab_check + fi + done + + for i in "${a9[@]}" + do + if [[ $glver = "$i" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=14.3.6-$glt.0 + else + $pkgmgr install gitlab-$glt-14.3.6 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + # gitlab-ctl restart redis # <-- Use only for standalone, not needed for rds + gitlab_check + fi + done + + for j in "${a10[@]}" + do + if [[ $glver = "$j" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=14.9.5-$glt.0 + else + $pkgmgr install gitlab-$glt-14.9.5 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + gitlab_check + fi + done + + for k in "${a11[@]}" + do + if [[ $glver = "$k" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=14.10.5-$glt.0 + else + $pkgmgr install gitlab-$glt-14.10.5 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + gitlab_check + fi + done + + for l in "${a12[@]}" + do + if [[ $glver = "$l" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=15.0.5-$glt.0 + else + $pkgmgr install gitlab-$glt-15.0.5 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + # gitlab-ctl restart postgesql # <-- Use only for standalone, not needed for rds + gitlab_check + fi + done + + for m in "${a13[@]}" + do + if [[ $glver = "$m" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=15.1.6-$glt.0 + else + $pkgmgr install gitlab-$glt-15.1.6 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + gitlab_check + fi + done + + for n in "${a14[@]}" + do + if [[ $glver = "$n" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=15.4.6-$glt.0 + else + $pkgmgr install gitlab-$glt-15.4.6 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + # gitlab-ctl restart redis # <-- Use only for standalone, not needed for rds + gitlab_check + fi + done + + for o in "${a15[@]}" + do + if [[ $glver = "$o" ]]; then + if [ "${OS}" = ubuntu ]; then + $pkgmgr install gitlab-$glt=16.1.2-$glt.0 + else + $pkgmgr install gitlab-$glt-16.1.2 + if [ "${OS}" = red ]; then + gitlab-ctl reconfigure + fi + fi + gitlab_check + fi + done + + for p in "${a16[@]}" + do + if [[ $glver = "$p" ]]; then + fn_glm + exit 0 + fi + done + } +} + +####################################### +### Check for Root / Function Calls ### +####################################### +if [ "$(whoami)" != root ]; then + fn_runerr +else + runner_installed +fi \ No newline at end of file diff --git a/mk_swap.sh b/mk_swap.sh new file mode 100644 index 0000000..c87bbfb --- /dev/null +++ b/mk_swap.sh @@ -0,0 +1,102 @@ +#!/bin/bash + +#################################################################### +#### Make a Swap script - Just set the size and the script #### +#### does the rest. #### +#### #### +#### Author: Phil Connor #### +#### Contact: contact@mylinux.work #### +#### Version 2.25 #### +#### #### +#### To use this script chmod it to 755 #### +#### or simply type bash mk_swap.sh #### +#################################################################### + +######################## +#### User Variables #### +######################## +swpsize=4 # set the size of swapfile needed in gigabytes + +########################## +#### System Variables #### +########################## +swpneed=$((swpsize * 1024)) # total the swap needs to be in mb's +dir=$(ls -la --block-size=M /) # / part dir file list +swpexist=$(echo "$dir" | grep -i swap | awk '{ print $5 }' | tr -d 'M"') # does the swap file already exist? +swpname=$(echo "$dir" | grep -i swap | awk '{ print $9 }') # If it already exists what is the name of the swap file +swppres=$(free -m | sed -n '3 p' | awk '{ print $2 }') # If it exists and is present what size is it + +######################################################################## +#### Check If the swap file already exist and if it's large enough? #### +######################################################################## +if (( swpneed < swpexist )) || (( swpneed < swppres )); then + echo -e '\e[01;37m =======================================================================' + echo -e '\e[01;32m =====================================================================' + echo -e '\e[01;32m ==== \e[01;37m A Large Enough Swapfile was Found! No Changes Needed... \e[01;32m ====' + echo -e '\e[01;32m =====================================================================' + echo -e '\e[01;37m =======================================================================' +elif (( swpneed > swpexist )) || (( swpneed > swppres )); then + echo -e '\e[01;37m ==================================================================================' + echo -e '\e[01;31m ================================================================================' + echo -e '\e[01;31m ==== \e[01;37m A Large Enough Swapfile was not found! Creating Larger SwapFile... \e[01;31m ====' + echo -e '\e[01;31m ================================================================================' + echo -e '\e[01;37m ==================================================================================' + + ####################################################### + #### Turn off existing swap if needing replacement #### + ####################################################### + if echo "$dir" | grep -i swap; then + swapoff /"${swpname}" + rm -f /"$swpname" + fi + + ############################################ + #### Create the requested size swapfile #### + ############################################ + fallocate -l ${swpsize}g /.SwapFile + + ################################################# + #### Fallocate does not work on some systems #### + ################################################# + # dd if=/dev/zero of=/.SwapFile count=${swpsize} bs=1MiB + + ################################################ + #### Configure and enable the new swap file #### + ################################################ + chmod 600 /.SwapFile + mkswap /.SwapFile + swapon /.SwapFile + + ########################################### + #### Check to make sure swap is active #### + ########################################### + echo -e '\e[01;37m =================================================================================' + echo -e '\e[01;32m ===============================================================================' + echo -e '\e[01;32m ==== \e[01;37m Checking whether the swap space was mounted and is active or not! \e[01;32m ====' + echo -e '\e[01;32m ===============================================================================' + echo -e '\e[01;37m =================================================================================' + R=$(swapon -s) + if [ -n "$R" ]; then + echo -e '\e[01;32m ============' + echo -e '\e[01;32m ============' + echo -e '\e[01;32m ==============================================================================' + echo -e "\e[01;37m$R" + echo -e '\e[01;32m ==============================================================================' + echo -e '\e[01;37m ================================================================================' + else + echo -e '\e[01;31m ============' + echo -e '\e[01;31m ============' + echo -e '\e[01;31m ============================================================================' + echo -e "\e[01;37m ==== Something Went Wrong no Swap was Loaded ====" + echo -e '\e[01;31m ============================================================================' + echo -e '\e[01;37m ==============================================================================' + fi + + ###################################################################### + #### Check to see if the created swap is listed in the fstab file #### + ###################################################################### + if ! grep -q "SwapFile" /etc/fstab; then + echo "/.SwapFile swap swap defaults 0 0" >> /etc/fstab + fi +fi + \ No newline at end of file diff --git a/motd.sh b/motd.sh new file mode 100644 index 0000000..66366c3 --- /dev/null +++ b/motd.sh @@ -0,0 +1,416 @@ +#! /bin/bash + +########################################################################## +## My spin on the MOTD ## +## version 4.2.3-71423 ## +## ## +## Copy this script to the /usr/local/bin directory and name it motd ## +## ## +## chmod 755 /usr/local/bin/motd and run it "motd" and it will make ## +## the the changes automatically and install the pkgs required ## +## to run at each login ## +## ## +## Questions or Comments: pconnor@ara.com ## +## ## +## TODO: add config file for some settings ## +########################################################################## + +if [ "$(command -v lsb_release)" ]; then + OS=$(lsb_release -i | awk '{print $3}') + OSVER=$(lsb_release -r | awk '{print $2}') + CODENAME=$(lsb_release -c | awk '{print $2}' | tr '[:upper:]' '[:lower:]') +else + OS=$(grep PRETTY_NAME /etc/os-release | sed 's/PRETTY_NAME=//g' | tr -d '="' | awk '{print $1}') + OSVER=$(grep VERSION_ID /etc/os-release | sed 's/VERSION_ID=//g' | tr -d '="') + if ! grep CODENAME /etc/os-release; then + CODENAME=$(cat < /etc/system-release | awk '{print $5}' | tr -d '("' | tr -d ')"') + else + CODENAME=$(grep VERSION_CODENAME /etc/os-release | sed 's/VERSION_CODENAME=//g' | tr -d '="' | awk -F. '{print $1}') + fi +fi + +########################################################### +#### Detect Package Manger from OS and OSVer Variables #### +########################################################### +if [ "${OS}" = Amazon ]; then + PAKMGR="yum -y" +elif [ "${OS}" = Red ] || [ "${OS}" = Rocky ]; then + if [ "${OSVER}" = 7 ]; then + PAKMGR="yum -y" + else + PAKMGR="dnf -y" + fi +elif [ "${OS}" = Debian ] || [ "${OS}" = Ubuntu ]; then + PAKMGR="apt -y" +fi + +############################## +#### Terminal Setup Start #### +############################## +export TERM=xterm-256color +tput rmam + +###################### +#### Script Setup #### +###################### +if ! grep -q motd /etc/profile; then + echo '/usr/local/bin/motd' >> /etc/profile +fi + +if [ ! -f "/etc/profile.d/colorprompt.sh" ]; then + # shellcheck disable=SC2016,SC2028 + { + echo '#########################################################################' + echo '#### This script is to setup and color the system prompt and can ####' + echo '#### be removed by a chmod 000 or deleting the file. Questions or ####' + echo '#### changes please contact Phil Connor pconnor@ara.com ####' + echo '#########################################################################' + echo '# UID 0 is the root user' + echo 'if [[ $UID == 0 ]];then' + echo ' # prompt for root user' + echo " PS1='\t [\[\033[01;31m\]\u\[\033[0m\]@\h: \[\033[01;34m\]\W\[\033[0m\]]# '" + echo 'else' + echo ' # prompt for all logged in users' + echo " PS1='[\[\033[38;5;221m\]\u\[\033[0m\]@\h: \[\033[01;34m\]\W\[\033[0m\]]% '" + echo 'fi' + } > /etc/profile.d/colorprompt.sh +fi + +if [[ "${OS}" = Debian || "${OS}" = Ubuntu ]]; then + if ! grep -q colorprompt.sh ~/.bashrc; then + echo 'source /etc/profile.d/colorprompt.sh' >> ~/.bashrc + fi +fi + +if [ ! -f "/etc/banner" ]; then + echo " + + ------------------------------------------------------------------------------ +(########################## **** WARNING! **** ############################) +#) (# +(# This system is the property of Linda's.Work Servers, and is to be #) +#) used in accordance with applicable LWS Policies. Unauthorized access or (# +(# activity is a violation of LWS Policies and may be a violation of law. #) +#) Use of this system constitutes consent to monitoring for unauthorized (# +(# use, in accordance with LWS Policies, local laws, and regulations. #) +#) Unauthorized use may result in penalties including, but not limited to, (# +(# reprimand, dismissal, financial penalties, and legal action. #) +#) (# +(##############################################################################) + ------------------------------------------------------------------------------ + + " > /etc/banner +fi + +if [ ! "$(command -v figlet)" ]; then + if [ "${OS}" = Debian ] || [ "${OS}" = Ubuntu ]; then + $PAKMGR update + $PAKMGR install figlet + elif [ "${OS}" = Red ] || [ "${OS}" = Rocky ]; then + $PAKMGR install epel-release + $PAKMGR install figlet + else + $PAKMGR install figlet + fi +fi + +if [ ! "$(command -v gem)" ]; then + $PAKMGR install gem +fi + +if [ ! "$(command -v lolcat)" ]; then + if [ "${OS}" = Debian ]; then + gem install lolcat + $PAKMGR update + $PAKMGR install lolcat + elif [ "${OS}" = Ubuntu ]; then + $PAKMGR update + $PAKMGR install lolcat + else + gem install lolcat + chmod 755 /usr/local/bin/lolcat + fi +fi + +# ------- TODO START -------- # +############################### +#### Script directory path #### +############################### +if [ -n "${BASH_SOURCE[0]}" ]; then + DIR=$(dirname "${BASH_SOURCE[0]}") +elif [ -n "${0}" ]; then + DIR=$(dirname "$(readlink -f "$0")") +fi + +########################################## +#### Configuration file and fallbacks #### +########################################## +CONFIG_FILE="${DIR}/motd.conf" +# shellcheck source=/dev/null +if test -f "${CONFIG_FILE}"; then + . "${DIR}/motd.conf" +fi + +if [ -z ${DATE_FORMAT+x} ]; then + DATE_FORMAT="%x %X" +fi +# ------- TODO END ------- # + +######################## +### Banner Functions ### +######################## +function banner() { + lolcat -f '/etc/banner' +} + +function hostn() { + hname=$(hostname -s) + figlet -f slant -c "$hname" | lolcat -f +} + +function logo() { + figlet -cf mini A Linda\'s Work Server | lolcat -f +} + +################ +#### Colors #### +################ +BW="\033[38;5;15m" # Bold White +CD="\033[0m" # Default +CRB="\033[1;31m" # Red bold +CG="\033[0;32m" # Green +CYB="\033[1;33m" # Yellow bold +# CYL="\033[3;33m" # Yellow light +CBB="\033[1;34m" # Blue bold +# CML="\033[3;35m" # Magenta light +# CCL="\033[3;36m" # Cyan light +NC="\033[00m" + +############################### +#### OS - (System Section) #### +############################### +DATE=$(date +"${DATE_FORMAT}") +DISTRIBUTION_NAME=$OS +DISTRIBUTION_VERSION=$OSVER +DISTRIBUTION_CODENAME=$CODENAME +UPTIME=$(uptime | awk '{print $3 " " $4}' | sed s'/.$//') +USER_COUNT=$(users | wc -w) +PROCESSES_RUNNING=$(ps aux | wc -l) + +if [ -z ${SYSTEM_NAME+x} ]; then + SYSTEM_NAME=$(hostname) +else + SYSTEM_NAME+=" ($(hostname))" +fi + +if [ "$(command -v timedatectl)" ]; then + TIMEZONE=$(timedatectl | grep "Time" | awk '{print $3" "$4" UTC"$5}') +else + TIMEZONE=$(date +"%Z %z") +fi + +##################### +#### Time of Day #### +##################### +HOUR=$(date +"%H") +if [ "$HOUR" -lt 12 ] && [ "$HOUR" -ge 0 ]; then + TIME="Morning User" +elif [ "$HOUR" -lt 17 ] && [ "$HOUR" -ge 12 ]; then + TIME="Afternoon User" +else + TIME="Evening User" +fi + +############################### +#### CPU - (Usage Section) #### +############################### +CPU_MODEL=$(grep -m 1 "model name" < /proc/cpuinfo | awk '{a="";for (i=4;i<=NF;i++){a=a$i" "}print a}') +CPU_LOAD=$(awk '{print $1*100}'< /proc/loadavg) +CPU_LOAD_AVG=$(awk '{print $1" "$2" "$3}'< /proc/loadavg) +CPU_CORES=$(nproc) +CPU_USAGE=$((CPU_LOAD / CPU_CORES)) +CPU_SPEED=$(lscpu | grep -m 1 "MHz" | awk '{for(i=NF;i>=1;i--) printf "%s ", $i;print ""}' | awk '{print $1}' | cut -f1 -d".") + +################################## +#### Memory - (Usage Section) #### +################################## +MEMORY_TOTAL=$(free -m | grep "Mem" | awk '{print $2}') +MEMORY_USAGE=$(free -m | grep "Mem" | awk '{print $3}') +MEMORY_USAGE_PERCENT=$(( MEMORY_USAGE * 100 / MEMORY_TOTAL )) + +################################ +#### Swap - (Usage Section) #### +################################ +SWAP_TOTAL=$(free -m | grep "Swap" | awk '{print $2}') +SWAP_USAGE=$(free -m | grep "Swap" | awk '{print $3}') +# SWAP space is optional, so it needs to be checked if it exist. +# shellcheck disable=2140 +if [[ "${SWAP_TOTAL}" -gt 0 ]]; then + SWAP_USAGE_PERCENT=$(( SWAP_USAGE * 100 / SWAP_TOTAL )) +else + SWAP_USAGE_PERCENT='-' +fi + +################################ +#### Disk - (Space Section) #### +################################ +function drive_space_used() { + { + W="\e[0;39m" + G="\e[1;32m" + R="\e[1;31m" + Y="\e[1;33m" + dim="\e[2m" + undim="\e[0m" + max_usage=90 + bar_width=26 + medium_usage=70 + mapfile -t dfs < <(df -H -x zfs -x squashfs -x tmpfs -x devtmpfs -x overlay --output=target,pcent,size | tail -n+2) + + for line in "${dfs[@]}" + do + usage=$(echo "$line" | awk '{print $2}' | sed 's/%//') + used_width=$((( usage * bar_width) / 100 )) + + if [ "${usage}" -ge "${max_usage}" ]; then + color=$R + elif [ "${usage}" -ge "${medium_usage}" ]; then + color=$Y + else + color=$G + fi + + bar="[${color}" + for (( i = 0; i < used_width; i++ )) + do + bar+="=" + done + + bar+="${W}${dim}" + for (( i = used_width; i < bar_width; i++)) + do + bar+="·" + done + + bar+="${undim}]" + echo "${line}" | awk '{ printf("%-16s%+3s used out of %+4s", $1, $2, $3); }' | sed -e 's/^/ /' | lolcat -f + echo -e "${bar}" | sed -e 's/^/ /' + done + } +} + +####################### +#### Network Block #### +####################### +if [ "$(command -v ip)" ]; then + mapfile -t INTERFACES < <(ip -o link show | awk -F': ' '{print $2}' | grep -v -E "lo|veth") + # IP V4 + for INTERFACE in "${INTERFACES[@]}" + do + if [[ "${INTERFACE}" != "${INTERFACES[0]}" ]] ; then + IP_V4="${IP_V4}\n ${CG}" + fi + + mapfile -t IPS < <(ip addr show "${INTERFACE}" | grep -oP '(?<=inet\s)\d+(\.\d+){3}') + + INTERFACE_IPS="" + for IP in "${IPS[@]}" + do + INTERFACE_IPS="${INTERFACE_IPS} ${IP}" + done + + IP_V4="${IP_V4}${INTERFACE}${INTERFACE_IPS}" + done + + # IP V6 + for INTERFACE in "${INTERFACES[@]}" + do + if [[ "${INTERFACE}" != "${INTERFACES[0]}" ]] ; then + IP_V6="${IP_V6}\n ${CG}" + fi + + mapfile -t IPS < <(ip addr show "${INTERFACE}" | grep -oP '(?<=inet6\s)\w+(:?:\w+){4}') + + INTERFACE_IPS="" + for IP in "${IPS[@]}" + do + INTERFACE_IPS="${INTERFACE_IPS} ${IP}" + done + + IP_V6="${IP_V6}${INTERFACE}${INTERFACE_IPS}" + done +else + IP1=$(hostname -I | awk '{print $1}') + IP2=$(hostname -I | awk '{print $2}') + IP3=$(hostname -I | awk '{print $3}') + + if [[ $IP1 =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then + IP1R="0" + else + IP1R="1" + fi + if [[ $IP2 =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then + IP2R="1" + IP2PIP="1" + else + IP2R="0" + fi + if [[ $IP3 =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then + IP3R="1" + else + IP3R="0" + fi +fi + +########################## +### Host Display Block ### +########################## +banner +hostn + +printf "\n" +printf " %b%b\n\n" "${CYB}" "${SYSTEM_NAME}${NC}" +printf " %bSYSTEM %b\n" "${CRB}" "${CD}" +echo '' +echo -e "${CD} ➤ ${CBB}Distribution ${CG} ${DISTRIBUTION_NAME} ${DISTRIBUTION_VERSION} (${DISTRIBUTION_CODENAME})" | lolcat -f +echo -e "${CD} ➤ ${CBB}CPU ${CG} ${CPU_MODEL}x ${CPU_CORES} cores" | lolcat -f +echo -e "${CD} ➤ ${CBB}Timezone ${CG} ${TIMEZONE}" | lolcat -f +echo -e "${CD} ➤ ${CBB}Date ${CG} ${DATE}" | lolcat -f +echo -e "${CD} ➤ ${CBB}Uptime ${CG} ${UPTIME}" | lolcat -f +echo -e "${CD} ➤ ${CBB}Users ${CG} ${USER_COUNT} Currently Logged in" | lolcat -f +echo '' +printf " %bUSAGE %b\n" "${CRB}" "${CD}" +echo '' +echo -e "${CD} ➤ ${CBB}CPU ${BW} ${CPU_USAGE}% ${CG}(${CPU_LOAD_AVG}) @ ${CPU_SPEED} MHz" | lolcat -f +echo -e "${CD} ➤ ${CBB}Memory ${CG} ${MEMORY_USAGE_PERCENT}% (${MEMORY_USAGE} MB of ${MEMORY_TOTAL} MB)" | lolcat -f +echo -e "${CD} ➤ ${CBB}Swap ${CG} ${SWAP_USAGE_PERCENT}% (${SWAP_USAGE} MB of ${SWAP_TOTAL} MB)" | lolcat -f +echo -e "${CD} ➤ ${CBB}Processes ${CG} ${PROCESSES_RUNNING} (running)" | lolcat -f +echo '' +printf " %bSPACE %b\n" "${CRB}" "${CD}" +echo '' +printf "${CD} ➤ ${CBB}Drive Usage ${CG}%b\n" +drive_space_used +echo '' +printf " %bNETWORK %b\n" "${CRB}" "${CD}" +echo '' +if [ "$IP1R" != 1 ]; then + printf "${CD} ➤ ${CBB}IPv4 ${CG}%b\n" "${IP_V4}""${IP1}" | lolcat -f +fi +if [ "$IP2R" != 1 ]; then + printf "${CD} ➤ ${CBB}IPv6 ${CG}%b\n" "${IP_V6}""${IP2}" | lolcat -f +fi +if [ "$IP2PIP" == 1 ]; then + printf "${CD} ➤ ${CBB}Private IP ${CG}%b\n" "${IP2}" | lolcat -f +elif [ "$IP3R" == 1 ]; then + printf "${CD} ➤ ${CBB}Private IP ${CG}%b\n" "${IP3}" | lolcat -f +fi +printf " %b" "${CD}" +printf "\n" + +logo +echo -e "${BW}Good $TIME ${CYB}$USER${NC}" + +###################### +### Terminal Reset ### +###################### +tput smam \ No newline at end of file diff --git a/networktuning.sh b/networktuning.sh new file mode 100644 index 0000000..0f9b234 --- /dev/null +++ b/networktuning.sh @@ -0,0 +1,270 @@ +#!/bin/bash + +###################################################################################### +#### Version 1.02 #### +#### For questions or comments contact@mylinux.work #### +#### Author : Phil Connor #### +#### #### +#### Notes : #### +#### This script is a simple "helper" to configure your sysctl.conf on linux #### +#### servers. There is no silver bullet. Don't expect the perfect setup, #### +#### review comments and adapt the parameters to your application usage. #### +#### #### +#### Use this script at your OWN risk. There is no guarantee whatsoever. #### +#### #### +#### Usage "tuning.sh" or "tuning.sh ssd" if you are running on ssd'd #### +###################################################################################### + +########################## +#### System Variables #### +########################## +host=$(hostname) +if [ "$(command -v lsb_release)" ]; then + os=$(lsb_release -i | awk '{print $3}' | tr '[:upper:]' '[:lower:]') + osv=$(lsb_release -r | awk '{print $2}' | awk -F. '{print $1}') +else + os=$(grep PRETTY_NAME /etc/os-release | sed 's/PRETTY_NAME=//g' | tr -d '="' | awk '{print $1}' | tr '[:upper:]' '[:lower:]') + osv=$(grep VERSION_ID /etc/os-release | sed 's/VERSION_ID=//g' | tr -d '="' | awk -F. '{print $1}') +fi +sfile=/etc/sysctl.conf + +################################## +#### Detect OS and OS Version #### +################################## +if [[ ${os} = alma || ${os} = amazon || ${os} = centos || ${os} = red || ${os} = rocky || ${os} = oracle ]]; then + if [ "${osv}" = 7 ]; then + PAKMGR="yum -y" + else + PAKMGR="dnf -y" + fi +elif [ "${os}" = ubuntu ]; then + PAKMGR="apt -y" +fi + +########################################## +#### Check to see if bc is Instaslled #### +########################################## +if ! command -v bc &> /dev/null; then + ${PAKMGR} install bc +fi + +########################## +#### Sysctl Variables #### +########################## +mem_bytes=$(awk '/MemTotal:/ { printf "%0.f",$2 * 1024}' /proc/meminfo) +shmmax=$(echo "$mem_bytes * 0.90" | bc | cut -f 1 -d '.') +shmall=$(("$mem_bytes" / $(getconf PAGE_SIZE))) +max_orphan=$(echo "$mem_bytes * 0.10 / 65536" | bc | cut -f 1 -d '.') +file_max=$(echo "$mem_bytes / 4194304 * 256" | bc | cut -f 1 -d '.') +max_tw=$((file_max * 2)) +min_free=$(echo "($mem_bytes / 1024) * 0.01" | bc | cut -f 1 -d '.') + +############################ +#### Update Sysctl.conf #### +############################ +echo "#######################################" +echo "#### Updating sysctl for $host" +echo "#######################################" + +cp -a -- "$sfile" "$sfile-$(date +"%m-%d-%y-%r")" + +###################################### +#### Check for ssd on commandline #### +###################################### +if [ "$1" != "ssd" ]; then + vm_dirty_bg_ratio=5 + vm_dirty_ratio=15 +else + # This setup is generally ok for ssd and highmem servers + vm_dirty_bg_ratio=3 + vm_dirty_ratio=5 +fi + +>>$sfile cat << EOF + +############################ +#### Performance Tuning #### +############################ + +# Disable syncookies +# (syncookies are not RFC compliant and can use too many resources) +net.ipv4.tcp_syncookies = 0 + +# Basic TCP tuning +net.ipv4.tcp_keepalive_time = 600 +net.ipv4.tcp_synack_retries = 3 +net.ipv4.tcp_syn_retries = 3 + +# RFC1337 +net.ipv4.tcp_rfc1337 = 1 + +# Defines the local port range that is used by TCP and UDP +# to choose the local port +net.ipv4.ip_local_port_range = 1024 65535 + +# Log Martian Packets with impossible addresses +net.ipv4.conf.all.log_martians = 1 +net.ipv4.conf.default.log_martians = 1 + +EOF + +if [ -f /proc/sys/net/ipv4/inet_peer_gc_mintime ]; then + { + echo '# Minimum interval between garbage collection passes This interval is' + echo '# in effect under high memory pressure on the pool' + echo 'net.ipv4.inet_peer_gc_mintime = 5' + echo '' + } >> $sfile +fi + +>> $sfile cat << EOF +# Disable Explicit Congestion Notification in TCP +net.ipv4.tcp_ecn = 0 + +# Enable window scaling as defined in RFC1323 +net.ipv4.tcp_window_scaling = 1 + +# Enable timestamps (RFC1323) +net.ipv4.tcp_timestamps = 1 + +# Enable select acknowledgments +net.ipv4.tcp_sack = 1 + +# Enable FACK congestion avoidance and fast restransmission +net.ipv4.tcp_fack = 1 + +# Allows TCP to send "duplicate" SACKs +net.ipv4.tcp_dsack = 1 + +# Controls IP packet forwarding for router advertisements +net.ipv4.ip_forward = 1 +net.ipv6.conf.all.forwarding=1 + +# Strict reverse path filtering +net.ipv4.conf.default.rp_filter = 1 +net.ipv4.conf.all.rp_filter=1 + +EOF + +if [ -f /proc/sys/net/ipv4/tcp_tw_recycle ]; then + { + echo '# Enable fast recycling TIME-WAIT sockets' + echo 'net.ipv4.tcp_tw_recycle = 1' + echo '' + } >> $sfile +fi + +>>$sfile cat << EOF +# Max number of remembered connection requests +# TCP_SYNQ_HSIZE*16<=tcp_max_syn_backlog +# NOTE: Setting this too low may impact IP6 Sessions +net.ipv4.tcp_max_syn_backlog = 20000 + +# tells the kernel how many TCP sockets that are +# not attached to any user file handle to maintain +net.ipv4.tcp_max_orphans = $max_orphan + +# How may times to retry before killing TCP connection, +# closed by the side +net.ipv4.tcp_orphan_retries = 1 + +# how long to keep sockets in the state FIN-WAIT-2 +# if we were the one closing the socket +net.ipv4.tcp_fin_timeout = 20 + +# maximum number of sockets in TIME-WAIT to be held simultaneously +net.ipv4.tcp_max_tw_buckets = $max_tw + +# don't cache ssthresh from previous connection +net.ipv4.tcp_no_metrics_save = 1 +net.ipv4.tcp_moderate_rcvbuf = 1 + +# increase Linux autotuning TCP buffer limits +net.ipv4.tcp_rmem = 4096 87380 16777216 +net.ipv4.tcp_wmem = 4096 65536 16777216 + +# increase TCP max buffer size +net.core.rmem_max = 16777216 +net.core.wmem_max = 16777216 + +net.core.netdev_max_backlog = 2500 +net.core.somaxconn = 65000 + +vm.swappiness = 0 + +# You can monitor the kernel behavior with regard to the dirty +# pages by using grep -A 1 dirty /proc/vmstat +vm.dirty_background_ratio = $vm_dirty_bg_ratio +vm.dirty_ratio = $vm_dirty_ratio + +# required free memory (set to 1% of physical ram) +vm.min_free_kbytes = $min_free + +# system open file limit +fs.file-max = $file_max + +# Core dump suidsafe +fs.suid_dumpable = 2 + +#( 3 4 1 3 for most webbased applications ) +kernel.printk = 4 4 1 7 +kernel.core_uses_pid = 1 +kernel.sysrq = 0 +kernel.msgmax = 65536 +kernel.msgmnb = 65536 + +# Maximum shared segment size in bytes +kernel.shmmax = $shmmax + +# Maximum number of shared memory segments in pages +kernel.shmall = $shmall + +########################### +#### Security Settings #### +########################### + +# Protect against worms and other automated attacks +EOF + +if [ -f /proc/sys/kernel/exec-shield ]; then + echo 'kernel.exec-shield = 1' >> $sfile +fi + +>>$sfile cat << EOF +kernel.randomize_va_space = 1 + +# Don't accept ICMP redirects +net.ipv4.conf.all.accept_redirects = 0 +net.ipv4.conf.default.accept_redirects = 0 +net.ipv6.conf.all.accept_redirects = 0 +net.ipv6.conf.default.accept_redirects = 0 + +# Don't send ICMP redirects (I'm not a router!) +net.ipv4.conf.all.send_redirects = 0 +net.ipv4.conf.default.accept_redirects = 0 + +# Don't accept IP source route packets (I'm not a router) +net.ipv4.conf.all.accept_source_route = 0 +net.ipv4.conf.default.accept_source_route = 0 +net.ipv6.conf.all.accept_source_route = 0 + +# Ignoring ICMP broadcasts and ignore bogus responses +net.ipv4.icmp_echo_ignore_broadcasts = 1 +net.ipv4.icmp_ignore_bogus_error_responses = 1 + +# Don’t accept routing preferences +net.ipv6.conf.default.accept_ra_rtr_pref = 0 +net.ipv6.conf.all.accept_ra_rtr_pref = 0 + +# Don’t try to learn prefix information +net.ipv6.conf.default.accept_ra_pinfo = 0 +net.ipv6.conf.all.accept_ra_pinfo = 0 + +# Don’t accept hop limits +net.ipv6.conf.default.accept_ra_defrtr = 0 +net.ipv6.conf.all.accept_ra_defrtr = 0 + +EOF + +sysctl -p +exit $? \ No newline at end of file diff --git a/postfix_sendonly.sh b/postfix_sendonly.sh new file mode 100644 index 0000000..4173f2d --- /dev/null +++ b/postfix_sendonly.sh @@ -0,0 +1,106 @@ +#! /bin/bash + +############################################################# +#### PostFix (Sendonly) install Script for Oracle Linux, #### +#### Centos/Redhat and Ubuntu Servers. #### +#### #### +#### Author: Phil Connor 02/10/2021 #### +#### Contact: contact@mylinux.work #### +#### Version 1.20-12.13.22 #### +#### #### +#### To use this script chmod it to 755 #### +#### or simply type bash #### +############################################################# + +############################# +#### User Configurations #### +############################# +DomainName=myserver.mydomain.com # <-- Name of the server you are configuring this on +EnableForw=yes # <-- Do you want the server to forward the mail (yes/no) +ForwardMail=my_email@mydomain.com # <-- What is the email you want to forward to? + +########################## +#### System Variables #### +########################## +macnf=/etc/postfix/main.cf +sslcerts=/etc/letsencrypt/live/$DomainName + +if [ "$(command -v lsb_release)" ]; then + OS=$(lsb_release -i | awk '{print $3}' | tr '[:upper:]' '[:lower:]') + OSVER=$(lsb_release -r | awk '{print $2}' | awk -F. '{print $1}') +else + OS=$(grep PRETTY_NAME /etc/os-release | sed 's/PRETTY_NAME=//g' | tr -d '="' | awk '{print $1}' | tr '[:upper:]' '[:lower:]') + OSVER=$(grep VERSION_ID /etc/os-release | sed 's/VERSION_ID=//g' | tr -d '="' | awk -F. '{print $1}') +fi + +########################################################### +#### Detect Package Manger from OS and OSVer Variables #### +########################################################### +if [[ ${OS} = alma || ${OS} = amazon || ${OS} = centos || ${OS} = red || ${OS} = rocky || ${OS} = oracle ]]; then + if [[ "${OSVER}" = 7 || "${OSVER}" = 7 ]]; then + PAKMGR="yum -y" + else + PAKMGR="dnf -y" + fi +elif [[ "${OS}" = ubuntu || "${OS}" = debian ]]; then + PAKMGR="apt -y" +fi + +######################################################## +#### Install PostFix, Configure and Start/Enable it #### +######################################################## +if [[ "${OS}" = ubuntu || "${OS}" = debian ]]; then + echo "postfix postfix/mailname string $DomainName" | debconf-set-selections + echo "postfix postfix/main_mailer_type string 'Internet Site'" | debconf-set-selections + DEBIAN_FRONTEND=noninteractive $PAKMGR install postfix bsd-mailx +else + $PAKMGR install postfix mailx +fi + +sed -i "s/inet_interfaces = all/inet_interfaces = loopback-only/g" $macnf +postconf -e "myhostname = $DomainName" +sed -i "s/#myorigin = \$myhostname/myorigin = \$myhostname/g" $macnf +sed -i "s/mydestination = \$myhostname, domain-name.com, localhost.\$mydomain, localhost/mydestination = \$myhostname, $DomainName, localhost.\$mydomain, localhost/g" $macnf + +systemctl enable --now postfix + +hostnamectl set-hostname $DomainName +echo "Mail delivery test" | mail -s "[Server] New e-mail" $ForwardMail + +if [ $EnableForw = yes ]; then + sed -i "s/root: /root: $ForwardMail/g" + newaliases + systemctl restart postfix +fi + +######################## +#### Add Encryption #### +######################## +function encrypt() { + { + $PAKMGR install certbot + + if [ "$(command -v ufw)" ]; then + ufw allow http + elif [ "$(command -v firewall-cmd)" ]; then + firewall-cmd --zone=public --add-port=80/tcp + firewall-cmd --zone=public --permanent --add-port=80/tcp + elif [ "$(command -v iptables)" ]; then + iptables -I INPUT -p tcp -m tcp –dport 80 -j ACCEPT + service iptables save + ip6tables -I INPUT -p tcp -m tcp –dport 80 -j ACCEPT + service ip6tables save + systemctl restart iptables ip6tables + fi + + certbot certonly --standalone --rsa-key-size 4096 --agree-tos --preferred-challenges http -d $DomainName + + #### TLS parameters #### + sed -i "s/smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem/smtpd_tls_cert_file=$sslcerts/fullchain.pem/g" $macnf + sed -1 "s/smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key/smtpd_tls_key_file=$sslcerts/privkey.pem/g" $macnf + + systemctl restart postfix + + echo "This is a test of an encrypted email" | mail -s "This is Just a Test" $ForwardMail + } +} \ No newline at end of file