Advertisement
Sweetening

harden.sh

Jun 26th, 2025
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 15.89 KB | None | 0 0
  1. #!/bin/bash
  2. #
  3. # ==================================================================================
  4. #      // USCYBERCOM FINAL UNIFIED DIRECTIVE: PROJECT CITADEL //
  5. # ==================================================================================
  6. #
  7. # CLASSIFICATION:      TS//SI//REL TO FVEY
  8. # OPERATION:           Definitive Synthesis of Hardening & C2 Deployment Protocols
  9. # TARGET PLATFORM:     Debian 12 (Bookworm) - High-Value Asset
  10. # LEAD:                Taylor Christian Newsome (ClumsyLulz)
  11. # REVISION:            8.0.0 (Citadel Final)
  12. #
  13. # PURPOSE: This directive represents the definitive synthesis of all previously
  14. # discussed protocols (BLACKSITE, GHOSTWRITER, AEGIS, OMNIBUS). It is a
  15. # fully automated, non-interactive "fire-and-forget" system for elevating a
  16. # stock Debian 12 installation to a national security framework standard. It
  17. # executes a multi-layered defense-in-depth lockdown, neutralizes potential
  18. # backdoors via a Zero-Trust network policy, deploys a comprehensive audit and
  19. # deception framework, and establishes a secure command channel. Upon completion,
  20. # it provides the operator with credentials and instructions for the final security
  21. # lockdown. This is the one script needed.
  22. #
  23. # EXECUTION: Run as root on a fresh Debian 12 system. No user input is required.
  24. #
  25.  
  26. # --- PRE-FLIGHT CHECKS ---
  27. set -euo pipefail
  28. if [[ "$(id -u)" -ne 0 ]]; then
  29.     echo -e "\n[FATAL] Directive requires root privileges. Execution denied." >&2; exit 1
  30. fi
  31. if ! grep -qi "bookworm" /etc/os-release; then
  32.     echo -e "\n[FATAL] This directive is tuned specifically for Debian 12 (Bookworm). Aborting." >&2; exit 1
  33. fi
  34.  
  35. # --- SCRIPT INITIALIZATION ---
  36. export DEBIAN_FRONTEND=noninteractive
  37. LOG_FILE="/var/log/project_citadel_run_$(date +%Y%m%d_%H%M%S).log"
  38. exec > >(tee -i "$LOG_FILE")
  39. exec 2>&1
  40.  
  41. # Helper functions
  42. log() { echo -e "[\033[1;36mCITADEL\033[0m] $1"; }
  43. warn() { echo -e "[\033[1;33mWARN\033[0m] $1"; }
  44. success() { echo -e "[\033[1;32mSUCCESS\033[0m] $1"; }
  45. op() { echo -e "\n[\033[1;35m==> OPERATION\033[0m] \033[1m$1\033[0m"; }
  46.  
  47. # ==================================================================================
  48. #                           DIRECTIVE EXECUTION
  49. # ==================================================================================
  50. clear
  51. echo "==========================================================================="
  52. echo "   USCYBERCOM FINAL UNIFIED DIRECTIVE: PROJECT CITADEL"
  53. echo "   Initiating fully automated, comprehensive system lockdown."
  54. echo "==========================================================================="
  55. sleep 1
  56.  
  57. op "Phase 1: System Baseline & Comprehensive Security Toolkit Installation"
  58. log "Updating package repositories and applying all security patches..."
  59. apt-get update && apt-get -y full-upgrade && apt-get -y dist-upgrade
  60.  
  61. log "Installing comprehensive security, auditing, and dependency toolkit..."
  62. apt-get -y install auditd audispd-plugins aide logwatch fail2ban apparmor apparmor-utils \
  63.   usbguard tpm2-tools nftables net-tools dnscrypt-proxy debsums curl git make gnupg2 \
  64.   rsyslog sudo lsof ipset systemd-timesyncd bpfcc-tools acct busybox cron bash-completion \
  65.   libpam-pwquality libpam-tmpdir needrestart python3 openssl lynis chkrootkit \
  66.   rkhunter apt-listchanges apt-transport-https ca-certificates dnsutils
  67.  
  68. op "Phase 2: Integrity, Boot Security, and Unattended Upgrades"
  69. if ! grep -q 'crypt' /etc/crypttab; then
  70.     warn "LUKS Full Disk Encryption not detected. This is a critical vulnerability for physical access."
  71. else
  72.     success "LUKS Full Disk Encryption detected."
  73. fi
  74. if tpm2_getcap properties-fixed 2>/dev/null | grep -q TPM2_PT_MANUFACTURER; then
  75.     success "TPM 2.0 module detected. Measured boot integrity is active."
  76. else
  77.     warn "No TPM 2.0 module detected. Hardware-based root of trust is not available."
  78. fi
  79.  
  80. log "Configuring automatic unattended security upgrades..."
  81. cat <<EOF > /etc/apt/apt.conf.d/20auto-upgrades
  82. APT::Periodic::Update-Package-Lists "1";
  83. APT::Periodic::Unattended-Upgrade "1";
  84. APT::Periodic::AutocleanInterval "7";
  85. EOF
  86.  
  87. log "Initializing AIDE database for file integrity monitoring..."
  88. aideinit && cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db
  89.  
  90. log "Securing GRUB bootloader against unauthorized modification and recovery..."
  91. sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="lockdown=integrity quiet /' /etc/default/grub
  92. echo "GRUB_DISABLE_RECOVERY=true" >> /etc/default/grub
  93. update-grub
  94.  
  95. log "Verifying package integrity against official repository manifests..."
  96. debsums --changed > /var/log/debsums_changed.log || true
  97. if [[ -s /var/log/debsums_changed.log ]]; then
  98.     warn "Potential supply chain compromise! Review /var/log/debsums_changed.log"
  99. else
  100.     success "Package integrity verification passed."
  101. fi
  102.  
  103. op "Phase 3: Kernel, Filesystem, and Scheduler Hardening"
  104. log "Applying kernel hardening parameters via sysctl..."
  105. cat <<EOF > /etc/sysctl.d/99-citadel-hardening.conf
  106. kernel.kptr_restrict=2
  107. kernel.dmesg_restrict=1
  108. kernel.randomize_va_space=2
  109. kernel.unprivileged_bpf_disabled=1
  110. user.max_user_namespaces=0
  111. net.ipv4.tcp_syncookies=1
  112. net.ipv4.conf.all.rp_filter=1
  113. net.ipv4.conf.all.accept_source_route=0
  114. net.ipv4.conf.all.accept_redirects=0
  115. net.ipv4.conf.all.log_martians=1
  116. net.ipv6.conf.all.disable_ipv6=1
  117. net.ipv6.conf.default.disable_ipv6=1
  118. fs.suid_dumpable=0
  119. EOF
  120. sysctl --system
  121.  
  122. log "Applying immediate, non-persistent mount hardening..."
  123. mount -o remount,ro /boot
  124. mount -o remount,nodev,noexec,nosuid /tmp
  125. mount -o remount,nodev,noexec,nosuid /var/tmp
  126. mount -o remount,nodev,noexec,nosuid /dev/shm
  127. log "Making temporary filesystem hardening persistent in /etc/fstab..."
  128. sed -i -e '/\/boot/ s/defaults/defaults,ro/' /etc/fstab
  129. echo "tmpfs /tmp tmpfs defaults,rw,nosuid,nodev,noexec,relatime 0 0" >> /etc/fstab
  130. echo "tmpfs /dev/shm tmpfs defaults,rw,nosuid,nodev,noexec,relatime 0 0" >> /etc/fstab
  131.  
  132. log "Locking down cron directories..."
  133. chmod 700 /etc/crontab /etc/cron.*
  134.  
  135. op "Phase 4: Attack Surface Reduction & Active Defense"
  136. log "Blacklisting unnecessary kernel modules..."
  137. cat <<EOF > /etc/modprobe.d/citadel-blacklist.conf
  138. install cramfs /bin/true; install udf /bin/true; install hfs /bin/true
  139. install hfsplus /bin/true; install freevxfs /bin/true; install jffs2 /bin/true
  140. install squashfs /bin/true; install usb-storage /bin/true; install firewire-core /bin/true
  141. EOF
  142. update-initramfs -u
  143.  
  144. log "Purging unnecessary and high-risk services..."
  145. SERVICES_TO_PURGE=(snapd lxd avahi-daemon bluetooth cups rpcbind nfs-kernel-server isc-dhcp-server)
  146. for svc in "${SERVICES_TO_PURGE[@]}"; do
  147.   if systemctl list-unit-files | grep -q "$svc.service"; then
  148.     systemctl disable --now "$svc" &>/dev/null || true; apt-get -y purge "$svc" &>/dev/null || true
  149.   fi
  150. done
  151. apt-get -y autoremove
  152.  
  153. log "Deploying honeypot user and generating USBGuard policy..."
  154. useradd -r -s /usr/sbin/nologin oracle-svc || true
  155. usbguard generate-policy > /etc/usbguard/rules.conf
  156. systemctl enable --now usbguard
  157.  
  158. log "Enabling process accounting and brute-force protection..."
  159. systemctl enable --now acct
  160. systemctl enable --now fail2ban
  161.  
  162. op "Phase 5: Zero-Trust Network Fortress"
  163. DEBIAN_REPOS_IPS=$(dig +short security.debian.org deb.debian.org | grep -E '^[0-9]' | tr '\n' ' ' || echo "151.101.246.132 199.232.162.132")
  164. C2_PORT=443
  165. log "Deploying Zero-Trust firewall. All outbound traffic will be blocked by default."
  166. cat <<EOF > /etc/nftables.conf
  167. flush ruleset
  168. table inet filter {
  169.     set debian_repos { type ipv4_addr; flags interval; elements = { ${DEBIAN_REPOS_IPS} }; }
  170.     chain input {
  171.         type filter hook input priority 0; policy drop;
  172.         iif lo accept; ct state established,related accept;
  173.         tcp dport ${C2_PORT} accept; # Allow C2 from anywhere initially. Operator will lock this down.
  174.         log prefix "[NFT_DROP_INPUT] " level info drop
  175.     }
  176.     chain forward { type filter hook forward priority 0; policy drop; }
  177.     chain output {
  178.         type filter hook output priority 0; policy drop;
  179.         oif lo accept; ct state established,related accept;
  180.         udp dport { 53, 123 } accept; tcp dport { 80, 443 } ip daddr @debian_repos accept;
  181.         tcp sport ${C2_PORT} accept;
  182.         log prefix "[NFT_DROP_OUTPUT] " level info drop
  183.     }
  184. }
  185. EOF
  186. systemctl enable --now nftables
  187.  
  188. op "Phase 6: Audit, Surveillance, and C2 Framework"
  189. log "Deploying persistent auditd rules mapped to MITRE ATT&CK TTPs..."
  190. cat <<EOF > /etc/audit/rules.d/99-citadel-rules.rules
  191. -w /etc/shadow -p wa -k cred_dump
  192. -w /etc/passwd -p wa -k cred_dump
  193. -w /usr/sbin/useradd -p x -k acct_mgmt
  194. -w /usr/sbin/usermod -p x -k acct_mgmt
  195. -w /usr/sbin/groupadd -p x -k acct_mgmt
  196. -w /usr/bin/sudo -p x -k priv_escalation
  197. -w /bin/su -p x -k priv_escalation
  198. -w /etc/audit/ -p wa -k defense_tamper
  199. -w /etc/apparmor.d/ -p wa -k defense_tamper
  200. -w /etc/nftables.conf -p wa -k defense_tamper
  201. -a always,exit -F arch=b64 -S init_module,finit_module,delete_module -k kernel_manip
  202. -w /usr/bin/history -p x -k indicator_removal
  203. -a always,exit -F arch=b64 -S execve,execveat -k exec_telemetry
  204. EOF
  205. systemctl restart auditd
  206.  
  207. log "Enabling persistent journald logging and configuring encrypted DNS..."
  208. sed -i -e 's/^#?Storage=.*/Storage=persistent/' -e 's/^#?Compress=.*/Compress=yes/' /etc/systemd/journald.conf
  209. sed -i "s/^# server_names = .*/server_names = ['quad9-doh-ip4-filter-pri']/" /etc/dnscrypt-proxy/dnscrypt-proxy.toml
  210. sed -i "s/^# listen_addresses = .*/listen_addresses = ['127.0.2.1:53']/" /etc/dnscrypt-proxy/dnscrypt-proxy.toml
  211. echo "nameserver 127.0.2.1" > /etc/resolv.conf
  212. systemctl daemon-reload && systemctl restart systemd-journald dnscrypt-proxy.service
  213.  
  214. log "Enabling bash forensic logging for all users..."
  215. mkdir -p /var/log/bashlog && chmod 733 /var/log/bashlog
  216. cat <<EOF > /etc/profile.d/bash_forensics.sh
  217. export PROMPT_COMMAND='history -a >(tee -a /var/log/bashlog/\$(whoami)_\$(date +%Y%m%d).log)' 2>/dev/null
  218. EOF
  219.  
  220. log "Generating C2 credentials and deploying listener..."
  221. C2_DISPATCH_CODE=$(openssl rand -hex 16)
  222. C2_SCRIPT_PATH="/opt/citadel_c2.py"
  223. mkdir -p /etc/ssl/private
  224. openssl req -x509 -newkey rsa:4096 -keyout /etc/ssl/private/citadel.key -out /etc/ssl/certs/citadel.pem -days 3650 -nodes -subj "/CN=internal.localhost" &>/dev/null
  225. cat << EOF > "${C2_SCRIPT_PATH}"
  226. import http.server, ssl, json, subprocess
  227. HOST, PORT, CODE = '0.0.0.0', ${C2_PORT}, "${C2_DISPATCH_CODE}"
  228. class C2(http.server.BaseHTTPRequestHandler):
  229.     def _r(self,c,d): self.send_response(c); self.send_header('Content-type','application/json'); self.end_headers(); self.wfile.write(json.dumps(d).encode())
  230.     def do_POST(self):
  231.         if self.headers.get('X-Citadel-Dispatch-Code') != CODE: return self._r(403,{'error':'auth denied'})
  232.         try: cmd = json.loads(self.rfile.read(int(self.headers['Content-Length']))).get('cmd'); res = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=60); self._r(200, {'out':res.stdout,'err':res.stderr,'rc':res.returncode})
  233.         except Exception as e: self._r(500, {'error': str(e)})
  234. httpd=http.server.HTTPServer((HOST,PORT),C2); httpd.socket=ssl.wrap_socket(httpd.socket,keyfile="/etc/ssl/private/citadel.key",certfile="/etc/ssl/certs/citadel.pem",server_side=True)
  235. httpd.serve_forever()
  236. EOF
  237. chmod +x "${C2_SCRIPT_PATH}"
  238.  
  239. op "Phase 7: Access Control, Sandboxing, and Final Lockdown"
  240. log "Applying intelligence-grade SSHD configuration..."
  241. sed -i -e 's/^#?PermitRootLogin.*/PermitRootLogin no/' -e 's/^#?PasswordAuthentication.*/PasswordAuthentication no/' -e 's/^#?KbdInteractiveAuthentication.*/KbdInteractiveAuthentication no/' -e 's/^#?UsePAM.*/UsePAM yes/' -e 's/^#?X11Forwarding.*/X11Forwarding no/' -e 's/^#?MaxAuthTries.*/MaxAuthTries 2/' /etc/ssh/sshd_config
  242. echo -e "\nCiphers [email protected],[email protected]\nMACs [email protected]\nKexAlgorithms [email protected]" >> /etc/ssh/sshd_config
  243. systemctl restart sshd
  244.  
  245. log "Strengthening PAM, user limits, and password policies..."
  246. sed -i '1i auth optional pam_faildelay.so delay=8000000' /etc/pam.d/common-auth
  247. sed -i 's/^password\s\+requisite\s\+pam_pwquality.*/password requisite pam_pwquality.so retry=3 minlen=18 difok=5 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1 enforce_for_root/' /etc/pam.d/common-password
  248. cat <<EOF > /etc/security/limits.d/99-citadel-limits.conf
  249. * hard core 0
  250. * hard nproc 1000
  251. * hard nofile 4096
  252. root hard nproc unlimited
  253. EOF
  254.  
  255. log "Configuring non-repudiable sudo logging..."
  256. mkdir -p /var/log/sudo
  257. echo 'Defaults log_output, logfile="/var/log/sudo/sudo.log", requiretty, timestamp_timeout=0' > /etc/sudoers.d/citadel_logging
  258. chmod 440 /etc/sudoers.d/citadel_logging
  259.  
  260. log "Enforcing AppArmor profiles and applying systemd sandboxing..."
  261. aa-enforce /etc/apparmor.d/* &>/dev/null
  262. mkdir -p /etc/systemd/system/sshd.service.d/ && echo -e "[Service]\nProtectSystem=strict\nProtectHome=yes\nNoNewPrivileges=true\nPrivateDevices=true\nPrivateNetwork=true" > /etc/systemd/system/sshd.service.d/override.conf
  263. systemctl daemon-reload
  264.  
  265. log "Making critical configurations immutable (read-only)..."
  266. FILES_TO_LOCK=( "/etc/ssh/sshd_config" "/etc/audit/rules.d/99-citadel-rules.rules" "/etc/sudoers.d/citadel_logging" "/etc/sysctl.d/99-citadel-hardening.conf" "/etc/nftables.conf" "/etc/modprobe.d/citadel-blacklist.conf" "/opt/citadel_c2.py" "/etc/ssl/private/citadel.key" "/etc/ssl/certs/citadel.pem" "/etc/resolv.conf" )
  267. for f in "${FILES_TO_LOCK[@]}"; do chattr +i "$f" &>/dev/null || true; done
  268. warn "To modify locked files, first run 'chattr -i <file>'"
  269.  
  270. log "Installing legal warning banners..."
  271. cat <<EOF > /etc/issue
  272. =============================================================================
  273.               ** UNITED STATES GOVERNMENT SYSTEM (TS//SI) **
  274. This system is for authorized use only. Activity is monitored, recorded, and
  275. subject to audit. Unauthorized use is prohibited and subject to criminal and
  276. civil penalties. By continuing, you consent to these terms.
  277. =============================================================================
  278. EOF
  279. cp /etc/issue /etc/issue.net
  280.  
  281. log "Running final post-hardening audit scans..."
  282. lynis audit system --quiet --no-colors > "/var/log/lynis_final.log"
  283. rkhunter --check --skip-keypress --quiet > "/var/log/rkhunter_final.log"
  284.  
  285. # --- FINALIZATION & OPERATOR BRIEFING ---
  286. SERVER_IP=$(hostname -I | awk '{print $1}' || curl -s4 ifconfig.me)
  287. echo -e "\n\n"
  288. echo "=================================================================================="
  289. echo -e "          \033[1;32m/// PROJECT CITADEL: LOCKDOWN COMPLETE ///\033[0m"
  290. echo "=================================================================================="
  291. echo -e "System hardened and C2 listener deployed. This information will \033[1;31mNOT\033[0m be shown again."
  292. echo ""
  293. echo -e "  \033[1mAsset IP Address:\033[0m   \033[1;33m${SERVER_IP}\033[0m"
  294. echo -e "  \033[1mC2 Port:\033[0m            \033[1;33m${C2_PORT}\033[0m"
  295. echo -e "  \033[1mC2 Dispatch Code:\033[0m   \033[1;33m${C2_DISPATCH_CODE}\033[0m"
  296. echo ""
  297. echo "------------------------- \033[1;31mCRITICAL: FIRST ACTION REQUIRED\033[0m -------------------------"
  298. echo "Lock the firewall to your IP. From your machine, run the following command,"
  299. echo -e "which will remotely update the firewall rules and re-lock the configuration:"
  300. echo ""
  301. echo -e "\033[1;36mOPERATOR_IP=\$(curl -s ifconfig.me); curl -k -X POST https://${SERVER_IP}:${C2_PORT} -H \"X-Citadel-Dispatch-Code: ${C2_DISPATCH_CODE}\" -d \"{\\\"cmd\\\": \\\"chattr -i /etc/nftables.conf && sed -i '/tcp dport ${C2_PORT} accept/c\\\\        tcp dport ${C2_PORT} ip saddr \\\\\$OPERATOR_IP accept' /etc/nftables.conf && chattr +i /etc/nftables.conf && systemctl restart nftables\\\"}\"\033[0m"
  302. echo "----------------------------------------------------------------------------------"
  303. echo ""
  304. echo -e "To start the C2 listener daemon, run: \033[1;32msystemd-run /opt/citadel_c2.py\033[0m"
  305. echo ""
  306. success "Directive complete. A reboot is required to finalize all kernel and filesystem protections."
  307. touch /force-reboot
  308. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement