***Script***A script to secure a Debian 12 installation

#!/bin/bash
# =========================================================================== #
# Description:      A script to secure a Debian 12 installation.
# Made for:           Linux, Cloudpanel (Debian & Ubuntu).
# Requirements:       ssh-keygen - ssh-copy-id root@127.0.0.1 (replace IP)
# Version:            0.1
# Make executable:    chmod +x security_hardening.sh
# Details:
#   1. Ensure the script is run as root.
#   2. Update and upgrade the system.
#   3. Install necessary security packages and tools.
#   4. Configure UFW (Uncomplicated Firewall) with default policies.
#   5. Secure SSH by disabling root login, password authentication, and changing the default port.
#   6. Configure and enable unattended upgrades.
#   7. Set up Fail2Ban for intrusion prevention.
#   8. Initialize and configure AIDE (Advanced Intrusion Detection Environment).
#   9. Enable and start AppArmor for application security.
#  10. Apply kernel hardening settings.
#  11. Enable and configure Logwatch for system log monitoring.
#  12. Provide instructions for securing GRUB manually.
#  13. Print reminders for BIOS/UEFI and physical security settings.
#  14. Disable the root account and create a non-root user.
#  15. Disable unused filesystems.
#  16. Restrict cron and at jobs to authorized users.
#  17. Ensure all users' home directories are private.
#  18. Set password expiration policies.
#  19. Install and configure RKHunter (Rootkit Hunter) for rootkit detection.
#  20. Install and configure ClamAV for antivirus protection.
#  21. Schedule regular ClamAV scans.
#
# Usage: sudo ./security_hardening.sh <username>
#
# NOTE: Some steps may require manual intervention as indicated in the script output.
# ------------------------------------------------------------------------------

set -e
LOGFILE="/var/log/security_hardening.log"
exec > >(tee -a ${LOGFILE}) 2>&1

# Ensure the script is run as root
if [ "$(id -u)" -ne 0 ]; then
  echo "This script must be run as root" >&2
  exit 1
fi

# Check if username is provided
if [ -z "$1" ]; then
  echo "Usage: $0 <username>"
  exit 1
fi

USERNAME="$1"

# Validate the username
if ! id -u "$USERNAME" > /dev/null 2>&1; then
  echo "The user $USERNAME does not exist, creating the user..."
  adduser "$USERNAME"
  usermod -aG sudo "$USERNAME"
else
  echo "User $USERNAME exists."
fi

# Update and upgrade the system
apt-get update && apt-get upgrade -y

# Ensure sudo is installed
if ! command -v sudo > /dev/null 2>&1; then
  apt-get install -y sudo
fi

# Install necessary packages
apt-get install -y ufw fail2ban apparmor apparmor-profiles unattended-upgrades logwatch aide apt-listchanges rkhunter clamav clamav-daemon at

# Configure UFW (Uncomplicated Firewall)
ufw default deny incoming
ufw default allow outgoing
ufw allow 2200/tcp  # Allow SSH on the custom port
ufw enable

# Configure SSH for security
sed -i 's/^#PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config
sed -i 's/^#PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config
sed -i 's/^#PubkeyAuthentication.*/PubkeyAuthentication yes/' /etc/ssh/sshd_config
sed -i 's/^#Port 22/Port 2200/' /etc/ssh/sshd_config  # Change SSH port to 2200
systemctl restart ssh

# Configure unattended upgrades
dpkg-reconfigure --priority=low unattended-upgrades

# Configure Fail2Ban for intrusion prevention
cat > /etc/fail2ban/jail.local <<EOF
[DEFAULT]
bantime = 1h
findtime = 10m
maxretry = 5

[sshd]
enabled = true
port = 2200
EOF
systemctl enable fail2ban
systemctl start fail2ban

# Initialize and configure AIDE (Advanced Intrusion Detection Environment)
aideinit
mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db
echo '0 5 * * * root /usr/bin/aide --check | mail -s "AIDE Integrity Check" admin@example.com' >> /etc/crontab

# Enable and start AppArmor for application security
systemctl enable apparmor
systemctl start apparmor

# Kernel hardening settings
cat >> /etc/sysctl.conf <<EOF
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.tcp_timestamps = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
kernel.randomize_va_space = 2
kernel.kptr_restrict = 2
kernel.dmesg_restrict = 1
kernel.sysrq = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
EOF
sysctl -p

# Create a systemd service file for Logwatch
cat > /etc/systemd/system/logwatch.service <<EOF
[Unit]
Description=Logwatch log analyzer
Documentation=man:logwatch(8)
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/sbin/logwatch --output mail --mailto admin@example.com --detail high

[Install]
WantedBy=multi-user.target
EOF

# Enable and start Logwatch service
systemctl enable logwatch.service

# Secure GRUB (manual step required)
echo 'For GRUB password setup, please manually add the following to /etc/grub.d/40_custom:'
echo 'set superusers="username"'
echo 'password_pbkdf2 username hash'
echo 'and then run update-grub.'

# Print reminder for BIOS/UEFI and physical security
echo "Remember to configure BIOS/UEFI password, disable USB boot, and lock down GRUB manually."

# Additional security recommendations
# Disable root account
passwd -l root

# Disable unused filesystems
cat >> /etc/modprobe.d/blacklist.conf <<EOF
install cramfs /bin/true
install freevxfs /bin/true
install jffs2 /bin/true
install hfs /bin/true
install hfsplus /bin/true
install squashfs /bin/true
install udf /bin/true
EOF

# Restrict cron jobs
chmod -R go-rwx /etc/cron.d /etc/cron.daily /etc/cron.hourly /etc/cron.monthly /etc/cron.weekly

# Restrict at jobs
if [ -d /var/spool/cron/atjobs ]; then
  chmod -R go-rwx /var/spool/cron/atjobs
fi
if [ -d /var/spool/cron/atspool ]; then
  chmod -R go-rwx /var/spool/cron/atspool
fi

# Ensure all users' home directories are private
for dir in /home/*/; do
  chmod 700 "$dir"
done

# Set password expiration policies
# cat >> /etc/login.defs <<EOF
# PASS_MAX_DAYS 90
# PASS_MIN_DAYS 10
# PASS_WARN_AGE 7
# EOF

# Install and configure rkhunter (Rootkit Hunter)
rkhunter --update
rkhunter --propupd
sed -i 's/^WEB_CMD=".*"/WEB_CMD=""/' /etc/rkhunter.conf
echo '0 3 * * * root /usr/bin/rkhunter --check --cronjob | mail -s "RKHunter Scan Report" admin@example.com' >> /etc/crontab

# Install and configure ClamAV (Antivirus)
systemctl enable clamav-freshclam
systemctl start clamav-freshclam
freshclam
systemctl enable clamav-daemon
systemctl start clamav-daemon

# Run a ClamAV scan once a week
echo '0 2 * * 0 root /usr/bin/clamscan -r / --exclude-dir="^/sys" --exclude-dir="^/proc" --exclude-dir="^/dev" --exclude-dir="^/run" --exclude-dir="^/mnt" --exclude-dir="^/media" --exclude-dir="^/lost+found" -i --log=/var/log/clamav/clamscan.log | mail -s "ClamAV Scan Report" admin@example.com' >> /etc/crontab

echo "Security hardening completed. Additional manual steps may be required."

exit 0