harden-sysctls.sh

· bash's pastes · raw

expires: 2025-07-22

 1#!/bin/sh
 2#
 3# Linux kernel hardening script
 4# Reference: https://madaidans-insecurities.github.io/guides/linux-hardening.html
 5
 6# Create the sysctl configuration file for hardened settings
 7SYSCTL_CONFIG="${SYSCTL_CONFIG:-/etc/sysctl.conf}"
 8
 9# Kernel protections
10apply_kernel_protections() {
11    echo "Applying kernel hardening settings..."
12
13    cat >> "$SYSCTL_CONFIG" << EOF
14# Kernel pointer restrictions
15kernel.kptr_restrict=2
16
17# Restrict access to kernel logs
18kernel.dmesg_restrict=1
19kernel.printk=3 3 3 3
20
21# BPF restrictions
22kernel.unprivileged_bpf_disabled=1
23net.core.bpf_jit_harden=2
24
25# Miscellaneous kernel hardening
26dev.tty.ldisc_autoload=0
27vm.unprivileged_userfaultfd=0
28kernel.kexec_load_disabled=1
29kernel.sysrq=4
30kernel.perf_event_paranoid=2
31EOF
32}
33
34# Network protections
35apply_network_protections() {
36    echo "Applying network hardening settings..."
37
38    cat >> "$SYSCTL_CONFIG" << EOF
39# TCP/SYN flood protection
40net.ipv4.tcp_syncookies=1
41
42# TIME-WAIT assassination protection
43net.ipv4.tcp_rfc1337=1
44
45# IP spoofing protection (commented-out due to performance concerns)
46# net.ipv4.conf.all.rp_filter=1
47# net.ipv4.conf.default.rp_filter=1
48
49# ICMP redirect protection
50net.ipv4.conf.all.accept_redirects=0
51net.ipv4.conf.default.accept_redirects=0
52net.ipv4.conf.all.secure_redirects=0
53net.ipv4.conf.default.secure_redirects=0
54net.ipv6.conf.all.accept_redirects=0
55net.ipv6.conf.default.accept_redirects=0
56net.ipv4.conf.all.send_redirects=0
57net.ipv4.conf.default.send_redirects=0
58
59# Ignore ICMP requests; Smurf mitigation
60net.ipv4.icmp_echo_ignore_all=1
61
62# Disable IPv6 router advertisements
63net.ipv6.conf.all.accept_ra=0
64net.ipv6.conf.default.accept_ra=0
65
66# Disable TCP SACK
67net.ipv4.tcp_sack=0
68net.ipv4.tcp_dsack=0
69net.ipv4.tcp_fack=0
70EOF
71}
72
73# Userspace protections
74apply_userspace_protections() {
75    echo "Applying userspace hardening settings..."
76
77    cat >> "$SYSCTL_CONFIG" << EOF
78# Restrict ptrace to CAP_SYS_PTRACE
79kernel.yama.ptrace_scope=2
80EOF
81}
82
83# Main
84apply_kernel_protections
85apply_network_protections
86apply_userspace_protections
87
88echo "Hardening complete. Settings written to $SYSCTL_CONFIG"
89
90# Apply settings immediately
91sysctl -p "$SYSCTL_CONFIG"