#!/bin/bash

#OUTPUT_FILE="audit_report_$(date +'%Y-%m-%d_%H-%M-%S').txt"
AUDIT_FILE="audit_report_$(date +'%Y-%m-%d_%H-%M-%S').txt"
# Text color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

# Text formatting codes
BOLD=$(tput bold)
NORMAL=$(tput sgr0)


print_info_green() {
    label="$1"
    value="$2"
    label_width=50 # Adjust the width as needed
    formatted_value=$(printf "%s" "$value")
    printf "${BOLD}${GREEN} %-*s ${NC} %s\n" "$label_width" "$label:" "$formatted_value"
}
print_info_green1() {
    label="$1"
    value="$2"
    label_width=50 # Adjust the width as needed
    formatted_value=$(printf "%s" "$value")
    printf "${BOLD}${YELLOW} %-*s ${NC} %s\n" "$label_width" "$label" "$formatted_value"
}

print_info_red() {
    label="$1"
    value="$2"
    label_width=50 # Adjust the width as needed
    formatted_value=$(printf "%s" "$value")
    printf "${BOLD}${GREEN} %-*s ${RED} %s\n" "$label_width" "$label:" "$formatted_value"
}
print_info_red1() {
    label="$1"
    value="$2"
    label_width=50 # Adjust the width as needed
    formatted_value=$(printf "%s" "$value")
    printf "${BOLD}${RED} %-*s ${RED} %s\n" "$label_width" "$label" "$formatted_value"
}
print_info_red_to_file() {
    label="$1"
    value="$2"
    label_width=50
    formatted_value=$(printf "%s" "$value")
	printf "${BOLD}${GREEN} %-*s ${RED} %s\n" "$label_width" "$label:" "$formatted_value"
    printf "${BOLD}${GREEN} %-*s ${RED} %s\n\n\n" "$label_width" "$label:" "$formatted_value" >> "$AUDIT_FILE"
}
print_info_red1_to_file() {
    label="$1"
    value="$2"
    label_width=50
    formatted_value=$(printf "%s" "$value")
	printf "${BOLD}${YELLOW} %-*s ${RED} %s\n" "$label_width" "$label" "$formatted_value"
    printf "${BOLD}${YELLOW} %-*s ${RED} %s\n\n\n" "$label_width" "$label" "$formatted_value" >> "$AUDIT_FILE"
}

printf "\n\n" >> "$AUDIT_FILE"
printf "\033[1m         		AUDIT REPORT SUMMARY \033[0m \n"  >> "$AUDIT_FILE"
printf "			###################### \n" >> "$AUDIT_FILE"
printf "\n\n" >> "$AUDIT_FILE"
printf "\n"
printf "		##############################################################\n"
printf "\033[1m 		Audit Report Of The Server `hostname` | `hostname -I | awk '{print $1}'` \033[0m \n"
printf "		##############################################################\n"
printf "\n"
sleep 1
printf "${BOLD}${YELLOW} Please be patient. The script may take some time to complete.  \n"
printf "\n"
sleep 1
countdown_seconds=5

while [ $countdown_seconds -gt 0 ]; do
    #clear  # Clear the terminal screen
    echo "The Scan will start within: $countdown_seconds seconds"
    sleep 1  # Wait for 1 second
    countdown_seconds=$((countdown_seconds - 1))
done
printf "\n"
printf "Time's up! The scan has started. \n"

sleep 3

printf "\n\n"
printf "		=====================\n"
printf "\033[1m 		General Information \033[0m \n"
printf "		=====================\n"
sleep 1
printf "\n\n"

# Hostname check

# Get the server's hostname
hostname=$(hostname)

#echo "Server Hostname: $hostname"


print_info_green "Server Hostname" "$hostname"

printf "\n"
sleep 1
# Get the server's IP address
ip_address=$(hostname -I | awk '{print $1}')

#echo "Server Main IP Address : $ip_address"


print_info_green "Server IP Address" "$ip_address"
sleep 1
printf "\n"
# Find the Linux flavor and version
linux_flavor=$(cat /etc/*-release | grep -E '^ID=' | sed 's/ID=//' | tr '[:upper:]' '[:lower:]')
linux_version=$(cat /etc/*-release | grep -E '^VERSION_ID=' | sed 's/VERSION_ID=//')

# Print the Linux flavor and version
#echo "The Linux Version is: $linux_flavor $linux_version"
# Print the table


print_info_green "Server OS Version" "$linux_flavor $linux_version"

printf "\n"
sleep 1
CloudlinuxOS_check=`uname -r |grep lve`

if [ -n "$CloudlinuxOS_check" ]; then



print_info_green "Is it CloudLinux Server" "Yes"
	
else


print_info_green "Is it CloudLinux Server" "No"
	
fi

printf "\n"
sleep 1

print_info_green "Server Uptime" "`uptime -p`"

printf "\n"
sleep 1
print_info_green "Server Load Average" "`uptime | awk -F 'load average: ' '{print $2}'`"

printf "\n\n"
sleep 3
printf "		==========================\n"
printf "${BOLD}${YELLOW}		HardWare Information  \n"
printf "		==========================\n"
sleep 1
printf "\n\n"

# Hard disk Information

printf "${BOLD}${YELLOW} Collecting Hard-disk Information \n"
sleep 1
printf "\n"

Hardisk_info=`lsblk -b -d -o SIZE,TYPE | awk 'BEGIN { disks=0; total_size=0 } $2 == "disk" { disks += 1; total_size += $1 } END {print "Number of hard disks: " disks}'`

Hardisk_info1=`lsblk -b -d -o SIZE,TYPE | awk 'BEGIN { total_size=0 } $2 == "disk" { total_size += $1 } END {print "Total size of hard disks: " total_size/1024/1024/1024 " GB"}'`
#echo "$Hardisk_info"

# Print the table


print_info_green "Hard disk Information" "$Hardisk_info"
sleep 1
printf "\n"
print_info_green1 "" "$Hardisk_info1"

printf "\n\n"
sleep 1
printf "${BOLD}${YELLOW} Collecting CPU Information \n"
printf "\n"
# CPU Information

cpu_info=`lscpu | grep "^Model name:" | awk '{print $3" "$4" "$5" "$6" "$7" "$8}'`
cpu_core=`lscpu | grep "^CPU(s):" | awk '{print $2}'`

#echo "Processor Information : $cpu_info & No. of CPU core : $cpu_core"
# Print the table


print_info_green "CPU Processor Information" "$cpu_info"

printf "\n"
sleep 1
print_info_green "No. of CPU core" "$cpu_core"

# Memory Information
printf "\n\n"
sleep 1
printf "${BOLD}${YELLOW} Collecting Memory Information \n"
printf "\n"

mem_info=`free -m | awk '/^Mem:/{print $2"MB"}'`

#echo "Memory Information: Total RAM in MB: $mem_info"


print_info_green "Memory Information (RAM in MB)" "$mem_info"


printf "\n\n"
sleep 1
#Function to get all IP addresses

get_all_ips() {
    ip -4 address show | grep -Eo 'inet ([0-9]{1,3}\.){3}[0-9]{1,3}' | awk '{print $2}'|grep -v "127.0.0.1"
}

# Main script

#echo "List of IP addresses on this system: `get_all_ips` "

print_info_green "List of IP addresses of the server" "`get_all_ips`"

printf "\n\n"
sleep 3

printf "		========================\n"
printf "\033[1m 		Software Information \033[0m \n"
printf "		========================\n"
sleep 1
printf "\n\n"
# COntrol Panel Information

printf "${BOLD}${YELLOW} Collecting Control Panel Details\n\n"

# Initialize control panel variable to a default value
controlpanel="Custom Server and No Control Panel Detected"

# Check for cPanel
if [ -d "/usr/local/cpanel" ]; then
  controlpanel="WHM/cPanel"
elif [ -d "/usr/local/directadmin" ]; then
  controlpanel="DirectAdmin"
elif [ -d "/usr/local/psa" ]; then
  controlpanel="Linux Plesk"
elif [ -d "/usr/local/cwpsrv" ]; then
  controlpanel="CentOS Panel"
elif [ -d "/usr/local/webuzo" ]; then
  controlpanel="Webuzo Panel"
fi

# Print the detected control panel
print_info_green "Control Panel" "$controlpanel"

printf "\n\n"
sleep 1
printf "${BOLD}${YELLOW} Collecting Services Informations \n"
printf "\n"
# Check if a service is enabled
is_service_enabled() {
     service_name=$1
     service_status=$(systemctl is-enabled $service_name 2>/dev/null)
    if [ "$service_status" = "enabled" ]; then
        enabled_services="$service_name is enabled"
		#echo $enabled_services
		
print_info_green "Main Active Services" "$enabled_services"
sleep 1
    else
        enabled_services="$service_name is disabled"
		#echo $enabled_services
print_info_green "Main Active Services" "$enabled_services"
sleep 1
    fi
}

# Check services on Ubuntu
if [ -f "/etc/redhat-release" ]; then
    echo "Checking services on Red Hat"
    
    is_service_enabled httpd
	is_service_enabled nginx
    is_service_enabled named
    is_service_enabled postfix
	is_service_enabled exim
    is_service_enabled vsftpd
    is_service_enabled mysql
	is_service_enabled mariadb
	is_service_enabled php-fpm
	is_service_enabled dovecot
	is_service_enabled pure-ftpd
	is_service_enabled proftpd
	is_service_enabled pdns
	is_service_enabled lsws
	


# Check services on Red Hat
elif [ -f "/etc/lsb-release" ]; then
    echo "Checking services on Ubuntu"
    
    is_service_enabled apache2
	is_service_enabled nginx
    is_service_enabled bind9
    is_service_enabled postfix
	is_service_enabled exim
    is_service_enabled vsftpd
    is_service_enabled mysql
	is_service_enabled mariadb
	is_service_enabled php-fpm
	is_service_enabled dovecot
	is_service_enabled pure-ftpd
	is_service_enabled proftpd
	is_service_enabled pdns
	is_service_enabled lsws
	
	

else
  
	print_info_green "Main Active Services" "Unsupported distribution"
	
fi

printf "\n\n"
sleep 3
printf "		========================================\n"
printf "${BOLD}${YELLOW} 		FileSystem & Memory Usage Information  \n"
printf "		========================================\n"
sleep 1
printf "\n\n"
#FileSystem Disk space usage

printf "${BOLD}${YELLOW} Collectiong FileSystem Usage"
printf "\n\n"
sleep 1
# get partition information
partition_info=$(df -h)

# print header
printf "+--------------------------------+------------------+\n"
printf "%-10s | %-10s | %-10s\n" "Partition" "Used" "Free"
printf "+--------------------------------+------------------+\n"
#echo "Partition | Used | Free"
printf "\n"
sleep 1
# loop through each line of partition information
echo "$partition_info" | while read -r line; do
    # skip header line and non-main partitions (e.g. tmpfs, devtmpfs)
    if [ "$(echo "$line" | cut -c1)" != "/" ]; then
	sleep 1
        continue
    fi
    
    # parse partition name, used space, and free space
    partition=$(echo "$line" | awk '{print $1}')
    used=$(echo "$line" | awk '{print $3}')
    free=$(echo "$line" | awk '{print $4}')
    
    # print partition information
	printf "\n"
    partition_diskspace_details="   $partition          |   $used          |   $free"
    echo "$partition_diskspace_details"
done

printf "\n"
sleep 1
# Memory Utilization Status
printf "${BOLD}${YELLOW} Collectiong Memory & Swap Usage"
printf "\n"
sleep 1
# get memory information
memory_info=$(free -h)

# parse total memory, used memory, and free memory
total_memory=$(echo "$memory_info" | awk '/^Mem:/ {print $2}')
used_memory=$(echo "$memory_info" | awk '/^Mem:/ {print $3}')
free_memory=$(echo "$memory_info" | awk '/^Mem:/ {print $7}')

# parse total swap, used swap, and free swap
total_swap=$(echo "$memory_info" | awk '/^Swap:/ {print $2}')
used_swap=$(echo "$memory_info" | awk '/^Swap:/ {print $3}')
free_swap=$(echo "$memory_info" | awk '/^Swap:/ {print $4}')

# print memory information

#echo "Total Memory (GB) | Used | Free"
#printf "+--------------------------------+------------------+\n"
printf "%-10s | %-10s | %-10s\n" "Total Memory (GB)" "Used" "Free"
#printf "+--------------------------------+------------------+\n"
memory_usage="  $total_memory         |    $used_memory     |   $free_memory"
printf "\n"
sleep 1
echo $memory_usage
printf "\n"
sleep 1
# Check if swap is enabled
swap_status=$(swapon --show)

if [ -z "$swap_status" ]; then
    print_info_red_to_file "SWAP Memory Enabled?" "No. It is recommended to enable swap to avoid OOM"
else
    print_info_green "SWAP Memory Enabled?" "Yes, Swap is enabled on this system."
fi
printf "\n"
sleep 1
#echo "Total SWAP Memory (GB) | Used | Free"
#printf "+--------------------------------+------------------+\n"
printf "%-10s | %-10s | %-10s\n" "Total SWAP Memory (GB)" "Used" "Free"
#printf "+--------------------------------+------------------+\n"
sleep 1
printf "\n"
# check if swap is enabled
if [ $total_swap = "0B" ]; then

	swap_mem_usage="Swap Memory Usage : Swap is disabled"
    print_info_red_to_file "Swap Memory Usage" "$swap_mem_usage"
else
    # print swap information
	printf "\n"
	swap_mem_usage="  $total_swap    |  $used_swap     |  $free_swap"
    echo $swap_mem_usage
fi

printf "\n\n"
sleep 3
printf "		========================================\n"
printf "${BOLD}${YELLOW} 		Server Security Audit Information  \n"
printf "		========================================\n"
printf "\n\n"
## SSH Information
sleep 1
printf "${BOLD}${YELLOW} Collecting SSH Service Information ${NC}${NORMAL}\n"
printf "\n"
# Get the current SSH port
sleep 1
ssh_port=`grep "^Port " /etc/ssh/sshd_config | awk '{print $2}'`


if [ $ssh_port -eq 22 ]; then
  # Default port is being used, suggest changing it

print_info_red_to_file "SSH port Number" "$ssh_port , Recommend to change SSH port number "

else
  # Custom port is being used, just display the current port
  #echo "The SSH port Number: $ssh_port "


print_info_green "SSH port Number" "$ssh_port"
fi
printf "\n"
sleep 1

# Check if PermitRootLogin is enabled in sshd_config file
if grep -q "PermitRootLogin yes" /etc/ssh/sshd_config; then
	PermitRootLogin="Yes"
	

print_info_red_to_file "SSH PermitRootLogin" "$PermitRootLogin, PermitRootLogin is Enabled. It is recommended to disable it and set up a sudo user for accessing SSH"
	#echo "PermitRootLogin = $PermitRootLogin"

else
	PermitRootLogin="No"
	#echo "PermitRootLogin = $PermitRootLogin"
    #echo "PermitRootLogin is already disabled. You don't need to do anything."

	
print_info_green "SSH PermitRootLogin" "$PermitRootLogin, PermitRootLogin is disabled"
fi
printf "\n"

sleep 1
# Check if PasswordAuthentication is enabled in sshd_config file
if grep -q "PasswordAuthentication yes" /etc/ssh/sshd_config; then
	PasswordAuthentication="Yes"


print_info_red_to_file "SSH PasswordAuthentication" "$PasswordAuthentication, PasswordAuthentication is Enabled. It is recommended to disable it and set up a key based authentication if the client has bastionhost/terminal server"
	#echo "PasswordAuthentication = $PasswordAuthentication"


else
	PasswordAuthentication="No"
	#echo "PasswordAuthentication = $PasswordAuthentication"
    #echo "PasswordAuthentication is already disabled. You don't need to do anything."


print_info_green "SSH PasswordAuthentication" "$PasswordAuthentication, PasswordAuthentication is disabled"
fi
printf "\n"
sleep 1

# Find all the shell-enabled users on the system

shell_enabled_users=`getent passwd |grep "/bin/bash" | grep -v root |awk -F: '{print $1 }'`

#echo "Shell Access enabled Users in the server: $shell_enabled_users" 

if [ -n "$shell_enabled_users" ]; then
    print_info_red_to_file "Shell Access enabled Users" "$shell_enabled_users"
	printf "\n"
sleep 1
    print_info_red1_to_file "" "Recommend enabling bash shell access for required users and disabling it for others for better security practices."
else
    print_info_green "Shell Access enabled Users" "No shell access enabled users are configured on this system."
fi

#printf "${BOLD}${RED} %-70s Recommend to enable bash shell access for required users and disable for others for bet secuirty practice. ${NC}${NORMAL}\n"
sleep 1
# List Sudo Users
printf "\n"


sudo_users=`grep -E "^(sudo|wheel)" /etc/group | cut -d: -f4 | tr ',' '\n'`
#echo " List of Sudo Users : $sudo_users"
	
if [ -n "$sudo_users" ]; then
    print_info_red_to_file "List of Sudo Users" "$sudo_users"
	printf "\n"
	sleep 1
    print_info_red1_to_file "" "Verify Sudo user's list and remove unwanted sudo users"
else
    print_info_green "List of Sudo Users" "No sudo users are found on this system."
fi

# Check Open SSH Version
printf "\n"
sleep 1

if [ "$(grep ^ID= /etc/os-release | cut -d= -f2)" = "ubuntu" ]; then
  ssh_version=$(ssh -V 2>&1 | awk '{print $1}' | cut -d_ -f2)
  #echo "Ubuntu OpenSSH version: $ssh_version"



print_info_green "OpenSSH version" "$ssh_version"
printf "\n"
sleep 1
  firewall_status=$(sudo ufw status | grep -E "^Status:" | awk '{print $2}')
  #echo "Firewall Status: $firewall_status"

print_info_green "Default Firewall Status" "$firewall_status"
sleep 1
elif [ "$(grep ^ID= /etc/os-release | cut -d= -f2)" = "debian" ]; then
  ssh_version=$(ssh -V 2>&1 | awk '{print $1}' | cut -d_ -f2)
  #echo "Debian OpenSSH version: $ssh_version"
  
print_info_green "OpenSSH version" "$ssh_version"
printf "\n"
sleep 1
  firewall_status=$(sudo ufw status | grep -E "^Status:" | awk '{print $2}')
  #echo "Firewall Status: $firewall_status"
  
print_info_green "Default Firewall Status" "$firewall_status"
sleep 1
else
  ssh_version=$(rpm -q openssh | awk -F '-' '{print $2}')
  #echo "OpenSSH version: $ssh_version"
  
print_info_green "OpenSSH version" "$ssh_version"
printf "\n"
sleep 1
  firewall_status=$(sudo systemctl is-active firewalld)
  
    #echo "Firewall Status: $firewall_status"
	
	print_info_green "Default Firewall Status" "$firewall_status"
	
fi
printf "\n"
sleep 2
print_info_green1 "Collecting Kernel package updates. Please be patient."
printf "\n"
# Function to check repository errors
check_repository_errors() {
   error_message=$(yum repolist 2>&1 | grep -i "error")
  if [ -n "$error_message" ]; then
    print_info_red_to_file "Check for repository errors" "Repository update error detected. Please fix repository errors before checking for security updates"
	printf "\n"
    return
  fi
}
sleep 1
printf "\n"
# Function to check kernel version
check_kernel_version() {
   current_kernel_version=$(uname -r)

  if [ "$(grep ^ID= /etc/os-release | cut -d= -f2)" = "ubuntu" ]; then
     latest_kernel_version=$(apt-cache show linux-image-generic | grep "Depends:" | head -n1 | awk {'print $2'} | sed 's/linux-image-//;s/,$//')
  elif [ "$(grep ^ID= /etc/os-release | cut -d= -f2)" = "debian" ]; then
     latest_kernel_version=$(apt-cache show linux-image-generic | grep "Depends:" | head -n1 | awk {'print $2'} | sed 's/linux-image-//;s/,$//')
  elif [ "$(grep ^ID= /etc/os-release | cut -d= -f2)" != "ubuntu" ]; then
     latest_kernel_version=$(yum check-update kernel 2>&1| grep kernel | awk '{print $2}' | head -n1)
  fi

  if [ -z "$latest_kernel_version" ]; then
    sleep 1
    print_info_green "Current Kernel Version" "$current_kernel_version"
    printf "\n"
    print_info_green "Kernel Updates" "No updates found for the kernel. Current kernel is up to date."
  else
    sleep 1
    print_info_green "Current Kernel Version" "$current_kernel_version"
    printf "\n"
    print_info_red_to_file "New kernel available" "$latest_kernel_version, Recommend updating the Kernel version"
  fi
}

#printf "Collecting Kernel Version Information \n"
check_repository_errors
check_kernel_version


printf "\n"
sleep 2
# Check CSF Status

#echo "Collecting CSF Firewall Information \n"

if [ -e /usr/sbin/csf ]
then
	csf_installed="CSF is installed"
    #echo $csf_installed

	print_info_green "CSF Installed?" "$csf_installed"
	printf "\n"
	sleep 1
	if [ "$(csf --status |cut -d"," -f1 |grep -v WARNING)" = "csf and lfd have been disabled" ]; then
	
		csf_status="Disabled"
		#echo "CSF Status : $csf_status"

	print_info_red_to_file "CSF Status" "$csf_status"
	printf "\n"
	else
     csf_status="Enabled"
		#echo "CSF Status : $csf_status"

	print_info_green "CSF Status" "$csf_status"
	printf "\n"
	sleep 1
    # Check CSF testing mode status
    csf_testing_mode=$(grep -E "^\s*TESTING\s*=" /etc/csf/csf.conf | awk -F= '{print $2}' | tr -d ' ')
    if [ $csf_testing_mode = "1" ]
    then
        #echo "CSF testing mode : $csf_testing_mode , Recommending to Disable it."

	print_info_red_to_file "CSF Testing Mode" "$csf_testing_mode , Recommending to Disable it"
	printf "\n"
    else
        #echo "CSF testing mode : $csf_testing_mode & disabled"

	print_info_green "CSF Testing Mode" "$csf_testing_mode , Disabled"
	printf "\n"
    fi
	printf "\n"
sleep 1
    # Print the list of TCP_IN ports
    tcp_in_ports=$(grep -E "^\s*TCP_IN\s*=" /etc/csf/csf.conf | awk -F= '{print $2}' | tr -d ' ')
    #echo "TCP_IN ports: $tcp_in_ports"

	
	print_info_red_to_file "CSF TCP_IN ports" "$tcp_in_ports"
	print_info_red1_to_file	" " "Recommend to remove unwanted ports from CSF TCP_IN list"
	sleep 1
	printf "\n\n"
    # Check LFD status
    lfd_status=$(systemctl status lfd.service | grep "Active:" | awk '{print $2}')
    #echo "LFD status: $lfd_status"

	print_info_green "LFD status" "$lfd_status"
	fi
else
	csf_installed="CSF is not installed"
    #echo $csf_installed
	
	print_info_red_to_file "CSF Installed?" "$csf_installed"
    
fi
printf "\n"
sleep 1
# Check if APF is installed
if [ -x "$(command -v apf)" ]; then
    print_info_green "APF Firewall is installed ?" "Yes"
else
    print_info_red_to_file "APF Firewall is installed?" "No , If CSF is there, no need for APF"
fi
printf "\n"
sleep 1
# Check if Fail2Ban is installed
if [ -x "$(command -v fail2ban-client)" ]; then

	print_info_green "Fail2Ban Firewall is installed ?" "Yes"
else
    print_info_red_to_file "Fail2Ban Firewall is installed ?" "No , If CSF/APF is there, no need for Fail2ban"
fi
printf "\n"
sleep 1
##Check ClanAv status
if [ -x "$(command -v clamscan)" ]; then
  
	print_info_green "ClamAV Antivirus Installed?" "Yes"
else
    print_info_red_to_file "ClamAV Antivirus Installed?" "No , Recommend to install Clamav scanner if there is no other malware scanner"
fi
printf "\n\n"
# Check OpenSSL Version
sleep 1
#echo "Collecting OpenSSL Version Information \n"

openssl_version=`openssl version`

#echo "OpenSSL Version : $openssl_version"

	print_info_green "OpenSSL Version" "$openssl_version"

# Get the server's RDNS
printf "\n"
sleep 1
# Check if dig or host commands are available
print_info_red1 "Collecting PTR/RDNS Status for all server IPs"
printf "\n"
sleep 1
if [ -x "$(command -v dig)" ]; then
    # Use dig to get the PTR record for each IP
    ips=$(hostname -I)
    for ip in $ips; do
        ptr_record=$(dig -x "$ip" +short)
        if [ -n "$ptr_record" ]; then
            print_info_green "PTR record for IP $ip" "$ptr_record"
			printf "\n"
			sleep 1
        else
            print_info_red_to_file "PTR record for IP $ip" "No PTR record found"
			printf "\n"
			sleep 1
        fi
    done
elif [ -x "$(command -v host)" ]; then
    # Use host to get the PTR record for each IP
    ips=$(hostname -I)
    for ip in $ips; do
        ptr_record=$(host "$ip" | awk '/pointer/ {print $5}')
        if [ -n "$ptr_record" ]; then
            print_info_green "PTR record for IP $ip" "$ptr_record"
			printf "\n"
			sleep 1
        else
            print_info_red_to_file "PTR record for IP $ip" "No PTR record found"
			printf "\n"
			sleep 1
        fi
    done
else
    print_info_red_to_file "PTR Record Status for Server IPs" "DNS utilities (dig or host) are not found. Use online DNS lookup tool for checking PTR Records"
   printf "\n"
	sleep 1
fi



printf "\n"
sleep 2
#echo "Checking /tmp Security Status \n"

# /tmp Secured

# Check if /tmp is secured using mount output
tmp_secured=$(mount | grep -wE "/tmp|tmpfs" | grep -o "noexec" |uniq)

if [ -n $tmp_secured ]; then

	tmp_secure_status="/tmp is secured."
	#echo $tmp_secure_status

	print_info_green "/tmp Secured Status" "$tmp_secure_status"
else
	tmp_secure_status="/tmp is not secured. Please secure the /tmp & /var/tmp by adding "nosuid,noexec" options in fstab"
	#echo $tmp_secure_status
	print_info_red_to_file "/tmp Secured Status" "$tmp_secure_status"
	
fi

printf "\n"
sleep 1
#echo "Checking whether /tmp is infected or not \n"

tmp_result1=`file /tmp/* | grep -iE "perl|shell|executable" |wc -l`

if [ $tmp_result1 -gt 0 ]; then
 tmp_infection_result="CRITICAL - Found Suspecious File in /tmp or /var/tmp : "$tmp_result1" "$tmp_result2" "$tmp_result3" "$tmp_result4" "$tmp_result5" "$tmp_result6" "
 #echo $tmp_infection_result

	print_info_red_to_file "Any infection in /tmp" "$tmp_infection_result"
else
 tmp_infection_result="No vulnerable scripts found in /tmp"

 #echo $tmp_infection_result

print_info_green "Any infection in /tmp" "$tmp_infection_result"
fi

printf "\n"

sleep 1

#echo "Collecting SSH Root Key Count"

# Check if /root/.ssh/authorized_keys exists
if [ ! -f "/root/.ssh/authorized_keys" ]; then

	print_info_green "SSH Key Under root user" "No authorized key file found"
elif [ ! -d "/root/.ssh" ]; then
 
	print_info_green "SSH Key Under root user" "No SSH path found"
else
    keyscount=$(cat /root/.ssh/authorized_keys | wc -l)
    keypairoutput="Number of Keys : $keyscount"

    if [ $keyscount -eq 0 ]; then
   
		print_info_green "SSH Key Under root user" "No SSH Keys found under root user"
    else
        SSH_Keypair_count="Found SSH Keys under root user. Kindly verify whether the keys are necessary. Number of Keys found : $keypairoutput"

		print_info_red_to_file "SSH Key Under root user" "$SSH_Keypair_count"
    fi
fi

printf "\n\n"
## Failed SSH login Attempt
sleep 1
#echo "Collecting Failed SSH login Attempt Details"

# Get the current time and calculate the timestamp for 1 hour ago
current_time=$(date -d '1 hour ago' "+%b %d")
one_hour_ago=$(date -d '1 hour ago' "+%H:%M:%S")

# Retrieve the SSH authentication log file path based on the operating system
auth_log=""
if [ -f "/var/log/auth.log" ]; then
    auth_log="/var/log/auth.log"  # Ubuntu
elif [ -f "/var/log/secure" ]; then
    auth_log="/var/log/secure"  # Red Hat
else

	print_info_green "Failed SSH login Attempt" "Failed to locate the SSH authentication log file."
    return
fi

# Extract the failed SSH login attempts and filter by timestamp
failed_ssh_attempts=$(grep "$current_time" "$auth_log" | grep "sshd.*Failed password" | awk -v h="$one_hour_ago" '$3 >= h { print $0 }')

if [ -z "$failed_ssh_attempts" ]; then

	print_info_green "Failed SSH login Attempt" "No Failed SSH login Attempt."
else
    # Extract the IP addresses from the failed attempts
    ip_addresses=$(echo "$failed_ssh_attempts" | awk '{ match($0, /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/); if (RSTART) print substr($0, RSTART, RLENGTH) }' | sort | uniq)
    
    # Display the list of IP addresses
    Failed_ssh_login_attempt="Failed SSH login attempts in the last hour, Please verify and secure SSH service: $ip_addresses"
    

	print_info_red_to_file "Failed SSH login Attempt" "$Failed_ssh_login_attempt"
fi

printf "\n\n"
sleep 1
#echo "Collecting Perl Cron Malware Details \n"
## Check Perl Cron Malware

cron_malware_count=$(grep '*' -ir /var/spool/cron/*  | grep -v root | egrep "/var/tmp/|base64" | wc -l )
cron_malware_user=$(grep '*'  -ir /var/spool/cron/*  | grep -v root | egrep "/var/tmp/|base64" | cut -d/ -f5 | cut -d: -f1 | uniq)

cron_malware_code=$(grep '*' -ir /var/spool/cron/*  | grep -v root | egrep "/var/tmp/|base64" )

if [ $cron_malware_count -eq 0 ]
then
        Perl_cron_malware_status="OK - No perl cron malware"
        #echo $Perl_cron_malware_status

	print_info_green "Check Perl Cron Malware" "$Perl_cron_malware_status"
		
else
	Perl_cron_malware_status="Found Perl Cron Malware : Affected User : $cron_malware_user , Cron Path : $cron_malware_code"
	#echo $Perl_cron_malware_status

	print_info_red_to_file "Check Perl Cron Malware" "$Perl_cron_malware_status"
fi
sleep 2
printf "\n"
#echo "Collecting Sysstat package Information \n"
# Check for sysstat installation
if [ -x "$(command -v sar)" ]; then
	sysstat_installed="sysstat is installed."
    #echo $sysstat_installed

	print_info_green "Check for sysstat installation" "$sysstat_installed"
	
else
   sysstat_installed="sysstat is not installed. Please install sysstat for collecting more detailed logs"
   #echo $sysstat_installed
   
	print_info_red_to_file "Check for sysstat installation" "$sysstat_installed"
   #exit 0
fi
printf "\n\n"
sleep 1
# Check if sysstat is enabled
sysstat_service=""
if [ -f "/etc/lsb-release" ]; then
    sysstat_service="sysstat"
fi

if [ -n "$sysstat_service" ]; then
    if [ -f "/etc/default/sysstat" ]; then
        if grep -qi "ENABLED=\"true\"" /etc/default/sysstat; then
	
			sysstat_enabled="sysstat is enabled."
			#echo $sysstat_enabled

	print_info_green "sysstat Enabled or not?" "$sysstat_enabled"
		else
			sysstat_enabled="sysstat is installed, however, it is not enabled. Please enable it"
			#echo $sysstat_enabled

	print_info_red_to_file "sysstat Enabled or not?" "$sysstat_enabled"
		fi
	else
        #echo "/etc/default/sysstat file not found."
	
	print_info_red "sysstat Enabled or not?" "/etc/default/sysstat file not found"
    fi
fi

printf "\n"
sleep 2
#echo "Collecting PHP disable_functions Status \n"
    
# --- Function to check PHP installation ---
check_php_installed() {
    if command -v php >/dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}

# --- disable_functions Checker ---
check_disable_functions() {
    php_ini_file=$1
    version=$2

    if [ ! -f "$php_ini_file" ]; then
        printf "PHP $version: php.ini not found.\n"
        return
    fi

    disable_functions=$(awk -F "=" '/^disable_functions/{print $2}' "$php_ini_file" | awk '{$1=$1;print}')
    if [ -z "$disable_functions" ]; then
        print_info_red_to_file "PHP $version disable_functions" "Not enabled. Please enable it."
	echo "PHP $version disable_functions: None (not set)"
    else
        print_info_green "PHP $version disable_functions" "Enabled"
	echo "PHP $version disable_functions: $disable_functions"
    fi
}

# --- allow_url_fopen Checker ---
check_allow_url_fopen() {
    php_ini_file=$1
    version=$2

    if [ ! -f "$php_ini_file" ]; then
        printf "PHP $version: php.ini not found.\n"
        return
    fi

    allow_url_fopen=$(awk -F "=" '/^allow_url_fopen/{print $2}' "$php_ini_file" | awk '{$1=$1;print}')
    if [ "$allow_url_fopen" = "On" ]; then
        print_info_red_to_file "PHP $version allow_url_fopen" "Enabled. Recommended to disable."
    else
        print_info_green "PHP $version allow_url_fopen" "Disabled"
    fi
}

# --- allow_url_include Checker ---
check_allow_url_include() {
    php_ini_file=$1
    version=$2

    if [ ! -f "$php_ini_file" ]; then
        printf "PHP $version: php.ini not found.\n"
        return
    fi

    allow_url_include=$(awk -F "=" '/^allow_url_include/{print $2}' "$php_ini_file" | awk '{$1=$1;print}')
    if [ "$allow_url_include" = "On" ]; then
        print_info_red_to_file "PHP $version allow_url_include" "Enabled. Recommended to disable."
    else
        print_info_green "PHP $version allow_url_include" "Disabled"
    fi
}

# =====================================================
#  cPanel, DirectAdmin, Plesk
# =====================================================
if [ -e "/usr/local/cpanel/cpanel" ]; then
    echo "Checking PHP settings in cPanel..."
    for version in $(ls -1 /opt/cpanel | grep ea-php); do
        check_disable_functions "/opt/cpanel/$version/root/etc/php.ini" "$version"
        check_allow_url_fopen "/opt/cpanel/$version/root/etc/php.ini" "$version"
        check_allow_url_include "/opt/cpanel/$version/root/etc/php.ini" "$version"
    done
fi

if [ -e "/usr/local/directadmin/directadmin" ]; then
    echo "Checking PHP settings in DirectAdmin..."
    for version in $(ls -1 /usr/local/ | grep php | grep -v suphp); do
        check_disable_functions "/usr/local/$version/lib/php.ini" "$version"
        check_allow_url_fopen "/usr/local/$version/lib/php.ini" "$version"
        check_allow_url_include "/usr/local/$version/lib/php.ini" "$version"
    done
fi

if [ -e "/usr/local/psa/version" ]; then
    echo "Checking PHP settings in Plesk..."
    for version in $(plesk bin php_handler --list 2>/dev/null | awk '{print $2}' | cut -d"." -f1,2 | grep -v display | uniq); do
        check_disable_functions "/opt/plesk/php/$version/etc/php.ini" "$version"
        check_allow_url_fopen "/opt/plesk/php/$version/etc/php.ini" "$version"
        check_allow_url_include "/opt/plesk/php/$version/etc/php.ini" "$version"
    done
fi

# =====================================================
#  Ubuntu
# =====================================================
if [ -e "/etc/lsb-release" ]; then
    if check_php_installed; then
        for version in $(ls -1 /etc/php 2>/dev/null); do
            if [ -e "/etc/php/$version/apache2/php.ini" ]; then
                ini="/etc/php/$version/apache2/php.ini"
            elif [ -e "/etc/php/$version/cli/php.ini" ]; then
                ini="/etc/php/$version/cli/php.ini"
            else
                continue
            fi
            echo "PHP $version found ($ini)"
            check_disable_functions "$ini" "$version"
            check_allow_url_fopen "$ini" "$version"
            check_allow_url_include "$ini" "$version"
        done

        # Also check loaded config from php --ini
        loaded_ini=$(php --ini 2>/dev/null | grep "Loaded Configuration File" | awk '{print $4}')
        if [ -f "$loaded_ini" ]; then
            echo "Checking loaded php.ini from php --ini ($loaded_ini)..."
            check_disable_functions "$loaded_ini" "php --ini"
            check_allow_url_fopen "$loaded_ini" "php --ini"
            check_allow_url_include "$loaded_ini" "php --ini"
        fi
    else
        print_info_red1 "PHP not found" "Skipping Ubuntu PHP checks."
    fi
fi

# =====================================================
#  Red Hat / CentOS
# =====================================================
if [ -e "/etc/redhat-release" ]; then
    if check_php_installed; then
        if [ -f "/etc/php.ini" ]; then
            check_disable_functions "/etc/php.ini" "Base Repo"
            check_allow_url_fopen "/etc/php.ini" "Base Repo"
            check_allow_url_include "/etc/php.ini" "Base Repo"
        fi
        if [ -d "/etc/opt/remi" ]; then
            for version in $(ls -1 /etc/opt/remi); do
                check_disable_functions "/etc/opt/remi/$version/php.ini" "$version"
                check_allow_url_fopen "/etc/opt/remi/$version/php.ini" "$version"
                check_allow_url_include "/etc/opt/remi/$version/php.ini" "$version"
            done
        fi
        loaded_ini=$(php --ini 2>/dev/null | grep "Loaded Configuration File" | awk '{print $4}')
        if [ -f "$loaded_ini" ]; then
            echo "Checking loaded php.ini from php --ini ($loaded_ini)..."
            check_disable_functions "$loaded_ini" "php --ini"
            check_allow_url_fopen "$loaded_ini" "php --ini"
            check_allow_url_include "$loaded_ini" "php --ini"
        fi
    else
        print_info_red1 "PHP not found" "Skipping RedHat PHP checks."
    fi
fi

# =====================================================
#  CloudLinux PHP Selector
# =====================================================
if uname -r | grep -q lve; then
    if command -v selectorctl >/dev/null 2>&1; then
        echo "Checking CloudLinux PHP Selector..."
        for selectorversion in $(selectorctl --list 2>/dev/null | awk '{gsub(/\./,"",$1); print $1}'); do
            ini="/opt/alt/php$selectorversion/etc/php.ini"
            [ -f "$ini" ] || continue
            check_disable_functions "$ini" "CloudLinux PHP$selectorversion"
            check_allow_url_fopen "$ini" "CloudLinux PHP$selectorversion"
            check_allow_url_include "$ini" "CloudLinux PHP$selectorversion"
        done
    fi
else
    echo "No CloudLinux PHP versions detected."
fi

printf "\n"

## Checking php disable_function status for CloudLinux PHP-Selector versions.
sleep 2
CloudlinuxOS_check=$(uname -r | grep lve)

if [ -n "$CloudlinuxOS_check" ]; then
    printf "${BOLD}${YELLOW} CloudLinux PHP-Selector Enabled & Checking disable_function status\n"

    # Function to check if PHP is installed
    check_phpselector_installed() {
        if [ -x "$(command -v selectorctl)" ]; then
            for selectorversion in $(selectorctl --list | awk '{gsub(/\./, "", $1); print $1}'); do
                disable_functions=$(awk -F "=" '/^disable_functions/{print $2}' "/opt/alt/php$selectorversion/etc/php.ini" | awk '{$1=$1;print}')

                if [ -z "$disable_functions" ]; then
                    disable_function_status="disable_functions is not enabled for PHP $selectorversion. Please enable it."
					print_info_red_to_file "PHP disable_function Status for CloudLinux PHPselector" "$disable_function_status"
                else
                    disable_function_status="disable_functions is enabled for PHP $selectorversion."
					print_info_green "PHP disable_function Status for CloudLinux PHPselector" "$disable_function_status"
                fi

               
				#print_info_green "PHP disable_function Status for CloudLinux PHPselector" "$disable_function_status"
				sleep 1
            done
        fi
    }

    check_phpselector_installed
else
    printf "${BOLD}${YELLOW} No CloudLinux PHP Versions \n"
fi

printf "\n"

## Checking php allow_url_fopen status for CloudLinux PHP-Selector versions.
sleep 1
CloudlinuxOS_check=$(uname -r | grep lve)

if [ -n "$CloudlinuxOS_check" ]; then
    printf "${BOLD}${YELLOW} CloudLinux PHP-Selector Enabled & Checking allow_url_fopen status \n"

    # Function to check if PHP is installed
    check_phpselector_installed() {
        if [ -x "$(command -v selectorctl)" ]; then
            for selectorversion in $(selectorctl --list | awk '{gsub(/\./, "", $1); print $1}'); do
                allow_url_fopen=$(awk -F "=" '/^allow_url_fopen/{print $2}' "/opt/alt/php$selectorversion/etc/php.ini" | awk '{$1=$1;print}')

                 if [ "$allow_url_fopen" = "On" ]; then
        allow_url_fopen_status="allow_url_fopen is enabled for PHP $selectorversion. It is recommended to disable it."
		print_info_red_to_file "PHP allow_url_fopen Status for CL PHP Selector" "$allow_url_fopen_status"
    else
        allow_url_fopen_status="allow_url_fopen is not enabled for PHP $selectorversion."
		print_info_green "PHP allow_url_fopen Status for CL PHP Selector" "$allow_url_fopen_status"
    fi


	#print_info_green "PHP allow_url_fopen Status for CL PHP Selector" "$allow_url_fopen_status"
sleep 1
            done
        fi
    }

    check_phpselector_installed

fi

printf "\n"
sleep 1
## Checking CL Cagefs status for CloudLinux PHP-Selector versions.

CloudlinuxOS_check=$(uname -r | grep lve)

if [ -n "$CloudlinuxOS_check" ]; then

    # Function to check if PHP is installed
    check_cagefs_installed() {
        if [ -x "$(command -v cagefsctl)" ]; then
            
                users_cagefs=$(cagefsctl --list-disabled)

                 if [ -z "$users_cagefs" ]; then
        users_cagefs_status="CloudLinux CageFs is enabled for all users"
		print_info_green "CloudLinux CageFs Status" "$users_cagefs_status"
    else
        users_cagefs_status="CloudLinux CageFs is disabled for the users $users_cagefs , Recommend to enable cagefs for all users"
		print_info_red_to_file "CloudLinux CageFs Status" "$users_cagefs_status"
    fi

  
	#print_info_green "CloudLinux CageFs Status" "$users_cagefs_status"

            
        fi
    }

    check_cagefs_installed

fi

printf "\n"
sleep 1
## Checking Db-Governor status for CloudLinux.

CloudlinuxOS_check=$(uname -r | grep lve)

if [ -n "$CloudlinuxOS_check" ]; then

    # Function to check if Db-Governor is installed
    check_dbgovernor_installed() {
        if [ -x "$(command -v dbctl)" ]; then
            
            dbgovnor_error=$(dbctl list 2>&1 | grep -E "Can't connect to socket|governor is not started")

            if [ -n "$dbgovnor_error" ]; then
              
				print_info_red_to_file "Checking Db-Governor status" "Db-Governor service has issues. Please check it Manually"
                return
            else
                
				print_info_green "Checking Db-Governor status" "Db-Governor service is Enabled"
                return
            fi
        else
           
			print_info_red_to_file "Checking Db-Governor status" "Db-Governor service is not Installed , Please check with seniors and enable it."
            return
        fi
    }

    check_dbgovernor_installed
#else
#   printf "+--------------------------------+------------------+\n"
#    printf "| Checking Db-Governor status    | %-16s |\n" "Db-Governor service is not Installed"
 #   printf "+--------------------------------+------------------+\n"
fi
printf "\n"
sleep 1
#echo "Collecting Apache Directory Listing Status"

# Function to check if directory listing is enabled for Apache
check_apache_directory_listing() {
    apache_config_file="$1"
    environment="$2"
    dir_listing_status=$(grep -E 'Options\s.*Indexes' "$apache_config_file")

    if [ -z "$dir_listing_status" ]; then
        printf "\n"
		sleep 1
		print_info_green "Web server DirectoryListing" "Disabled"
		sleep 1
    else
        printf "\n"
		sleep 1
		print_info_red_to_file "Web server DirectoryListing" "Enabled"
		sleep 1
    fi
}


apache_control_panel_detected=0

# Check for Apache directory listing
if [ -x "$(command -v httpd)" ] || [ -x "$(command -v apachectl)" ]; then
    # Check for cPanel
    if [ -e "/usr/local/cpanel/cpanel" ]; then
        printf "${BOLD}${YELLOW} Checking Apache directory listing in cPanel... "
		printf "\n\n"
        check_apache_directory_listing "/etc/apache2/conf/httpd.conf" "cPanel"
        echo
        apache_control_panel_detected=1
    fi

    # Check for DirectAdmin
    if [ -e "/usr/local/directadmin/directadmin" ]; then
        printf "${BOLD}${YELLOW} Checking Apache directory listing in DirectAdmin... "
		printf "\n\n"
        check_apache_directory_listing "/etc/httpd/conf/httpd.conf" "DirectAdmin"
        echo
        apache_control_panel_detected=1
    fi

    # Check for Plesk
    if [ -e "/usr/local/psa/version" ]; then
        printf "${BOLD}${YELLOW} Checking Apache directory listing in Plesk... "
		printf "\n\n"
        check_apache_directory_listing "/etc/httpd/conf/httpd.conf" "Plesk"
        echo
        apache_control_panel_detected=1
    fi

if [ $apache_control_panel_detected -eq 0 ]; then
   # echo "No control panel detected for Apache. Proceeding with OS checks."
	print_info_green "Controlpanel Status " "No control panel detected. Checking LAMP Configuration"
	printf "\n"
    # Check for Red Hat
    if [ -e "/etc/redhat-release" ]; then
        printf "${BOLD}${YELLOW} Checking Apache directory listing in Red Hat... "
		printf "\n"
        check_apache_directory_listing "/etc/httpd/conf/httpd.conf" "Red Hat"
        echo
    fi

    # Check for Ubuntu
    if [ -e "/etc/lsb-release" ]; then
        printf "${BOLD}${YELLOW} Checking Apache directory listing in Ubuntu... "
		printf "\n"
        check_apache_directory_listing "/etc/apache2/apache2.conf" "Ubuntu"
        echo
    fi
fi

else


print_info_green "Apache DirectoryListing Status " "No Apache service found. Skipping"
sleep 1
fi
sleep 1
#echo "Collecting Nginx Directory Listing Status"

# Function to check if directory listing is enabled for Nginx
check_nginx_directory_listing() {
    nginx_config_file=$1
    environment=$2
    directory_listing_status=$(grep -E 'autoindex\s+on;' "$nginx_config_file")

    if [ -z "$directory_listing_status" ]; then
        printf "\n"
		sleep 1
		print_info_green "Web server DirectoryListing" "Disabled"
		sleep 1
    else
		printf "\n"
		sleep 1
		print_info_red_to_file "Web server DirectoryListing" "Enabled"
		sleep 1
    fi
}

nginx_control_panel_detected=0

# Check for Nginx directory listing
if [ -x "$(command -v nginx)" ]; then
    # Check for cPanel
    if [ -e "/usr/local/cpanel/cpanel" ]; then
        printf "${BOLD}${YELLOW} Checking Nginx directory listing in cPanel... "
		printf "\n"
        check_nginx_directory_listing "/etc/nginx/nginx.conf" "cPanel"
        echo
        nginx_control_panel_detected=1
    fi

    # Check for DirectAdmin
    if [ -e "/usr/local/directadmin/directadmin" ]; then
        printf "${BOLD}${YELLOW} Checking Nginx directory listing in DirectAdmin... "
		printf "\n"
        check_nginx_directory_listing "/etc/nginx/nginx.conf" "DirectAdmin"
        echo
        nginx_control_panel_detected=1
    fi

    # Check for Plesk
    if [ -e "/usr/local/psa/version" ]; then
        printf "${BOLD}${YELLOW} Checking Nginx directory listing in Plesk... "
		printf "\n"
        check_nginx_directory_listing "/etc/nginx/nginx.conf" "Plesk"
        echo
        nginx_control_panel_detected=1
    fi
 
  if [ $nginx_control_panel_detected -eq 0 ]; then
  printf "\n"
    printf "${BOLD}${YELLOW} No control panel detected for Nginx. Proceeding with LNPM checks."
	printf "\n"
	sleep 1
    # Check for Red Hat
    if [ -e "/etc/redhat-release" ]; then
        printf "${BOLD}${YELLOW} Checking Nginx directory listing in Red Hat... "
		printf "\n"
		printf "\n"
        check_nginx_directory_listing "/etc/nginx/nginx.conf" "Red Hat"
		printf "\n"
        echo
    fi

    # Check for Ubuntu
    if [ -e "/etc/lsb-release" ]; then
        printf "${BOLD}${YELLOW} Checking  Nginx directory listing in Ubuntu... "
		printf "\n"
		printf "\n"
        check_nginx_directory_listing "/etc/nginx/nginx.conf" "Ubuntu"
		printf "\n"
        echo
    fi
fi

else 


print_info_green "Nginx DirectoryListing Status " "Nginx is not installed, Skipping"
printf "\n"
fi


sleep 2
printf "\n"

# Define the path to the vhosts directory
VHOSTS_DIR="/usr/local/lsws/conf/vhosts/"

# Check if the vhosts directory exists
if [ -d "$VHOSTS_DIR" ]; then

	print_info_red1_to_file "Collecting DirectoryListing Setting for Litespeed"
    # Get a list of all domain names under vhosts
    domains_vhosts=$(find "$VHOSTS_DIR" -type f -name "vhconf.conf" -exec dirname {} \; | grep -v "Example" | awk -F'/' '{print $NF}')

    # Check the autoIndex setting for each domain
    for domain in $domains_vhosts; do
        vhconf_file="$VHOSTS_DIR/$domain/vhconf.conf"
		  printf "\n"
		  sleep 1
        # Check if the vhconf file exists
        if [ ! -f "$vhconf_file" ]; then
            print_info_red_to_file "Litespeed Vhost check for the domain $domain" "Error: Virtual host configuration file not found for domain $domain"
			  printf "\n"
        else
            autoIndex_setting=$(grep "autoIndex" "$vhconf_file" | awk '{print $2}')

            if [ -z "$autoIndex_setting" ]; then
                #echo "Directory listing setting not found for the domain: $domain"
				print_info_red_to_file "Litespeed DirectoryListing check for the domain $domain" "DirectoryListing setting not found for the domain: $domain"
				printf "\n"
            elif [ "$autoIndex_setting" -eq 0 ]; then
                #echo "Directory listing is DISABLED for the domain: $domain"
				print_info_green "Litespeed DirectoryListing check for the domain $domain" "DirectoryListing is disabled for the domain: $domain"
				printf "\n"
				sleep 1
            else
                #echo "Directory listing is ENABLED for the domain: $domain"
				print_info_red_to_file "Litespeed DirectoryListing check for the domain $domain" "DirectoryListing is enabled. Recommend to disable it."
				printf "\n"
				sleep 1
            fi
        fi
    done

else
    print_info_red1_to_file "No Open LiteSpeed Web server found in this system"
	printf "\n"
				sleep 1
fi

printf "\n\n"
				sleep 2
#echo "Collecting  Mod-Security Status \n"



# Check if Apache service is installed
check_apache_service() {
    if [ -x "$(command -v apachectl 2>/dev/null)" ]; then
        return 0
    else
        return 1
    fi
}

# Check if mod_security is enabled in Apache
check_mod_security() {
    module_list=$(apachectl -M 2>/dev/null)
    
    if echo "$module_list" | grep -q "security"; then
        
		print_info_green "Mod-Security (WAF) Status" "Enabled"
		sleep 1
    else
        
		print_info_red_to_file "Mod-Security (WAF) Status" "Disabled, Recommend to enable it."
		sleep 1
    fi
}

# Main function
main() {
    if check_apache_service; then
        check_mod_security
    else
        
		print_info_green "Apache Mod-Security Status " "No Apache service found. Skipping"
		sleep 1
    fi
}

# Execute the main function
main

sleep 2
printf "\n"
print_info_green1 "Collecting Security Package Update Status. Please be patient."
printf "\n"
#echo "Collecting Security Package Update Status \n"
# Function to check if the package manager is yum or apt-get
get_package_manager() {
  if [ -f "/etc/redhat-release" ]; then
    package_manager="yum"
  elif [ -f "/etc/lsb-release" ]; then
    package_manager="apt-get"
  else
    printf "Error: Unable to determine the package manager. This script supports Red Hat and Ubuntu-based systems only. \n"
	sleep 1
    return
  fi
}




# Function to check for security updates
check_security_updates() {
  if [ "$package_manager" = "yum" ]; then
    repo_errors=$(yum repolist 2>&1 | grep -E "Error|Could not|Fail")
    if [ -n "$repo_errors" ]; then
    
	  print_info_red_to_file "Check for repository errors" "Repository update error detected. Please fix repository errors before checking for security updates."
      return
    fi

    security_updates=$(yum list-security --security)
  elif [ "$package_manager" = "apt-get" ]; then
    repo_errors=$(apt-get update 2>&1 | grep "Err ")
    if [ -n "$repo_errors" ]; then
    
	  print_info_red_to_file "Check for repository errors" "Repository update error detected. Please fix repository errors before checking for security updates."
      return
    fi

    security_updates=$(apt-get -s upgrade | grep -i security)
  fi

  if [ -z "$security_updates" ]; then
    security_update_status="No security updates available."
	print_info_green "Check for security updates" "$security_update_status"
  else
    security_update_status="Security updates available. Recommendation: It is recommended to install security updates."
	print_info_red_to_file "Check for security updates" "$security_update_status"
  fi

  #print_info_green "Check for security updates" "$security_update_status"
}

get_package_manager
check_security_updates

sleep 2
## Checking DDOS##
printf "\n"
#echo "Checking DDOS Attack Status \n"


# Check for SYN_RECV and SYN_SENT connections
syn_recv_count=$(netstat -plane | grep SYN_RECV | wc -l)
syn_sent_count=$(netstat -plane | grep SYN_SENT | wc -l)


print_info_green "SYN_RECV connections" "$syn_recv_count"
printf "\n"
print_info_green "SYN_SENT connections" "$syn_sent_count"
printf "\n"
sleep 1
# Define threshold values
syn_recv_threshold=50
syn_sent_threshold=1

# Compare with thresholds and take action
if [ "$syn_recv_count" -gt "$syn_recv_threshold" ]; then
    #echo "Potential SYN_RECV DDoS attack detected!"
	
	print_info_red_to_file "Check Inhound DDOS Connections " "Potential SYN_RECV DDoS attack detected!. Please check network connections"
    # Add your actions here, such as sending alerts or blocking IP addresses
	else
	
	print_info_green "Check Inhound DDOS Connections " "No Inbound DDOS Detected"
fi
printf "\n"
if [ "$syn_sent_count" -ge "$syn_sent_threshold" ]; then
  
	print_info_red_to_file "Check Outbound DDOS Connections " "Potential SYN_SENT DDoS attack detected!. Please check network connections"
    # Add your actions here, such as sending alerts or blocking IP addresses
	else
	
	print_info_green "Check Outbound DDOS Connections " "No Outbound DDOS Detected"
fi
printf "\n"
sleep 1
# Define the path to the named.conf file
NAMED_CONF="/etc/named.conf"

# Check if the named.conf file exists
if [ -f "$NAMED_CONF" ]; then
    # Check if this is a cPanel server
    if [ -f "/usr/local/cpanel/version" ]; then
       
        # Check for recursion settings in the "external" view of named.conf
        if grep -q "view[[:space:]]*\"external\"" "$NAMED_CONF" && \
           grep -q "recursion[[:space:]]*no;" "$NAMED_CONF"; then
            
			print_info_green "cPanel DNS recursion Status" "DNS recursion is Disabled in the 'external' view"
			printf "\n"
        else
            
			print_info_red_to_file "cPanel DNS recursion Status" "DNS recursion is Enabled in the 'external' view. Recommend to disable it."
			printf "\n"
            
        fi
    else
       

        # Check for recursion settings in named.conf
        if grep -q "recursion[[:space:]]*no;" "$NAMED_CONF"; then
            
			print_info_green "DNS recursion Status" "DNS recursion is Disabled"
			printf "\n"
        else
           
			print_info_red_to_file "DNS recursion Status" "DNS recursion is Enabled. Recommend to disable it."
			printf "\n"
            # You can add commands here to disable recursion if needed.
        fi
    fi
else
    print_info_green1 "DNS recursion Check" "DNS configuration file not found. Skipping "
fi
printf "\n"
sleep 1
# Check if the /usr/local/lsws/ directory exists
if [ -e "/usr/local/cpanel/cpanel" ]; then

if [ -d "/usr/local/lsws/" ]; then
    print_info_green "cPanel LiteSpeed Plugin is installed ?" " Yes, cPanel LiteSpeed Plugin is installed"
	printf "\n"
	sleep 1
    
    # Check if LiteSpeed is running
    if systemctl is-active lsws > /dev/null 2>&1; then
        print_info_green "cPanel LiteSpeed  service status?" "cPanel LiteSpeed service is running."
    else
        print_info_red_to_file "cPanel LiteSpeed  service status?" "cPanel LiteSpeed Plugin is installed but not running."
    fi
else
    print_info_green "cPanel LiteSpeed Plugin is installed ?" "cPanel LiteSpeed Plugin is not installed on this server."
fi
fi
printf "\n"
sleep 1
## cPanel Security Check.

if [ -d "/usr/local/cpanel" ]; then

#WHM Terminal Enabled checking

terminal_disable_file="/var/cpanel/disable_whm_terminal_ui"

if [ -f "$terminal_disable_file" ]; then
   
	print_info_green "WHM Terminal Status " "Disabled"
else
    
	print_info_red_to_file "WHM Terminal Status " "Enabled, Recommend to disable it "
fi
printf "\n"
## cPHulk Brute Force Protection Check

sleep 1

cphulk_status_output=$(/usr/local/cpanel/scripts/restartsrv_cphulkd --status)

if [[ $cphulk_status_output == *"is running"* ]]; then
   
	print_info_green "cPHulk Brute Force Protection Status " "Enabled & Running"
else
 
	print_info_red_to_file "cPHulk Brute Force Protection Status " "Disabled"
fi

fi
##
sleep 2
printf "\n"

# Check if rkhunter executable is available
if [ -x "$(command -v rkhunter)" ]; then
    print_info_green "RKHunter RootKit Scanner is installed?" "Yes"
	printf "\n"
	sleep 2
	# Ask for confirmation
read -p "Do you want to run RKHunter Scan to see if there is any Warning? (yes/no): " choice
case "$choice" in 
  yes|YES|y|Y)
  printf "\n"
  print_info_green1 "The RKHunter Scan just shows only Warning here if there is anything. The scan may take some time. Hence, Please be patient."
  printf "\n"
  print_info_red1_to_file "Please review the RKHunter scanning result and do the needful on the server." 
    # User confirmed, run RKHunter
    rkhunter -c --rwo
    ;;
  no|NO|n|N)
  printf "\n"
    print_info_red1 "RKHunter Scan has been cancelled"
    ;;
  *)
    print_info_red1 "Invalid choice. Please enter 'yes' or 'no'"
    ;;
esac
else
    #echo "RKHunter is not installed."
	print_info_red_to_file "RKHunter RootKit Scanner is installed?" "No , Recommend to install and run a rootkit scan"
fi
printf "\n"
sleep 2
# Check if LMD (Linux Malware Detect) or maldet is installed
if [ -x "$(command -v maldet)" ]; then
    #echo "LMD (Linux Malware Detect) or maldet is installed on this system."
	print_info_green "LMD (Linux Malware Detect) or maldet is installed on this system?" "Yes"
    printf "\n"
	sleep 1
    # Check if LMD/maldet is currently enabled
    if [ -f /usr/local/maldetect/conf.maldet ]; then
        if grep -q "enabled_scan=\"1\"" /usr/local/maldetect/conf.maldet; then
            
			print_info_green "LMD/maldet Scan Status in the configuration file" "Enabled"
        else
           
			print_info_red_to_file "LMD/maldet Scan Status in the configuration file /usr/local/maldetect/conf.maldet" "LMD/maldet is installed but not enabled."
            
        fi
    else
        
		print_info_red_to_file "LMD/maldet Scan Status in the configuration file" "LMD/maldet is installed but the configuration file /usr/local/maldetect/conf.maldet is missing."
    fi
else
    
    print_info_red_to_file "LMD (Linux Malware Detect) or maldet is installed on this system?" "LMD (Linux Malware Detect) or maldet is not installed on this system."
fi
printf "\n"
sleep 2
# Check for the presence of /var/log/messages and /var/log/syslog
if [ -f /var/log/messages ]; then
    # Check for "Out of memory" events in /var/log/messages
    if grep -q "Out of memory" /var/log/messages; then
        print_info_red_to_file "Any Out of memory (OOM) detection in the system?" "Yes, Found OOM in the system log, please check if there is any memory constraints"
    else
        
		print_info_green "Any Out of memory (OOM) detection in the system?" "No, OOM not found in the server"
    fi
elif [ -f /var/log/syslog ]; then
    # Check for "Out of memory" events in /var/log/syslog
    if grep -q "Out of memory" /var/log/syslog; then
        print_info_red_to_file "Any Out of memory (OOM) detection in the system?" "Yes, Found OOM in the system log, please check if there is any memory constraints"
    else
        print_info_green "Any Out of memory (OOM) detection in the system?" "No, OOM not found in the server"
    fi
else
    print_info_red_to_file "Any Out of memory (OOM) detection in the system?" "Neither /var/log/messages nor /var/log/syslog found."
fi
printf "\n"
sleep 2
# Function to check the mail queue count and print a warning if it's above a threshold
check_mail_queue() {
    local queue_count=$1
    #echo "Mail Queue Count: $queue_count"
	print_info_green "Mail Queue Count" "$queue_count"
	sleep 1
	printf "\n"
    if [ "$queue_count" -gt 100 ]; then
        #echo "WARNING: Mail queue count is above 100. There may be email delivery issues."
		print_info_red_to_file "Mail Queue Count" "Mail queue count is above 100. There may be email delivery issues. Please check logs."
    else
        #echo "Mail queue count is within the acceptable range."
		print_info_green1 " " "Mail queue count is within the acceptable range."
    fi
}
# Check the server environment and determine the appropriate command to check the mail queue
if [ -x "$(command -v exim)" ]; then
    # Check if it's cPanel or DirectAdmin (assumes exim is used)
    if [ -d "/etc/exim" ]; then
        queue_count=$(exim -bpc)
        check_mail_queue "$queue_count"
    fi
elif [ -x "$(command -v mailq)" ]; then
    # Check if it's Linux Plesk (assumes mailq command is used)
    if [ -d "/var/qmail" ]; then
        queue_count=$(mailq | tail -n +2 | wc -l)
        check_mail_queue "$queue_count"
    fi
elif [ -x "$(command -v postqueue)" ]; then
    # Check if it's Linux Plesk (assumes postqueue command is used)
    if [ -d "/var/spool/postfix" ]; then
        queue_count=$(postqueue -p | tail -n +2 | wc -l)
        check_mail_queue "$queue_count"
    fi
else
    print_info_red1 "Mail Queue Count"  "Unable to determine the server environment or mail queue command is not available."
fi
printf "\n"
sleep 2
# Check CSI for cPanel
    if [ -e "/usr/local/cpanel/cpanel" ]; then
	
	read -p "Do you want to run cPanel's malware scanner CSI script? (yes/no): " choice1
case "$choice1" in 
  yes|YES|y|Y)
  printf "\n"
  print_info_green1 "cPanel's malware scanner CSI script to do an overall scan of a server for malware. Here, we perform quick scan. The scan may take some time. Hence, Please be patient."
  printf "\n"
  print_info_red1_to_file "Please review the cPanel CSI scanning result and do the needful on the server." 
    # User confirmed, run RKHunter
    cpanel_csi_script="/usr/local/cpanel/3rdparty/bin/perl <(curl -s https://raw.githubusercontent.com/CpanelInc/tech-CSI/master/csi.pl)"
	bash -c "$cpanel_csi_script"
    ;;
  no|NO|n|N)
  printf "\n"
    print_info_red1 "cPanel's malware scanner CSI script has been cancelled."
    ;;
  *)
    print_info_red1 "Invalid choice. Please enter 'yes' or 'no'."
    ;;
esac
fi
printf "\n\n\n"
sleep 2
### Additional cPanel Security Settings ##
if [ -e "/usr/local/cpanel/cpanel" ]; then
printf "\033[1m         		Additional cPanel/WHM Security Settings \033[0m \n" 
printf "			====================================== \n" 
printf "\n\n" >> "$AUDIT_FILE"
printf "\033[1m         		Additional cPanel/WHM Security Settings \033[0m \n"  >> "$AUDIT_FILE"
printf "			====================================== \n" >> "$AUDIT_FILE"
printf "\n\n" >> "$AUDIT_FILE"
printf "\n\n"
sleep 1
print_info_red1_to_file "a). Visit WHM >> Security Center >> Run cPanel Security Advisor and enable all recommendations"
printf "\n"
sleep 1
print_info_red1_to_file "b). Visit WHM >> Security Center >> Enable mod_userdir Protection"
printf "\n"
sleep 1
print_info_red1_to_file "c). Visit WHM >> Security Center >> Enable SMTP Restrictions"
printf "\n"
sleep 1
print_info_red1_to_file "d). Visit WHM >> Security Center >> Disable Compiler Access"
printf "\n"
sleep 1
print_info_red1_to_file "e). Visit WHM >> Security Center >> Configure Security Policies"
printf "\n"
sleep 1
print_info_red1_to_file "f). Visit WHM >> Security Center >> Host Access Control to restrict WHM & SSH Port Access"
printf "\n"
sleep 1
print_info_red1_to_file "g). Visit WHM >> Security Center >> Enable OWASP ModSecurity Rule Set"
printf "\n"
sleep 1
print_info_red1_to_file "h). Visit WHM >> Security Center >> Enable Shell Fork Bomb Protection"
printf "\n"
sleep 1
print_info_red1_to_file "i). Visit WHM >> Security Center >> Enable Shell Fork Bomb Protection"
printf "\n"
sleep 1
print_info_red1_to_file "j). Visit WHM >> Service Configuration >> Apache Configuration >> Global Configuration >> Enable Symlink Protection & Keep-Alive settings"
printf "\n"
sleep 1
print_info_red1_to_file "k). Visit WHM >> Service Configuration >> Exim Configuration Manager >> Enable Dictionary attack protection"
printf "\n"
sleep 1
print_info_red1_to_file "l). Visit WHM >> Service Configuration >> Exim Configuration Manager >> Enable Reject remote mail sent to the server's hostname"
printf "\n"
sleep 1
print_info_red1_to_file "m). Visit WHM >> Service Configuration >> Exim Configuration Manager >> Enable Reference /etc/mailips for custom IP on outgoing SMTP connections"
printf "\n"
sleep 1
print_info_red1_to_file "n). Visit WHM >> Service Configuration >> Exim Configuration Manager >> Enable System Filter File"
printf "\n"
sleep 1
print_info_red1_to_file "o). Visit WHM >> Service Configuration >> Exim Configuration Manager >> Enable Set SMTP Sender: headers"
printf "\n"
sleep 1
print_info_red1_to_file "p). Visit WHM >> Service Configuration >> Exim Configuration Manager >> Enable Custom RBLs"
printf "\n"
sleep 1
print_info_red1_to_file "q). Visit WHM >> Service Configuration >> Exim Configuration Manager >> Scan outgoing messages for malware"
printf "\n"
sleep 1
print_info_red1_to_file "r). Visit WHM >> Service Configuration >> FTP Server Configuration >> Disable Allow Anonymous Logins & Allow Anonymous Uploads"
printf "\n"
sleep 1
print_info_red1_to_file "s). Visit WHM >> Service Configuration >> FTP Server Configuration >> Disable Allow Logins with Root Password"
printf "\n"
sleep 1
print_info_red1_to_file "t). Visit WHM >> SSL/TLS >> Manage AutoSSL >> Enable autoSSL for all users"
printf "\n"
sleep 1
print_info_red1_to_file "v). Visit WHM >> System Health >> Enable Background Process Killer"
printf "\n"
sleep 1
print_info_red1_to_file "w). Visit WHM >> Plugins >> ConfigServer Security & Firewall >> Perform Check Server Security and do the needful changes"
printf "\n"
sleep 1
print_info_red1_to_file "x). Visit WHM >> Server Configuration >> Tweak Settings >> Enable DKIM & SPF on domains for newly created accounts"
printf "\n"
sleep 1
print_info_red1_to_file "y). Visit WHM >> Server Configuration >> Tweak Settings >> Set Max hourly emails per domain"
printf "\n"
sleep 1
print_info_red1_to_file "Z). Visit WHM >> Server Configuration >> Tweak Settings >> Set Initial default/catch-all forwarder destination to Fail"
printf "\n"
sleep 1
print_info_red1_to_file "aa). Visit WHM >> Server Configuration >> Tweak Settings >> Enable Track email origin via X-Source email headers "
printf "\n"
sleep 1
print_info_red1_to_file "bb). Visit WHM >> Server Configuration >> Tweak Settings >> Enable Restrict outgoing SMTP to root, exim, and mailman"
printf "\n"
sleep 1
print_info_red1_to_file "cc). Visit WHM >> Server Configuration >> Tweak Settings >> Enable Prevent “nobody” from sending mail"
printf "\n"
sleep 1
print_info_red1_to_file "dd). Visit WHM >> Server Configuration >> Tweak Settings >> Enable Apache SpamAssassin spam filter"
printf "\n"
sleep 1
print_info_red1_to_file "ee). Visit WHM >> Server Configuration >> Tweak Settings >> Enable Blank referrer safety check & Referrer safety check"

fi
printf "\n"
sleep 2
#printf "\033[1m Audit report has been generated and saved to $OUTPUT_FILE. \033[0m \n"
printf "\n\n"
printf "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"
printf "\033[1m The Scan has completed. Please review the output and take necessary actions based on this. \033[0m \n"
printf "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"
sleep 2
printf "\n\n"

printf "${BOLD}${YELLOW} Printing Audit Report Summary .......  \n"
printf "\n"
printf "\n"
printf "\n"
sleep 3

cat "$AUDIT_FILE"
rm -rf "$AUDIT_FILE"
printf "\n\n"
sleep 1
printf "\033[1m         	Please Review The Audit Report Summary and Do The Needful \033[0m \n" 
sleep 1
printf "\n"
printf "\033[1m         	Thank You! \033[0m \n"
sleep 1
printf "\n\n"

### END OF THE SCRIPT ###
