Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- #
- # ==================================================================================
- # // USCYBERCOM FINAL UNIFIED DIRECTIVE: PROJECT CITADEL //
- # ==================================================================================
- #
- # CLASSIFICATION: TS//SI//REL TO FVEY
- # OPERATION: Definitive Synthesis of Hardening & C2 Deployment Protocols
- # TARGET PLATFORM: Debian 12 (Bookworm) - High-Value Asset
- # LEAD: Taylor Christian Newsome (ClumsyLulz)
- # REVISION: 8.0.0 (Citadel Final)
- #
- # PURPOSE: This directive represents the definitive synthesis of all previously
- # discussed protocols (BLACKSITE, GHOSTWRITER, AEGIS, OMNIBUS). It is a
- # fully automated, non-interactive "fire-and-forget" system for elevating a
- # stock Debian 12 installation to a national security framework standard. It
- # executes a multi-layered defense-in-depth lockdown, neutralizes potential
- # backdoors via a Zero-Trust network policy, deploys a comprehensive audit and
- # deception framework, and establishes a secure command channel. Upon completion,
- # it provides the operator with credentials and instructions for the final security
- # lockdown. This is the one script needed.
- #
- # EXECUTION: Run as root on a fresh Debian 12 system. No user input is required.
- #
- # --- PRE-FLIGHT CHECKS ---
- set -euo pipefail
- if [[ "$(id -u)" -ne 0 ]]; then
- echo -e "\n[FATAL] Directive requires root privileges. Execution denied." >&2; exit 1
- fi
- if ! grep -qi "bookworm" /etc/os-release; then
- echo -e "\n[FATAL] This directive is tuned specifically for Debian 12 (Bookworm). Aborting." >&2; exit 1
- fi
- # --- SCRIPT INITIALIZATION ---
- export DEBIAN_FRONTEND=noninteractive
- LOG_FILE="/var/log/project_citadel_run_$(date +%Y%m%d_%H%M%S).log"
- exec > >(tee -i "$LOG_FILE")
- exec 2>&1
- # Helper functions
- log() { echo -e "[\033[1;36mCITADEL\033[0m] $1"; }
- warn() { echo -e "[\033[1;33mWARN\033[0m] $1"; }
- success() { echo -e "[\033[1;32mSUCCESS\033[0m] $1"; }
- op() { echo -e "\n[\033[1;35m==> OPERATION\033[0m] \033[1m$1\033[0m"; }
- # ==================================================================================
- # DIRECTIVE EXECUTION
- # ==================================================================================
- clear
- echo "==========================================================================="
- echo " USCYBERCOM FINAL UNIFIED DIRECTIVE: PROJECT CITADEL"
- echo " Initiating fully automated, comprehensive system lockdown."
- echo "==========================================================================="
- sleep 1
- op "Phase 1: System Baseline & Comprehensive Security Toolkit Installation"
- log "Updating package repositories and applying all security patches..."
- apt-get update && apt-get -y full-upgrade && apt-get -y dist-upgrade
- log "Installing comprehensive security, auditing, and dependency toolkit..."
- apt-get -y install auditd audispd-plugins aide logwatch fail2ban apparmor apparmor-utils \
- usbguard tpm2-tools nftables net-tools dnscrypt-proxy debsums curl git make gnupg2 \
- rsyslog sudo lsof ipset systemd-timesyncd bpfcc-tools acct busybox cron bash-completion \
- libpam-pwquality libpam-tmpdir needrestart python3 openssl lynis chkrootkit \
- rkhunter apt-listchanges apt-transport-https ca-certificates dnsutils
- op "Phase 2: Integrity, Boot Security, and Unattended Upgrades"
- if ! grep -q 'crypt' /etc/crypttab; then
- warn "LUKS Full Disk Encryption not detected. This is a critical vulnerability for physical access."
- else
- success "LUKS Full Disk Encryption detected."
- fi
- if tpm2_getcap properties-fixed 2>/dev/null | grep -q TPM2_PT_MANUFACTURER; then
- success "TPM 2.0 module detected. Measured boot integrity is active."
- else
- warn "No TPM 2.0 module detected. Hardware-based root of trust is not available."
- fi
- log "Configuring automatic unattended security upgrades..."
- cat <<EOF > /etc/apt/apt.conf.d/20auto-upgrades
- APT::Periodic::Update-Package-Lists "1";
- APT::Periodic::Unattended-Upgrade "1";
- APT::Periodic::AutocleanInterval "7";
- EOF
- log "Initializing AIDE database for file integrity monitoring..."
- aideinit && cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db
- log "Securing GRUB bootloader against unauthorized modification and recovery..."
- sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/GRUB_CMDLINE_LINUX_DEFAULT="lockdown=integrity quiet /' /etc/default/grub
- echo "GRUB_DISABLE_RECOVERY=true" >> /etc/default/grub
- update-grub
- log "Verifying package integrity against official repository manifests..."
- debsums --changed > /var/log/debsums_changed.log || true
- if [[ -s /var/log/debsums_changed.log ]]; then
- warn "Potential supply chain compromise! Review /var/log/debsums_changed.log"
- else
- success "Package integrity verification passed."
- fi
- op "Phase 3: Kernel, Filesystem, and Scheduler Hardening"
- log "Applying kernel hardening parameters via sysctl..."
- cat <<EOF > /etc/sysctl.d/99-citadel-hardening.conf
- kernel.kptr_restrict=2
- kernel.dmesg_restrict=1
- kernel.randomize_va_space=2
- kernel.unprivileged_bpf_disabled=1
- user.max_user_namespaces=0
- net.ipv4.tcp_syncookies=1
- net.ipv4.conf.all.rp_filter=1
- net.ipv4.conf.all.accept_source_route=0
- net.ipv4.conf.all.accept_redirects=0
- net.ipv4.conf.all.log_martians=1
- net.ipv6.conf.all.disable_ipv6=1
- net.ipv6.conf.default.disable_ipv6=1
- fs.suid_dumpable=0
- EOF
- sysctl --system
- log "Applying immediate, non-persistent mount hardening..."
- mount -o remount,ro /boot
- mount -o remount,nodev,noexec,nosuid /tmp
- mount -o remount,nodev,noexec,nosuid /var/tmp
- mount -o remount,nodev,noexec,nosuid /dev/shm
- log "Making temporary filesystem hardening persistent in /etc/fstab..."
- sed -i -e '/\/boot/ s/defaults/defaults,ro/' /etc/fstab
- echo "tmpfs /tmp tmpfs defaults,rw,nosuid,nodev,noexec,relatime 0 0" >> /etc/fstab
- echo "tmpfs /dev/shm tmpfs defaults,rw,nosuid,nodev,noexec,relatime 0 0" >> /etc/fstab
- log "Locking down cron directories..."
- chmod 700 /etc/crontab /etc/cron.*
- op "Phase 4: Attack Surface Reduction & Active Defense"
- log "Blacklisting unnecessary kernel modules..."
- cat <<EOF > /etc/modprobe.d/citadel-blacklist.conf
- install cramfs /bin/true; install udf /bin/true; install hfs /bin/true
- install hfsplus /bin/true; install freevxfs /bin/true; install jffs2 /bin/true
- install squashfs /bin/true; install usb-storage /bin/true; install firewire-core /bin/true
- EOF
- update-initramfs -u
- log "Purging unnecessary and high-risk services..."
- SERVICES_TO_PURGE=(snapd lxd avahi-daemon bluetooth cups rpcbind nfs-kernel-server isc-dhcp-server)
- for svc in "${SERVICES_TO_PURGE[@]}"; do
- if systemctl list-unit-files | grep -q "$svc.service"; then
- systemctl disable --now "$svc" &>/dev/null || true; apt-get -y purge "$svc" &>/dev/null || true
- fi
- done
- apt-get -y autoremove
- log "Deploying honeypot user and generating USBGuard policy..."
- useradd -r -s /usr/sbin/nologin oracle-svc || true
- usbguard generate-policy > /etc/usbguard/rules.conf
- systemctl enable --now usbguard
- log "Enabling process accounting and brute-force protection..."
- systemctl enable --now acct
- systemctl enable --now fail2ban
- op "Phase 5: Zero-Trust Network Fortress"
- 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")
- C2_PORT=443
- log "Deploying Zero-Trust firewall. All outbound traffic will be blocked by default."
- cat <<EOF > /etc/nftables.conf
- flush ruleset
- table inet filter {
- set debian_repos { type ipv4_addr; flags interval; elements = { ${DEBIAN_REPOS_IPS} }; }
- chain input {
- type filter hook input priority 0; policy drop;
- iif lo accept; ct state established,related accept;
- tcp dport ${C2_PORT} accept; # Allow C2 from anywhere initially. Operator will lock this down.
- log prefix "[NFT_DROP_INPUT] " level info drop
- }
- chain forward { type filter hook forward priority 0; policy drop; }
- chain output {
- type filter hook output priority 0; policy drop;
- oif lo accept; ct state established,related accept;
- udp dport { 53, 123 } accept; tcp dport { 80, 443 } ip daddr @debian_repos accept;
- tcp sport ${C2_PORT} accept;
- log prefix "[NFT_DROP_OUTPUT] " level info drop
- }
- }
- EOF
- systemctl enable --now nftables
- op "Phase 6: Audit, Surveillance, and C2 Framework"
- log "Deploying persistent auditd rules mapped to MITRE ATT&CK TTPs..."
- cat <<EOF > /etc/audit/rules.d/99-citadel-rules.rules
- -w /etc/shadow -p wa -k cred_dump
- -w /etc/passwd -p wa -k cred_dump
- -w /usr/sbin/useradd -p x -k acct_mgmt
- -w /usr/sbin/usermod -p x -k acct_mgmt
- -w /usr/sbin/groupadd -p x -k acct_mgmt
- -w /usr/bin/sudo -p x -k priv_escalation
- -w /bin/su -p x -k priv_escalation
- -w /etc/audit/ -p wa -k defense_tamper
- -w /etc/apparmor.d/ -p wa -k defense_tamper
- -w /etc/nftables.conf -p wa -k defense_tamper
- -a always,exit -F arch=b64 -S init_module,finit_module,delete_module -k kernel_manip
- -w /usr/bin/history -p x -k indicator_removal
- -a always,exit -F arch=b64 -S execve,execveat -k exec_telemetry
- EOF
- systemctl restart auditd
- log "Enabling persistent journald logging and configuring encrypted DNS..."
- sed -i -e 's/^#?Storage=.*/Storage=persistent/' -e 's/^#?Compress=.*/Compress=yes/' /etc/systemd/journald.conf
- sed -i "s/^# server_names = .*/server_names = ['quad9-doh-ip4-filter-pri']/" /etc/dnscrypt-proxy/dnscrypt-proxy.toml
- sed -i "s/^# listen_addresses = .*/listen_addresses = ['127.0.2.1:53']/" /etc/dnscrypt-proxy/dnscrypt-proxy.toml
- echo "nameserver 127.0.2.1" > /etc/resolv.conf
- systemctl daemon-reload && systemctl restart systemd-journald dnscrypt-proxy.service
- log "Enabling bash forensic logging for all users..."
- mkdir -p /var/log/bashlog && chmod 733 /var/log/bashlog
- cat <<EOF > /etc/profile.d/bash_forensics.sh
- export PROMPT_COMMAND='history -a >(tee -a /var/log/bashlog/\$(whoami)_\$(date +%Y%m%d).log)' 2>/dev/null
- EOF
- log "Generating C2 credentials and deploying listener..."
- C2_DISPATCH_CODE=$(openssl rand -hex 16)
- C2_SCRIPT_PATH="/opt/citadel_c2.py"
- mkdir -p /etc/ssl/private
- 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
- cat << EOF > "${C2_SCRIPT_PATH}"
- import http.server, ssl, json, subprocess
- HOST, PORT, CODE = '0.0.0.0', ${C2_PORT}, "${C2_DISPATCH_CODE}"
- class C2(http.server.BaseHTTPRequestHandler):
- 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())
- def do_POST(self):
- if self.headers.get('X-Citadel-Dispatch-Code') != CODE: return self._r(403,{'error':'auth denied'})
- 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})
- except Exception as e: self._r(500, {'error': str(e)})
- 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)
- httpd.serve_forever()
- EOF
- chmod +x "${C2_SCRIPT_PATH}"
- op "Phase 7: Access Control, Sandboxing, and Final Lockdown"
- log "Applying intelligence-grade SSHD configuration..."
- 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
- echo -e "\nCiphers [email protected],[email protected]\nMACs [email protected]\nKexAlgorithms [email protected]" >> /etc/ssh/sshd_config
- systemctl restart sshd
- log "Strengthening PAM, user limits, and password policies..."
- sed -i '1i auth optional pam_faildelay.so delay=8000000' /etc/pam.d/common-auth
- 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
- cat <<EOF > /etc/security/limits.d/99-citadel-limits.conf
- * hard core 0
- * hard nproc 1000
- * hard nofile 4096
- root hard nproc unlimited
- EOF
- log "Configuring non-repudiable sudo logging..."
- mkdir -p /var/log/sudo
- echo 'Defaults log_output, logfile="/var/log/sudo/sudo.log", requiretty, timestamp_timeout=0' > /etc/sudoers.d/citadel_logging
- chmod 440 /etc/sudoers.d/citadel_logging
- log "Enforcing AppArmor profiles and applying systemd sandboxing..."
- aa-enforce /etc/apparmor.d/* &>/dev/null
- 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
- systemctl daemon-reload
- log "Making critical configurations immutable (read-only)..."
- 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" )
- for f in "${FILES_TO_LOCK[@]}"; do chattr +i "$f" &>/dev/null || true; done
- warn "To modify locked files, first run 'chattr -i <file>'"
- log "Installing legal warning banners..."
- cat <<EOF > /etc/issue
- =============================================================================
- ** UNITED STATES GOVERNMENT SYSTEM (TS//SI) **
- This system is for authorized use only. Activity is monitored, recorded, and
- subject to audit. Unauthorized use is prohibited and subject to criminal and
- civil penalties. By continuing, you consent to these terms.
- =============================================================================
- EOF
- cp /etc/issue /etc/issue.net
- log "Running final post-hardening audit scans..."
- lynis audit system --quiet --no-colors > "/var/log/lynis_final.log"
- rkhunter --check --skip-keypress --quiet > "/var/log/rkhunter_final.log"
- # --- FINALIZATION & OPERATOR BRIEFING ---
- SERVER_IP=$(hostname -I | awk '{print $1}' || curl -s4 ifconfig.me)
- echo -e "\n\n"
- echo "=================================================================================="
- echo -e " \033[1;32m/// PROJECT CITADEL: LOCKDOWN COMPLETE ///\033[0m"
- echo "=================================================================================="
- echo -e "System hardened and C2 listener deployed. This information will \033[1;31mNOT\033[0m be shown again."
- echo ""
- echo -e " \033[1mAsset IP Address:\033[0m \033[1;33m${SERVER_IP}\033[0m"
- echo -e " \033[1mC2 Port:\033[0m \033[1;33m${C2_PORT}\033[0m"
- echo -e " \033[1mC2 Dispatch Code:\033[0m \033[1;33m${C2_DISPATCH_CODE}\033[0m"
- echo ""
- echo "------------------------- \033[1;31mCRITICAL: FIRST ACTION REQUIRED\033[0m -------------------------"
- echo "Lock the firewall to your IP. From your machine, run the following command,"
- echo -e "which will remotely update the firewall rules and re-lock the configuration:"
- echo ""
- 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"
- echo "----------------------------------------------------------------------------------"
- echo ""
- echo -e "To start the C2 listener daemon, run: \033[1;32msystemd-run /opt/citadel_c2.py\033[0m"
- echo ""
- success "Directive complete. A reboot is required to finalize all kernel and filesystem protections."
- touch /force-reboot
- exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement