#!/bin/sh # # Linux kernel hardening script # Reference: https://madaidans-insecurities.github.io/guides/linux-hardening.html # Create the sysctl configuration file for hardened settings SYSCTL_CONFIG="${SYSCTL_CONFIG:-/etc/sysctl.conf}" # Kernel protections apply_kernel_protections() { echo "Applying kernel hardening settings..." cat >> "$SYSCTL_CONFIG" << EOF # Kernel pointer restrictions kernel.kptr_restrict=2 # Restrict access to kernel logs kernel.dmesg_restrict=1 kernel.printk=3 3 3 3 # BPF restrictions kernel.unprivileged_bpf_disabled=1 net.core.bpf_jit_harden=2 # Miscellaneous kernel hardening dev.tty.ldisc_autoload=0 vm.unprivileged_userfaultfd=0 kernel.kexec_load_disabled=1 kernel.sysrq=4 kernel.perf_event_paranoid=2 EOF } # Network protections apply_network_protections() { echo "Applying network hardening settings..." cat >> "$SYSCTL_CONFIG" << EOF # TCP/SYN flood protection net.ipv4.tcp_syncookies=1 # TIME-WAIT assassination protection net.ipv4.tcp_rfc1337=1 # IP spoofing protection (commented-out due to performance concerns) # net.ipv4.conf.all.rp_filter=1 # net.ipv4.conf.default.rp_filter=1 # ICMP redirect protection 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 net.ipv4.conf.all.send_redirects=0 net.ipv4.conf.default.send_redirects=0 # Ignore ICMP requests; Smurf mitigation net.ipv4.icmp_echo_ignore_all=1 # Disable IPv6 router advertisements net.ipv6.conf.all.accept_ra=0 net.ipv6.conf.default.accept_ra=0 # Disable TCP SACK net.ipv4.tcp_sack=0 net.ipv4.tcp_dsack=0 net.ipv4.tcp_fack=0 EOF } # Userspace protections apply_userspace_protections() { echo "Applying userspace hardening settings..." cat >> "$SYSCTL_CONFIG" << EOF # Restrict ptrace to CAP_SYS_PTRACE kernel.yama.ptrace_scope=2 EOF } # Main apply_kernel_protections apply_network_protections apply_userspace_protections echo "Hardening complete. Settings written to $SYSCTL_CONFIG" # Apply settings immediately sysctl -p "$SYSCTL_CONFIG"