Kali Linux Security Hardening script

This is one of many projects where we will explore how to improve upon operating systems.

#!/bin/bash

# Kali Linux Advanced Security Hardening Script
# Run as root or with sudo

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${GREEN}================================================${NC}"
echo -e "${GREEN}Kali Linux Advanced Security Hardening Script${NC}"
echo -e "${GREEN}================================================${NC}\n"

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}Please run as root or with sudo${NC}"
    exit 1
fi

# Backup original configs
BACKUP_DIR="/root/security_backup_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"
echo -e "${YELLOW}[*] Creating backup directory: $BACKUP_DIR${NC}"

# === SYSTEM UPDATES ===
echo -e "\n${GREEN}[+] Updating system packages...${NC}"
apt update && apt upgrade -y
apt dist-upgrade -y

# === FIREWALL CONFIGURATION (UFW) ===
echo -e "\n${GREEN}[+] Configuring UFW firewall...${NC}"
apt install -y ufw
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw logging on
ufw logging high
ufw enable
systemctl enable ufw

# === FAIL2BAN INSTALLATION ===
echo -e "\n${GREEN}[+] Installing and configuring Fail2Ban...${NC}"
apt install -y fail2ban
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local 2>/dev/null || true

cat > /etc/fail2ban/jail.local <<EOF
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
destemail = root@localhost
sendername = Fail2Ban
action = %(action_mwl)s

[sshd]
enabled = true
port = ssh
logpath = /var/log/auth.log
maxretry = 3
bantime = 7200
EOF

systemctl enable fail2ban
systemctl restart fail2ban

# === SSH HARDENING ===
echo -e "\n${GREEN}[+] Hardening SSH configuration...${NC}"
cp /etc/ssh/sshd_config "$BACKUP_DIR/sshd_config.bak"

cat > /etc/ssh/sshd_config <<EOF
# Kali SSH Hardened Configuration
Port 22
Protocol 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

# Authentication
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
UsePAM yes

# Security options
X11Forwarding no
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
MaxAuthTries 3
MaxSessions 2
ClientAliveInterval 300
ClientAliveCountMax 2

# Logging
SyslogFacility AUTH
LogLevel VERBOSE

# Allowed users (customize as needed)
# AllowUsers your_username

# Ciphers and algorithms
Ciphers [email protected],[email protected],[email protected],aes256-ctr,aes192-ctr,aes128-ctr
MACs [email protected],[email protected],hmac-sha2-512,hmac-sha2-256
KexAlgorithms curve25519-sha256,[email protected],diffie-hellman-group-exchange-sha256
EOF

# === AUDITD INSTALLATION ===
echo -e "\n${GREEN}[+] Installing and configuring auditd...${NC}"
apt install -y auditd audispd-plugins

cat > /etc/audit/rules.d/hardening.rules <<EOF
# Audit rules for security monitoring
-w /etc/passwd -p wa -k passwd_changes
-w /etc/group -p wa -k group_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/sudoers -p wa -k sudoers_changes
-w /var/log/auth.log -p wa -k auth_log_changes
-w /var/log/faillog -p wa -k login_failures
-w /usr/bin/passwd -p x -k passwd_modification
-w /usr/bin/sudo -p x -k sudo_execution
-w /etc/ssh/sshd_config -p wa -k sshd_config_changes
-a always,exit -F arch=b64 -S adjtimex -S settimeofday -k time_change
-a always,exit -F arch=b32 -S adjtimex -S settimeofday -S stime -k time_change
EOF

augenrules --load
systemctl enable auditd
systemctl restart auditd

# === KERNEL HARDENING (SYSCTL) ===
echo -e "\n${GREEN}[+] Applying kernel hardening settings...${NC}"
cp /etc/sysctl.conf "$BACKUP_DIR/sysctl.conf.bak"

cat >> /etc/sysctl.conf <<EOF

# === Security Hardening Parameters ===
# IP Forwarding
net.ipv4.ip_forward = 0
net.ipv6.conf.all.forwarding = 0

# SYN Cookies
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_max_syn_backlog = 4096

# IP Spoofing protection
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# Ignore ICMP redirects
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.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0

# Ignore send redirects
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

# Disable source packet routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
net.ipv6.conf.default.accept_source_route = 0

# Log Martians
net.ipv4.conf.all.log_martians = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1

# Ignore ICMP ping requests
net.ipv4.icmp_echo_ignore_all = 0

# Ignore broadcasts
net.ipv4.icmp_echo_ignore_broadcasts = 1

# IPv6 hardening
net.ipv6.conf.all.accept_ra = 0
net.ipv6.conf.default.accept_ra = 0

# Kernel hardening
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
kernel.yama.ptrace_scope = 2
kernel.unprivileged_bpf_disabled = 1
kernel.unprivileged_userns_clone = 0

# File system hardening
fs.suid_dumpable = 0
fs.protected_hardlinks = 1
fs.protected_symlinks = 1
EOF

sysctl -p

# === APPARMOR ===
echo -e "\n${GREEN}[+] Enabling AppArmor...${NC}"
apt install -y apparmor apparmor-utils apparmor-profiles apparmor-profiles-extra
systemctl enable apparmor
systemctl start apparmor

# === INSTALL SECURITY TOOLS ===
echo -e "\n${GREEN}[+] Installing additional security tools...${NC}"
apt install -y \
    rkhunter \
    chkrootkit \
    lynis \
    aide \
    clamav \
    clamav-daemon \
    unattended-upgrades \
    needrestart \
    debsums

# === RKHUNTER CONFIGURATION ===
echo -e "\n${GREEN}[+] Configuring rkhunter...${NC}"
rkhunter --update
rkhunter --propupd

# === AIDE CONFIGURATION ===
echo -e "\n${GREEN}[+] Initializing AIDE database (this may take time)...${NC}"
aideinit
mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db 2>/dev/null || true

# === CLAMAV CONFIGURATION ===
echo -e "\n${GREEN}[+] Updating ClamAV definitions...${NC}"
systemctl stop clamav-freshclam 2>/dev/null || true
freshclam
systemctl start clamav-freshclam
systemctl enable clamav-freshclam

# === AUTOMATIC SECURITY UPDATES ===
echo -e "\n${GREEN}[+] Configuring automatic security updates...${NC}"
cat > /etc/apt/apt.conf.d/50unattended-upgrades <<EOF
Unattended-Upgrade::Allowed-Origins {
    "\${distro_id}:\${distro_codename}-security";
};
Unattended-Upgrade::AutoFixInterruptedDpkg "true";
Unattended-Upgrade::MinimalSteps "true";
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "false";
EOF

dpkg-reconfigure -plow unattended-upgrades

# === SECURE SHARED MEMORY ===
echo -e "\n${GREEN}[+] Securing shared memory...${NC}"
if ! grep -q "tmpfs /run/shm" /etc/fstab; then
    echo "tmpfs /run/shm tmpfs defaults,noexec,nosuid,nodev 0 0" >> /etc/fstab
fi

# === DISABLE UNNECESSARY SERVICES ===
echo -e "\n${GREEN}[+] Disabling unnecessary services...${NC}"
systemctl disable bluetooth.service 2>/dev/null || true
systemctl disable cups.service 2>/dev/null || true
systemctl disable avahi-daemon.service 2>/dev/null || true

# === FILE PERMISSIONS ===
echo -e "\n${GREEN}[+] Hardening file permissions...${NC}"
chmod 700 /root
chmod 600 /boot/grub/grub.cfg 2>/dev/null || true
chmod 644 /etc/passwd
chmod 644 /etc/group
chmod 600 /etc/shadow
chmod 600 /etc/gshadow
chmod 644 /etc/ssh/ssh_config
chmod 600 /etc/ssh/sshd_config

# === USB PROTECTION ===
echo -e "\n${GREEN}[+] Configuring USB storage protection...${NC}"
cat > /etc/modprobe.d/blacklist-usb.conf <<EOF
# Uncomment to disable USB storage
# install usb-storage /bin/true
EOF

# === SUDOERS HARDENING ===
echo -e "\n${GREEN}[+] Hardening sudoers configuration...${NC}"
cat > /etc/sudoers.d/security <<EOF
Defaults    env_reset
Defaults    secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Defaults    use_pty
Defaults    logfile="/var/log/sudo.log"
Defaults    timestamp_timeout=5
EOF

chmod 440 /etc/sudoers.d/security

# === NETWORK SECURITY ===
echo -e "\n${GREEN}[+] Installing network security tools...${NC}"
apt install -y \
    iptables-persistent \
    psad \
    portsentry

# Configure PSAD
sed -i 's/EMAIL_ADDRESSES.*/EMAIL_ADDRESSES root@localhost;/' /etc/psad/psad.conf
sed -i 's/HOSTNAME.*/HOSTNAME kali-hardened;/' /etc/psad/psad.conf
psad --sig-update
systemctl enable psad
systemctl restart psad

# === MAC ADDRESS RANDOMIZATION ===
echo -e "\n${GREEN}[+] Configuring MAC address randomization...${NC}"
cat > /etc/NetworkManager/conf.d/mac-randomization.conf <<EOF
[device]
wifi.scan-rand-mac-address=yes

[connection]
wifi.cloned-mac-address=random
ethernet.cloned-mac-address=random
EOF

# === FINAL SECURITY SCAN ===
echo -e "\n${GREEN}[+] Running Lynis security audit...${NC}"
lynis audit system --quick

# === SUMMARY ===
echo -e "\n${GREEN}================================================${NC}"
echo -e "${GREEN}Security Hardening Complete!${NC}"
echo -e "${GREEN}================================================${NC}\n"
echo -e "${YELLOW}Important Notes:${NC}"
echo -e "1. ${RED}SSH root login is DISABLED${NC}"
echo -e "2. ${RED}SSH password authentication is DISABLED${NC}"
echo -e "   - Configure SSH keys before logging out!"
echo -e "3. UFW firewall is enabled with default deny"
echo -e "4. Fail2Ban is active and monitoring"
echo -e "5. Backups saved to: $BACKUP_DIR"
echo -e "6. Review /var/log/lynis.log for additional recommendations"
echo -e "\n${YELLOW}Recommended Next Steps:${NC}"
echo -e "- Set up SSH keys for your user"
echo -e "- Configure UFW to allow necessary ports"
echo -e "- Review and customize SSH AllowUsers directive"
echo -e "- Schedule regular security scans with lynis/rkhunter"
echo -e "- Test all services before rebooting"
echo -e "\n${RED}A reboot is recommended to apply all changes${NC}\n"

Leave a Reply

Your email address will not be published. Required fields are marked *