#!/usr/bin/bash ####################################################################### #Script Name: vm_setup_deb.sh #Version: 1.6 #Description: Wrapper for installing Da server #AbuseIPDB #Last Modify Date: 03102021 #Author:Brent Dacus #Email:brent[at]thedacus[dot]net ####################################################################### # Banner # ####################################################################### export COLUMNS=100 vmsetup_banner() { cat <<"eot" ad88888ba d8" "8b ,d Dd ,VM Y8, 88 HH 8b ,dPj ,dYa. `Y8aaaaa, ,adPPYba, MM88MMM 88 88 8b,dPPYba, a8 44 8P' V 8b `"""""8b, a8P_____88 88 88 88 88P' "8a 8b 55 88 d8 ` 8b 8PP""""""" 88 88 88 88 d8 'Da' 88 b8 Y8a a8P "8b, ,aa 88, "8a, ,a88 88b, ,a8" V TT YM "Y88888P" `"Ybbd8"' "Y888 `"YbbdP'Y8 88`YbbdP"' 88 88 eot cat <<"eot" Author: Brent Dacus eot } ####################################################################### # Variables # ####################################################################### cur_hostname="$(hostname)" serverip="$(hostname -I | awk '{print $1}')" serverip6="$(hostname -I | awk '{print $2}')" servername="$(hostname -s)" svrdomainname="$(hostname -d)" hstdomainname=delainhosting.com cpu_cores=1 cpu_cores="$(grep >"${2}" fi if grep -q \\"${1}" "${2}"; then printf '%s exists.\n Skipping.\n' "${1}" else printf '%s does not exist\n' "$1" echo "${1}" >>"${2}" fi } doreboot() { printf "Need to reboot? (y/n)? " read -r yn yn=${yn:-n} case $yn in [Yy]*) reboot ;; [Nn]*) ;; esac } cycleswap() { printf "Cycling Swapfile.\n" swapoff -a sleep 10 swapon -a } ####################################################################### # Add Admin User # ####################################################################### addadminuser() { printf "Installing Standard packages.\n" printf "Please Wait.\n" apt-get install ${aptargs} perl wget curl nano btop htop >/dev/null bshrvals=("export EDITOR='nano'") printf 'Adding values in to %s.\n Please wait.\n' "$bshrc" for bshrval in "${bshrvals[@]}"; do if grep -q "$bshrval" ${bshrc}; then printf '%s exists.\n Skipping.\n' "$bshrval" else printf '%s does not exist\n' "$bshrval" printf '#added by DH.\n' >>${bshrc} printf '%s\n' "$bshrval" >>${bshrc} fi done if ! grep -q daconf /root/.bashrc; then printf 'Bash shell profile not set up. adding...\n' cat <<"eol" >>/root/.bashrc export EDITOR='nano' export LS_OPTIONS='--color=auto' eval "`dircolors`" alias ls='ls $LS_OPTIONS' alias ll='ls $LS_OPTIONS -l' alias l='ls $LS_OPTIONS -lA' alias rm='rm -i' alias cp='cp -i' alias mv='mv -i' alias lh='history |grep ' alias search='find / -name ' alias doserver='curl -o vm_setup_deb.sh -L https://files.delaintech.com/vm_setup_deb.sh && bash vm_setup_deb.sh' alias cycle='systemctl restart ' alias status='systemctl is-active ' eol printf "Print Profile File.\n" cat /root/.bashrc printf "Done.\n" else printf "Profile already setup. See Below.\n" cat /root/.bashrc fi } ####################################################################### # Turn on IPV6 # ####################################################################### setipv6() { printf "Do we need to turn on IPV6? REBOOT REQUIRED (y/n)? " read -r yn yn=${yn:-n} case $yn in [Yy]*) sed -i "/net.ipv6.conf.all.disable_ipv6.*/d" /etc/sysctl.conf sysctl -q -p echo 0 >/proc/sys/net/ipv6/conf/all/disable_ipv6 doreboot systemctl restart webmin ;; [Nn]*) ;; esac } ####################################################################### # Set Timezone # ####################################################################### settimezone() { printf "What TimeZone are you in? [America/Chicago]: " read -r tmzone tmzone=${tmzone:-America/Chicago} if timedatectl | grep -q "America/Chicago"; then printf "%s found\n" "$tmzone" else timedatectl set-timezone "$tmzone" timedatectl set-local-rtc 0 printf "We set timezone as:\n" timedatectl printf "Done.\n" fi } ####################################################################### # Add Hosts file # ####################################################################### creathostfile() { # does the Host already exist? if ! grep -q ${hstdomainname} /etc/hosts; then printf 'Hostfile not found. adding...\n' cat <<"eol" >>/etc/hosts 209.126.81.64 apollo.delainhosting.com apollo 209.145.52.110 athena.delainhosting.com athena 144.91.108.77 thor.delainhosting.com thor 154.12.224.183 saturn.delainhosting.com saturn eol printf "Print Host File.\n" cat /etc/hosts printf "Done.\n" else printf "Hostfile exsits.\nSee Below.\n" cat /etc/hosts fi } ####################################################################### # Set Server Hostname # ####################################################################### creathostname() { setipv6 # does the Host already exist? unset new_hostname printf "Please enter a Hostname to add: " read -r new_hostname if ! grep -q "$new_hostname" /etc/hosts; then printf 'Hostname not found. adding...\n' printf "Changing hostname %s from to %s...\n" "$cur_hostname" "$new_hostname" hostnamectl set-hostname "$new_hostname" serverip="$(hostname -I | awk '{print $1}')" serverip6="$(hostname -I | awk '{print $2}')" servername="$(hostname -s)" echo "${serverip} ${new_hostname} ${servername}" >>/etc/hosts echo "${serverip6} ${new_hostname} ${servername}" >>/etc/hosts printf "Print Host File.\n" cat /etc/hosts printf "\nDone.\n" else printf "Hostname exsits.\nAll good.\n" fi } ####################################################################### # Remove Hostnames # ####################################################################### removehosts() { printf "Here is the Host file.\n" cat /etc/hosts printf "\nWhat is the server name or ip to remove? " read -r removehosts sed -i.bkp '/'$removehosts'/d ' /etc/hosts printf "Print Host.\n" cat /etc/hosts printf "\nDone.\n" while true; do printf "Continue removing? (y/n)?" read -r yn yn=${yn:-n} case $yn in [Yy]*) removehosts break ;; [Nn]*) break ;; esac done } ####################################################################### # Add External Hosts # ####################################################################### addhosts() { # does the Host already exist? unset serverip add_hostname servername printf "Enter Hostname to add:[ IP FDQN Hostname ]: " read -r serverip add_hostname servername if ! grep -q "$add_hostname" /etc/hosts; then printf 'Hostname not found. adding...\n' echo "${serverip} ${add_hostname} ${servername}" | tee -a /etc/hosts printf "Print Host File.\n" cat /etc/hosts printf "Done.\n" else printf "Hostname exsits.\nAll good.\n" fi while true; do printf "Continue adding? (y/n)?" read -r yn yn=${yn:-n} case $yn in [Yy]*) creathostentry break ;; [Nn]*) break ;; esac done } ####################################################################### # Add Swapfile # ####################################################################### creatswapfile() { printf 'Enter Swapfile size in GB: ' read -r swapsize swapsize=${swapsize:-2} printf "You choose %s GB for swap.\n" "$swapsize" # does the swap file already exist? cp /etc/fstab /etc/fstab.bak # if not then create it if ! grep -q "swap" /etc/fstab; then printf 'Swap file not found.\nCreating Swap file.\n' fallocate -l "${swapsize}"G /swapfile chmod 600 /swapfile mkswap /swapfile swapon /swapfile printf "/swapfile none swap defaults 0 0" | tee -a /etc/fstab printf "\nDone\nSwap should be active.\nIf not reboot.\n" else printf 'Swap file found.\nNo changes made.\n' fi } ####################################################################### # Update OS on Server # ####################################################################### serverupdate() { printf "Debian Cleaning and Updating.\n" apt-get ${aptargs} autoremove apt-get autoclean apt-get ${aptargs} update apt-get ${aptargs} upgrade apt-get ${aptargs} dist-upgrade printf "Done.\n" } ####################################################################### # Install Standard Packages # ####################################################################### installpreq() { #DH Added Standard packages printf "Installing Standard Server packages!\n" apt-get install ${aptargs} htop screen inotify-tools ipset pigz pbzip2 tuned rsync zip unzip rclone } ####################################################################### # Install Virtualmin # ####################################################################### installvirtualmin() { if [ ! -f "$vm" ]; then printf "No problem, let's get Virtualmin installed first...\nThis could take a minute...\nor two... or thirty...\nPlease wait ...\n" cd $vmsetupbuild || return wget https://download.virtualmin.com/virtualmin-install.sh sh virtualmin-install.sh -V else printf "Script killed, Virtualmin installed.\n" exit fi } ####################################################################### # Harden Server # ####################################################################### hardenserver() { printf "Do we need to Secure sshd? (y/n)? " read -r yn yn=${yn:-n} case $yn in [Yy]*) cursshport="$(grep -m1 -E "Port .*" /etc/ssh/sshd_config)" printf "Enter SSH port to change to: " read -r sshport sshport=${sshport:-14} printf "Set to Port: %s\n" "$sshport" printf "Securing the server, please wait...\n" sed -i -e "s/$cursshport/Port ${sshport}/g" /etc/ssh/sshd_config sed -i -e 's/.*UseDNS .*/UseDNS no/g' /etc/ssh/sshd_config sed -i -e 's/#AddressFamily any/AddressFamily inet/g' /etc/ssh/sshd_config sed -i -e 's/#LoginGraceTime 2m/LoginGraceTime 2m/g' /etc/ssh/sshd_config sed -i -e 's/#MaxAuthTries 6/MaxAuthTries 5/g' /etc/ssh/sshd_config sed -i -e 's/#MaxStartups 10:30:100/MaxStartups 10:30:100/g' /etc/ssh/sshd_config sed -i -e 's/.*PermitRootLogin yes/PermitRootLogin prohibit-password/g' /etc/ssh/sshd_config sed -i -e 's/.*PasswordAuthentication .*/PasswordAuthentication no/g' /etc/ssh/sshd_config sed -i -e 's/#ClientAliveInterval .*/ClientAliveInterval 120/g' /etc/ssh/sshd_config sed -i -e 's/#ClientAliveCountMax .*/ClientAliveCountMax 15/g' /etc/ssh/sshd_config sed -i -e 's/.*PubkeyAuthentication yes/PubkeyAuthentication yes/g' /etc/ssh/sshd_config sed -i -e 's/.*AuthorizedKeysFile .*/AuthorizedKeysFile .*/g' /etc/ssh/sshd_config systemctl restart sshd ;; [Nn]*) ;; esac if [[ $(systemctl is-active rpcbind) = active ]]; then printf "rpcbind found.\nRemoving.\n" systemctl stop rpcbind systemctl disable rpcbind printf "Removal complete.\n" else printf "rpcbind not found.\nNo changes made.\n" fi if [[ $(systemctl is-active firewalld) == "active" ]]; then printf "Firewalld found.\nRemoving.\n" systemctl disable --now firewalld apt purge -y firewalld elif [[ $(systemctl is-active nftables) == "active" ]]; then printf "NFTables found.\nAlready running.\n" else printf "NFTables not found or not running.\nInstalling NFTables.\n" apt-get ${aptargs} install -y nftables systemctl unmask --now nftables systemctl enable --now nftables printf "NFTables installation complete.\n" fi printf "Do we need to install Crowdsec? (y/n)? " read -r yn yn=${yn:-n} case $yn in [Yy]*) installcrowdsec ;; [Nn]*) ;; esac printf "Do we need to intall Maldetect? (y/n)? " read -r yn yn=${yn:-n} case $yn in [Yy]*) installmaldetect ;; [Nn]*) ;; esac } ####################################################################### # Install Firewall # ####################################################################### installfirewall() { printf "Do we need to reconfigure Firewall? (y/n)? " read -r yn yn=${yn:-n} case $yn in [Yy]*) # Remove firewalld if it is active if systemctl is-active --quiet firewalld; then printf "Firewalld found.\nRemoving.\n" systemctl disable --now firewalld apt-get purge -y firewalld fi # Install nftables if necessary if ! dpkg -s nftables >/dev/null 2>&1; then printf "NFTables not found.\nAdding.\n" apt-get ${aptargs} install -y nftables else printf "NFTables found.\n" fi printf "Checking NFTables configuration.\n" if [[ -f /etc/nftables.conf ]]; then if grep -Fqx 'include "/etc/nftables.d/*.nft"' /etc/nftables.conf; then printf 'NFTables include already exists.\nSkipping.\n' else printf 'Adding NFTables include to /etc/nftables.conf.\n' printf '\ninclude "/etc/nftables.d/*.nft"\n' >> /etc/nftables.conf printf 'NFTables include added.\n' fi else printf "ERROR: /etc/nftables.conf does not exist.\n" return 1 fi # Enable and start nftables systemctl unmask nftables systemctl enable --now nftables printf "NFTables is running.\n" printf "General install complete.\n" # -------------------------------------------------- # Add country blocking # -------------------------------------------------- printf "Adding country blocking\n" wget -rnH --cut-dirs=1 \ https://files.delaintech.com/fw/fwdloadcountry.sh \ -P /opt/ chmod +x /opt/fwdloadcountry.sh /opt/fwdloadcountry.sh # -------------------------------------------------- # Add AbuseIPDB blocking # -------------------------------------------------- printf "Adding AbuseIPDB blocking\n" wget -rnH --cut-dirs=1 \ https://files.delaintech.com/fw/fwdloadabipdb.sh \ -P /opt/ chmod +x /opt/fwdloadabipdb.sh /opt/fwdloadabipdb.sh printf "NFTables firewall configuration complete.\n" ;; [Nn]*) printf "Firewall reconfiguration skipped.\n" ;; *) printf "Invalid option.\n" ;; esac } ####################################################################### # Install crowdsec # ####################################################################### installcrowdsec() { printf "Continue with CrowdSec? (y/n)? " read -r yn yn=${yn:-n} case $yn in [Yy]*) printf "Checking if Fail2Ban is installed.\n" if dpkg-query -W -f='${Status}' fail2ban 2>/dev/null | grep -q "install ok installed"; then printf "Fail2Ban found.\nRemoving.\n" systemctl disable --now fail2ban 2>/dev/null || true apt-get purge -y fail2ban apt-get autoremove -y printf "Fail2Ban removed.\n" else printf "Fail2Ban not installed.\n" fi printf "Checking CrowdSec installation.\n" # -------------------------------------------------- # Install CrowdSec if necessary # -------------------------------------------------- if systemctl list-unit-files crowdsec.service >/dev/null 2>&1; then printf "CrowdSec already installed.\nUpdating configuration.\n" else printf "Checking if Fail2Ban is installed.\n" if dpkg-query -W -f='${Status}' fail2ban 2>/dev/null | grep -q "install ok installed"; then printf "Fail2Ban found.\nRemoving.\n" systemctl disable --now fail2ban 2>/dev/null || true apt-get purge -y fail2ban apt-get autoremove -y printf "Fail2Ban removed.\n" else printf "Fail2Ban not installed.\n" fi printf "CrowdSec not found.\nInstalling.\n" # Add CrowdSec repository curl -s https://install.crowdsec.net | sh apt-get ${aptargs} update # Install CrowdSec apt-get ${aptargs} install -y crowdsec # Install nftables firewall bouncer apt-get ${aptargs} install -y crowdsec-firewall-bouncer-nftables systemctl enable --now crowdsec systemctl enable --now crowdsec-firewall-bouncer printf "CrowdSec installation complete.\n" fi # -------------------------------------------------- # Update CrowdSec Hub # -------------------------------------------------- printf "Updating CrowdSec Hub.\n" cscli hub update # -------------------------------------------------- # Linux / SSH protection # -------------------------------------------------- printf "Installing firewall scanning protection.\n" cscli collections install crowdsecurity/iptables # -------------------------------------------------- # Apache protection # -------------------------------------------------- printf "Installing Apache Extended protection.\n" cscli collections install crowdsecurity/http-extended-context # -------------------------------------------------- # WordPress protection # -------------------------------------------------- printf "Installing WordPress protection.\n" cscli collections install crowdsecurity/wordpress # -------------------------------------------------- # HTTP CVE protection # -------------------------------------------------- printf "Installing HTTP CVE protection.\n" cscli collections install crowdsecurity/http-cve # -------------------------------------------------- # Add Virtulamin file locations # -------------------------------------------------- cat > /etc/crowdsec/acquis.d/virtualmin-apache.yaml <<'EOF' filenames: - /var/log/apache2/*error_log - /var/log/apache2/*access_log - /var/log/virtualmin/*_error_log - /var/log/virtualmin/*_access_log labels: type: apache2 source: file EOF printf "Configuring CrowdSec Postfix log acquisition.\n" cat > /etc/crowdsec/acquis.d/setup.postfix.yaml <<'EOF' journalctl_filter: - _SYSTEMD_UNIT=postfix.service labels: type: syslog source: journalctl EOF printf "Postfix log acquisition configured.\n" printf '%s\n' "Configuring CrowdSec AbuseIPDB..." mkdir -p /etc/crowdsec/notifications cat > /etc/crowdsec/notifications/abuseipdb.yaml < /etc/crowdsec/profiles.yaml <<'EOF' name: default_ip_remediation #debug: true filters: - Alert.Remediation == true && Alert.GetScope() == "Ip" decisions: - type: ban duration: 24h #duration_expr: Sprintf('%dh', (GetDecisionsCount(Alert.GetValue()) + 1) * 24) duration_expr: >- Sprintf('%dh', GetDecisionsCount(Alert.GetValue()) == 0 ? 7 * 24 : GetDecisionsCount(Alert.GetValue()) == 1 ? 30 * 24 : GetDecisionsCount(Alert.GetValue()) == 2 ? 60 * 24 : GetDecisionsCount(Alert.GetValue()) == 3 ? 90 * 24 : GetDecisionsCount(Alert.GetValue()) == 4 ? 180 * 24 : 360 * 24 ) notifications: - report_abuse_ip_db # notifications: # - slack_default # Set the webhook in /etc/crowdsec/notifications/slack.yaml before enabling this. # - splunk_default # Set the splunk url and token in /etc/crowdsec/notifications/splunk.yaml before enabling this. # - http_default # Set the required http parameters in /etc/crowdsec/notifications/http.yaml before enabling this. # - email_default # Set the required email parameters in /etc/crowdsec/notifications/email.yaml before enabling this. ## on_success: break --- name: default_range_remediation #debug: true filters: - Alert.Remediation == true && Alert.GetScope() == "Range" decisions: - type: ban duration: 24h #duration_expr: Sprintf('%dh', (GetDecisionsCount(Alert.GetValue()) + 1) * 24) duration_expr: >- Sprintf('%dh', GetDecisionsCount(Alert.GetValue()) == 0 ? 7 * 24 : GetDecisionsCount(Alert.GetValue()) == 1 ? 30 * 24 : GetDecisionsCount(Alert.GetValue()) == 2 ? 60 * 24 : GetDecisionsCount(Alert.GetValue()) == 3 ? 90 * 24 : GetDecisionsCount(Alert.GetValue()) == 4 ? 180 * 24 : 360 * 24 ) notifications: - report_abuse_ip_db # notifications: # - slack_default # Set the webhook in /etc/crowdsec/notifications/slack.yaml before enabling this. # - splunk_default # Set the splunk url and token in /etc/crowdsec/notifications/splunk.yaml before enabling this. # - http_default # Set the required http parameters in /etc/crowdsec/notifications/http.yaml before enabling this. # - email_default # Set the required email parameters in /etc/crowdsec/notifications/email.yaml before enabling this. on_success: break EOF chmod 600 /etc/crowdsec/notifications/abuseipdb.yaml printf '%s\n' "CrowdSec AbuseIPDB configuration files created." # -------------------------------------------------- # Upgrade CrowdSec configuration # -------------------------------------------------- printf "Upgrading CrowdSec Hub configuration.\n" cscli hub upgrade # -------------------------------------------------- # Restart CrowdSec # -------------------------------------------------- printf "Restarting CrowdSec.\n" systemctl restart crowdsec # -------------------------------------------------- # Restart nftables bouncer # -------------------------------------------------- printf "Restarting CrowdSec nftables bouncer.\n" systemctl restart crowdsec-firewall-bouncer # -------------------------------------------------- # Status # -------------------------------------------------- printf "\nCrowdSec status:\n" systemctl --no-pager --full status crowdsec printf "\nCrowdSec nftables bouncer status:\n" systemctl --no-pager --full status crowdsec-firewall-bouncer printf "\nCrowdSec decisions:\n" cscli decisions list printf "\nCrowdSec installation/configuration complete.\n" ;; [Nn]*) printf "CrowdSec reconfiguration skipped.\n" ;; *) printf "Invalid option.\n" ;; esac bshrvals=( "alias csban='cscli decisions list'" "alias csc='cscli collections list'" "alias cshub='cscli hub list'" "alias csmetrics='cscli metrics'" ) printf 'Adding values in to %s.\n Please wait.\n' "$bshrc" for bshrval in "${bshrvals[@]}"; do if grep -Fqx "$bshrval" "${bshrc}"; then printf '%s exists.\n Skipping.\n' "$bshrval" else printf '%s does not exist.\n' "$bshrval" printf '#added by DH.\n' >> "${bshrc}" printf '%s\n' "$bshrval" >> "${bshrc}" fi done } ####################################################################### # Install IonCube # ####################################################################### installioncube() { echo "Choose IonCube Loader version:" echo "1. PHP 7.4" echo "2. PHP 8.0" echo "3. PHP 8.1" echo "4. PHP 8.2" echo "5. PHP 8.3" echo "6. PHP 8.4" echo "7. PHP 8.5" read -p "Enter your choice (1, 2, 3, or ...): " version_choice case $version_choice in 1) PHP_VERSION="7.4" ;; 2) PHP_VERSION="8.0" ;; 3) PHP_VERSION="8.1" ;; 4) PHP_VERSION="8.2" ;; 5) PHP_VERSION="8.3" ;; 6) PHP_VERSION="8.4" ;; 7) PHP_VERSION="8.5" ;; *) echo "Invalid choice. Exiting." exit 1 ;; esac echo "Choose installation target:" echo "1. FPM only" echo "2. CLI only" echo "3. Both FPM and CLI" read -p "Enter your choice (1, 2, or 3): " target_choice case $target_choice in 1) TARGET="fpm" ;; 2) TARGET="cli" ;; 3) TARGET="both" ;; *) echo "Invalid choice. Exiting." exit 1 ;; esac cd /tmp wget "https://downloads.ioncube.com/loader_downloads/ioncube_loaders_lin_x86-64.tar.gz" tar xzf ioncube_loaders_lin_x86-64.tar.gz PHP_EXT_DIR=$(php${PHP_VERSION} -r "echo ini_get('extension_dir');") echo $PHP_EXT_DIR sudo cp "ioncube/ioncube_loader_lin_${PHP_VERSION}.so" $PHP_EXT_DIR cat >"/etc/php/${PHP_VERSION}/mods-available/ioncube.ini" < /etc/apt/sources.list.d/sury-debian-php-$(lsb_release -sc).list' && apt-get update apt-get install ${aptargs} php7.4-{bcmath,bz2,cgi,cli,fpm,igbinary,intl,imagick,pdo,pdo-mysql,gd,gmp,redis,mbstring,memcached,mysqlnd,opcache,curl,xml,zip,soap,sqlite3,imap} apt-get install ${aptargs} php8.0-{bcmath,bz2,cgi,cli,fpm,igbinary,intl,imagick,pdo,pdo-mysql,gd,gmp,redis,mbstring,memcached,mysqlnd,opcache,curl,xml,zip,soap,sqlite3,imap} apt-get install ${aptargs} php8.1-{bcmath,bz2,cgi,cli,fpm,igbinary,intl,imagick,pdo,pdo-mysql,gd,gmp,redis,mbstring,memcached,mysqlnd,opcache,curl,xml,zip,soap,sqlite3,imap} apt-get install ${aptargs} php8.2-{bcmath,bz2,cgi,cli,fpm,igbinary,intl,imagick,pdo,pdo-mysql,gd,gmp,redis,mbstring,memcached,mysqlnd,opcache,curl,xml,zip,soap,sqlite3,imap} apt-get install ${aptargs} php8.3-{bcmath,bz2,cgi,cli,fpm,igbinary,intl,imagick,pdo,pdo-mysql,gd,gmp,redis,mbstring,memcached,mysqlnd,opcache,curl,xml,zip,soap,sqlite3,imap} apt-get install ${aptargs} php8.4-{bcmath,bz2,cgi,cli,fpm,igbinary,intl,imagick,pdo,pdo-mysql,gd,gmp,redis,mbstring,memcached,mysqlnd,opcache,curl,xml,zip,soap,sqlite3,imap} apt-get install ${aptargs} php8.5-{bcmath,bz2,cgi,cli,fpm,igbinary,intl,imagick,pdo,pdo-mysql,gd,gmp,redis,mbstring,memcached,mysqlnd,curl,xml,zip,soap,sqlite3,imap} } ####################################################################### # Main Configure Section # ####################################################################### ####################################################################### # Configure httpd # ####################################################################### confapache2() { printf "Setting up Apache.\n" a2enmod http2 headers expires printf "Adding KeepAlive config in Apache2.\n" sed -i -e 's/Timeout .*/Timeout 60/g' /etc/apache2/apache2.conf sed -i -e 's/KeepAliveTimeout .*/KeepAliveTimeout 2/g' /etc/apache2/apache2.conf printf "Adding MPM event config in Apache2.\n" cat >/etc/apache2/mods-available/mpm_event.conf < StartServers 6 MinSpareThreads 32 MaxSpareThreads 128 ThreadsPerChild 64 ServerLimit 32 MaxRequestWorkers 2048 MaxConnectionsPerChild 10000 eol printf "Adding mod deflate config in Apache2.\n" cat >/etc/apache2/mods-available/deflate.conf < AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css AddOutputFilterByType DEFLATE application/x-javascript application/javascript application/ecmascript AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/xml DeflateCompressionLevel 7 DeflateMemLevel 8 DeflateWindowSize 10 eol printf "Adding HTST header config in Apache2.\n" cat >/etc/apache2/mods-available/headers.conf </etc/apache2/mods-available/expires.conf < ExpiresActive On # Images ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType image/webp "access plus 1 year" ExpiresByType image/svg+xml "access plus 1 year" ExpiresByType image/x-icon "access plus 1 year" # Video ExpiresByType video/webm "access plus 1 year" ExpiresByType video/mp4 "access plus 1 year" ExpiresByType video/mpeg "access plus 1 year" # Fonts ExpiresByType font/ttf "access plus 1 year" ExpiresByType font/otf "access plus 1 year" ExpiresByType font/woff "access plus 1 year" ExpiresByType font/woff2 "access plus 1 year" ExpiresByType application/font-woff "access plus 1 year" # CSS, JavaScript ExpiresByType text/css "access plus 1 year" ExpiresByType text/javascript "access plus 1 year" ExpiresByType application/javascript "access plus 1 year" # Others ExpiresByType application/pdf "access plus 1 year" ExpiresByType image/vnd.microsoft.icon "access plus 1 year" eol if [ ! -f "/etc/apache2/mods-enabled/expires.conf" ]; then ln -s /etc/apache2/mods-available/expires.conf /etc/apache2/mods-enabled/expires.conf else printf "Mod Expires config exsist in Apache2.\n" fi printf "Do we need to intall Multi PHP? (y/n)? " read -r yn yn=${yn:-n} case $yn in [Yy]*) installmphp ;; [Nn]*) ;; esac printf "Do we need to install IONcube Loaders? (y/n)? " read -r yn yn=${yn:-n} case $yn in [Yy]*) installioncube ;; [Nn]*) ;; esac printf "Setting up Apache2.\n" systemctl enable apache2 systemctl restart apache2 printf "Done.\n" } ####################################################################### # Configure Email # ####################################################################### confmail() { apt install ${aptargs} pflogsumm opendkim dovecot-sieve dovecot-managesieved printf "Set Root mail? (y/n)? " read -r yn yn=${yn:-n} case $yn in [Yy]*) printf "Where should root email go: " read -r rootemail rootemail=${rootemail:-tech@delainhosting.com} grep -E "$rootemail" /etc/aliases >/dev/null if [ $? -eq 0 ]; then printf "%s found already set in Aliases file.\n" "$rootemail" else echo root: ${rootemail} >>/etc/aliases newaliases printf "Email set to: " grep -E "$rootemail" /etc/aliases fi ;; [Nn]*) ;; esac virtualmin set-dkim --enable # mkdir -p /usr/local/directadmin/custombuild/custom/roundcube/ # cp /var/www/html/roundcube/config/config.inc.php ${cbblddir}/custom/roundcube/config.inc.php # sed -i -e 's|"'localhost'"|tls://%n|g' custom/roundcube/config.inc.php # sed -i -e 's/Roundcube Webmail/Delain Hosting Webmail/g' ${cbblddir}/custom/roundcube/config.inc.php # # printf "Need identity switch in Roundcube? (yn)" # read -r yn # case $yn in # [Yy]*) # printf "********Is the Firewall on Saturn open?*********\n" # sleep 10 # cd ${cbblddir}/custom || exit # cat /usr/local/directadmin/scripts/setup.txt # mysqldump -uroot -p da_roundcube >da_roundcube.bk.sql # wget -rnH http://files.delaintech.com/mysql.initial.sql -P /tmp # mysql -uroot -p da_roundcube /etc/dovecot/conf.d/10-mail.conf <<"eol" mail_driver = maildir mail_path = ~/Maildir #Standard NameSpace for Maildir namespace inbox { type = private separator = . subscriptions = yes inbox = yes } eol cat >/etc/dovecot/conf.d/15-mailboxes.conf <<"eol" #Standard Folders for Maildir. Namespace in 10-mail.conf namespace inbox { mailbox Drafts { auto = subscribe special_use = \Drafts } mailbox Junk { auto = subscribe special_use = \Junk } mailbox Archive { auto = subscribe special_use = \Archive } mailbox Trash { auto = subscribe special_use = \Trash } # For \Sent mailboxes there are two widely used names. We'll mark both of # them as \Sent and use Sent. User typically deletes one of them if duplicates are created. mailbox Sent { auto = subscribe special_use = \Sent } mailbox "Sent Messages" { special_use = \Sent } } eol cat >/etc/dovecot/conf.d/15-lda.conf <<"eol" # %d for each domain on your server postmaster_address = postmaster@%d protocol lda { # Space separated list of plugins to load (default is global mail_plugins). #mail_plugins = $mail_plugins mail_plugins = $mail_plugins sieve } eol cat >/etc/dovecot/conf.d/20-managesieve.conf <<"eol" protocols = imap pop3 sieve # Service definitions service managesieve-login { inet_listener sieve { port = 4190 } } eol cat >/etc/procmailrc <<"eol" DELIVER=/usr/lib/dovecot/deliver LOGFILE=/var/log/procmail.log TRAP=/etc/webmin/virtual-server/procmail-logger.pl :0wi VIRTUALMIN=|/etc/webmin/virtual-server/lookup-domain.pl $LOGNAME EXITCODE=$? :0 * ?/bin/test "$EXITCODE" = "73" /dev/null EXITCODE=0 :0 * ?/bin/test "$VIRTUALMIN" != "" { INCLUDERC=/etc/webmin/virtual-server/procmail/$VIRTUALMIN } ORGMAIL=$HOME/Maildir/ DEFAULT=$HOME/Maildir/ DROPPRIVS=yes :0 w | $DELIVER :0 $DEFAULT eol printf "Cycling PostFix and Dovecot.\n" systemctl restart postfix systemctl restart dovecot } ####################################################################### # Configure DNS # ####################################################################### confnamed() { sed -i -e "s|.*listen-on-v6[[:blank:]]*.{ any; };||g" /etc/bind/named.conf.options sed -i -e "s|.*allow-transfer[[:blank:]]*.{ none; };||g" /etc/bind/named.conf.options sed -i -e "s|dnssec-validation.*|dnssec-validation auto;|g" /etc/bind/named.conf.options grep -q "recursion no;" /etc/bind/named.conf.options if [ $? -ne 0 ]; then cp /etc/bind/named.conf.options /etc/bind/named.conf.options.bak sed -i.bkp '/dnssec-validation auto;/a\ listen-on { '"$serverip"'; };\ listen-on-v6 { '"$serverip6"'; };\ recursion no;\ notify yes;\ allow-transfer { 209.145.52.110; 152.53.197.244; };\ also-notify { 209.145.52.110; 152.53.197.244; };\ version "Not Found";\ ' /etc/bind/named.conf.options fi apt-get ${aptargs} remove resolvconf printf "Setup Resolver configuration.\n" cat >/etc/resolv.conf <"$myconf" do_setting "[mysqld]" "$myconf" do_setting "local-infile=0" "$myconf" do_setting "log_error=/var/log/mysql/${servername}.${svrdomainname}.err" "$myconf" do_setting "performance_schema=ON" "$myconf" do_setting "bind-address = 127.0.0.1" "$myconf" do_setting "skip-name-resolve=1" "$myconf" do_setting "max_allowed_packet=64M" "$myconf" do_setting "key_buffer_size=10MB" "$myconf" do_setting "innodb_file_per_table" "$myconf" do_setting "innodb_buffer_pool_size=${bpsize}G" "$myconf" do_setting "innodb_log_file_size=${bplsize}G" "$myconf" do_setting "max_allowed_packet=64M" "$myconf" echo ' ' >>"$myconf" do_setting "[client]" "$myconf" do_setting "socket=/run/mysqld/mysqld.sock" "$myconf" sed -i -e "s|socket = /run/mysqld/mysqld.sock.*|#socket = /run/mysqld/mysqld.sock|g" /etc/mysql/my.cnf printf "Mysql Setup Complete.\n" printf "Do we need to install Mysqltuner? (y/n)? " read -r yn yn=${yn:-n} case $yn in [Yy]*) installmysqltuner ;; [Nn]*) ;; esac do_setting "mysql soft nofile 65535" "$limitsconf" do_setting "mysql hard nofile 65535" "$limitsconf" do_setting "mysql soft core unlimited" "$limitsconf" do_setting "mysql hard core unlimited" "$limitsconf" do_setting "vm.swappiness = 1" "$sysctlconf" } ######################################################################## # Configure Performance # ####################################################################### perfmserver() { printf "Setting up Server General file Ulimits.\n" do_setting "* soft nofile 65535" "$limitsconf" do_setting "* hard nofile 65535" "$limitsconf" do_setting "root soft nofile 65535" "$limitsconf" do_setting "root hard nofile 65535" "$limitsconf" do_setting "admin soft nofile 65535" "$limitsconf" do_setting "admin hard nofile 65535" "$limitsconf" printf "Setting up Server Sysctl file.\n" do_setting "net.core.somaxconn = 65536" "$sysctlconf" do_setting "net.ipv4.conf.all.log_martians = 1" "$sysctlconf" do_setting "net.ipv4.tcp_fin_timeout = 15" "$sysctlconf" do_setting "net.ipv4.tcp_rfc1337 = 1" "$sysctlconf" do_setting "net.ipv4.tcp_synack_retries = 3" "$sysctlconf" do_setting "net.ipv4.tcp_syncookies = 0" "$sysctlconf" do_setting "net.ipv4.tcp_syn_retries = 3" "$sysctlconf" do_setting "vm.swappiness = 1" "$sysctlconf" do_setting "kernel.printk = 3 4 1 3" "$sysctlconf" printf "Complete Reboot.\n" doreboot } ####################################################################### # Check Server Satus # ####################################################################### serverstatus() { printf "Checking Virtualmin/Webmin - " systemctl is-active webmin printf "Checking Usermin - " systemctl is-active usermin printf "Checking HTTPD - " systemctl is-active apache2 printf "Checking MariaDB - " systemctl is-active mariadb printf "Checking Postfix - " systemctl is-active postfix printf "Checking Dovecot - " systemctl is-active dovecot printf "Checking FTP - " systemctl is-active proftpd printf "Checking DNS - " systemctl is-active bind9 printf "Checking SSH - " systemctl is-active sshd printf "Checking Crowdsec - " systemctl is-active crowdsec printf "Checking NFt - " systemctl is-active nftables printf "Done.\n" } ####################################################################### # Backup Server # ####################################################################### backupall() { printf 'Running Server file backup.\n' if [ -d /sys_backup ] && [ -d /admin_backups ]; then virtualmin backup-domain --dest /admin_backups/%A/full-%m-%d-%Y:%R --strftime --purge 1 --all-domains --all-features --newformat --all-virtualmin cd / tar -cvpzf /sys_backup/conf_files.tar.gz \ --exclude=/sys_backup/backup.tar.gz \ --exclude=/admin_backups \ --exclude=/root/.c* \ /etc \ /root printf "Server Backup done.\n" else mkdir /admin_backups mkdir /sys_backup chmod 755 /admin_backups chmod 755 /sys_backup virtualmin backup-domain --dest /admin_backups/%A/full-%m-%d-%Y:%R --strftime --purge 1 --all-domains --all-features --newformat --all-virtualmin cd / tar -cvpzf /sys_backup/conf_files.tar.gz \ --exclude=/sys_backup/conf_files.tar.gz \ --exclude=/admin_backups \ --exclude=/root/.c* \ /etc \ /root printf "Server Backup done.\n" fi } ####################################################################### # Main Menu of Script # ####################################################################### clear vmsetup_banner linebreak #Check that user is root. if [ "$(id -u)" = "0" ]; then printf "We are root. Continue on....\n" else printf "This script must be run as root\n" exit 1 fi #What Distro are you on? printf "Distro are you on??\n" 2>&1 OS_VER=$(sed 's/\..*//' /etc/debian_version) if [ "$OS_VER" = 12 ]; then printf "This appears to be Debian version $OS_VER which is Better!!\n" elif [ "$OS_VER" = 13 ]; then printf "This appears to be Debian version $OS_VER which is Great!!\n" else [ "$OS_VER" != 11 ] printf "System runs on unsupported Linux. Exiting...\n" exit fi if [ -n $run ]; then printf "Build Directory Created.\n" mkdir -p $vmsetupbuild fi #Menus Starts here linebreak printf "${YELLOW}" printf "Hostname: %s Server IP: %s Server IPV6: %s \n" "$serverip" "$cur_hostname" "$serverip6" linebreak printf "${YELLOW}" cat <<"eot" MAIN VIRTUALMIN SERVER SETUP MENU eot linebreak while true; do options=("Add Admin User" "Timezone" "Host file" "Hostname" "Remove hosts" "Add hosts" "Swap file" "Update server" "Install Required Packages" "Install Virtualmin" "Harden Server" "Install Firewall" "Install KernelCare" "Install MalDetect" "Install MySQLTuner" "Install Installatron" "Configure Apache" "Configure Named" "Configure Mail" "Configure Proftpd" "Configure MySql" "Performance Tweaks" "Check Server Status" "Backup Server Files" "Quit") printf "Choose an option: \n" select opt in "${options[@]}"; do case $REPLY in 1) addadminuser break ;; 2) settimezone break ;; 3) creathostfile break ;; 4) creathostname break ;; 5) removehosts break ;; 6) addhosts break ;; 7) creatswapfile break ;; 8) serverupdate break ;; 9) installpreq break ;; 10) installvirtualmin break ;; 11) hardenserver break ;; 12) installfirewall break ;; 13) installkernelcare break ;; 14) installmaldetect break ;; 15) installmysqltuner break ;; 16) installinstallatron break ;; 17) confapache2 break ;; 18) confnamed break ;; 19) confmail break ;; 20) confproftpd break ;; 21) confmysql break ;; 22) perfmserver break ;; 23) serverstatus break ;; 24) backupall break ;; 25) break 2 ;; *) echo "Invalid option. Try again." >&2 ;; esac done done if [ -n $run ]; then printf "Script exited.\nCleaning up build files, please wait...\n" cd ~ || exit rm -rf $vmsetupbuild exit fi