Logo

CIS Benchmark Hardening Toolkit Documentation

This page explains what this project hardens, why each control exists, and what vulnerabilities are reduced when the hardening scripts are applied.

Target OS: Ubuntu 22.04 LTS Benchmark Profile: CIS Level 1 Execution Model: Audit -> Harden -> Validate -> Report

Documentation Index

CIS Benchmark Overview

The Center for Internet Security (C I S) Benchmarks are security configuration standards for operating systems and applications. This project aligns with CIS Ubuntu Linux 22.04 LTS Benchmark (Level 1) principles.

Level 1 controls focus on practical baseline security with low operational overhead. The goal is to reduce common attack paths while keeping systems usable.

Hardening Scope in This Project

The toolkit covers controls for identity, authentication, SSH, file permissions, kernel networking behavior, firewall policy, service reduction, logging/auditing, AppArmor, and sudo controls.

It also performs pre-check and post-check scans to show measurable security posture improvement.

How the Scripts Work Together

Main execution entrypoint is main.sh.

Pipeline: audit/baseline_audit.sh -> hardening modules in harden/ -> audit/compliance_validator.sh -> HTML/TXT report generation in reports/.

Most configuration files are backed up before modification, allowing rollback via rollback.sh.

Execution Evidence — Baseline Audit
baseline_audit.sh — Phase 1 startup
baseline_audit.sh — Phase 1 startup

The baseline audit scans the host against CIS Level 1 controls before remediation. The tool identifies the host OS and kernel, then begins checking filesystem configuration.

baseline_audit.sh — initial findings
baseline_audit.sh — initial findings

Initial checks reveal weak defaults such as loaded insecure modules, /tmp issues, pending updates, and policy gaps — establishing the pre-hardening baseline.

Authentication and Password Hardening (harden_auth.sh)

This module strengthens local authentication and account policy to limit brute-force success, credential reuse, and weak password abuse.

Control What is Implemented Why It Matters If Missing, Possible Vulnerability
Password complexity Configures /etc/security/pwquality.conf with min length, class checks, repeat limits, dictionary checks. Raises attacker cost for guessing and cracking password hashes. Weak credentials become practical targets for brute-force and password-spraying attacks.
Password reuse prevention Adds remember=5 to PAM unix password policy. Prevents immediate reuse of recently compromised passwords. Users can rotate back to old leaked passwords after forced reset.
Failed login lockout Uses pam_faillock with deny=5 and unlock timeout. Slows credential stuffing and high-rate password guessing. Unlimited retries increase online brute-force success probability.
Password aging Sets PASS_MAX_DAYS, PASS_MIN_DAYS, PASS_WARN_AGE and applies to active users via chage. Limits lifetime of stolen credentials and enforces periodic rotation behavior. Long-lived passwords increase blast radius after compromise.
Restrict su Uses PAM wheel restriction in /etc/pam.d/su. Limits privilege escalation path to approved operator groups. Any local account may attempt privileged context switching.
Root account lock Locks root password while preserving sudo-based administration. Removes direct root password login path. Direct root authentication can be brute-forced or reused from leaked secrets.
Execution Evidence
harden_auth.sh — password & PAM hardening
harden_auth.sh — password & PAM hardening

Password quality, PAM rules, lockout policy, and password aging settings are applied with backup support — each step is confirmed with a [PASS] or [APPLY] status.

SSH Hardening (harden_ssh.sh)

This module applies secure defaults for remote administration, including stronger cryptography and stricter authentication behavior.

Control What is Implemented Why It Matters If Missing, Possible Vulnerability
Root SSH disabled PermitRootLogin no, empty passwords disallowed, environment import restricted. Forces identity-based least privilege and audited escalation via sudo. Root-targeted password attacks and unmanaged privileged sessions.
Authentication throttling MaxAuthTries 4, LoginGraceTime 60. Reduces brute-force attempt rate and incomplete-auth session abuse. Higher trial volume enables faster password guessing.
Cryptographic policy Explicit ciphers, MACs, and KEX algorithms are enforced. Avoids weak/legacy algorithm negotiation and improves session integrity. Downgrade opportunities and weaker confidentiality/integrity guarantees.
Session control ClientAliveInterval 300, ClientAliveCountMax 0, forwarding disabled. Limits stale sessions and reduces pivot paths through tunnels/agents. Zombie sessions and unintended lateral movement channels.
Legal warning banners Configures /etc/issue and /etc/issue.net. Supports monitored-access policy and legal notice requirements. Weak legal posture for monitoring/enforcement in regulated environments.
File permission hardening Restricts SSH host key and config file permissions; validates config before restart. Prevents unauthorized key/config exposure and avoids lockout due to syntax errors. Key leakage, config tampering, or failed service restarts.

Filesystem and Permission Hardening (harden_filesystem.sh)

This module secures critical OS files, audit surfaces, temporary storage behavior, and risky file permission states.

Control What is Implemented Why It Matters If Missing, Possible Vulnerability
Critical file permissions Applies strict ownership/permissions to passwd/shadow/group/sudoers/grub and related files. Protects credential stores and privileged configuration from unauthorized edits/read. Privilege escalation through tampered auth or boot configuration files.
Cron and at access control Secures cron directories and enforces cron.allow/at.allow. Limits scheduled task creation to trusted administrators. Persistence via unauthorized scheduled jobs.
SUID/SGID discovery Generates audit report of privileged binaries. Provides visibility into high-risk executables for manual review. Unmonitored privileged binaries can be exploited for local escalation.
World writable and unowned file scans Reports dangerous file states and unknown ownership artifacts. Highlights tamper points and hygiene issues often abused post-compromise. Unauthorized writes, hidden persistence, and forensic blind spots.
/tmp and /var/tmp hardening Mounts /tmp as tmpfs (noexec,nodev,nosuid) where needed; links /var/tmp to /tmp. Restricts execution and device/suid behavior in temporary paths. Malware staging and local privilege escalation via writable temp locations.
Legacy trust file cleanup Removes .rhosts, .netrc and /etc/hosts.equiv if present. Eliminates insecure host-based trust artifacts. Passwordless trust abuse and remote impersonation opportunities.
Execution Evidence
harden_filesystem.sh — permissions & tmp hardening
harden_filesystem.sh — permissions & tmp hardening

Critical file permissions, sticky-bit handling, /tmp hardening, and legacy trust cleanup are enforced — SUID/SGID and world-writable file scans are also completed.

Kernel and Network Hardening (harden_kernel.sh)

This module configures defensive kernel/network defaults through sysctl and disables risky modules and core dump vectors.

Control What is Implemented Why It Matters If Missing, Possible Vulnerability
Routing and redirect protections Disables IP forwarding, send redirects, source routes, and ICMP redirects. Reduces traffic manipulation and host misuse as a rogue router. MITM-style route manipulation and trust boundary bypass.
Packet sanity defenses Enables martian logging, SYN cookies, reverse path filtering, and bogus ICMP handling. Improves resilience to spoofing and TCP resource exhaustion patterns. Increased susceptibility to spoofing and SYN flood impact.
Kernel exploit friction Enables ASLR, restricts dmesg and kernel pointers, hardens BPF, sets ptrace scope. Reduces exploit reliability and information leakage useful to attackers. Kernel memory disclosure and easier local exploit chaining.
Core dump restrictions Disables suid dumps, configures limits, and disables systemd coredump storage. Prevents sensitive process memory from being persisted to disk. Credential/token leakage through dump artifacts.
Module blacklist Blacklists uncommon filesystems and network modules (for example dccp/sctp/rds/tipc). Shrinks kernel attack surface by disabling unused protocol paths. Unused modules remain exploitable if vulnerabilities are discovered.
IPv6 boot-level disable Applies ipv6.disable=1 in GRUB and sysctl disable flags. Avoids unmanaged dual-stack exposure in IPv4-only environments. Hidden IPv6 paths bypassing expected IPv4 firewall policy.
Execution Evidence
harden_kernel.sh — sysctl, IPv6, coredump & module controls
harden_kernel.sh — sysctl, IPv6, coredump & module controls

Sysctl controls, IPv6 boot configuration, coredump restrictions, and module-level protections are applied — GRUB is updated and changes are verified in place.

Logging and Auditing Hardening (harden_logging.sh)

This module improves observability, accountability, and forensic readiness with rsyslog, auditd, journald, and log rotation controls.

Control What is Implemented Why It Matters If Missing, Possible Vulnerability
Centralized logging baseline Installs/enables rsyslog and adds explicit auth/kernel/cron logging policy. Ensures high-value events are retained for detection and investigation. Attack activity may go unlogged or remain hard to correlate.
Audit rules for identity and privilege events Defines auditd rules for passwd/sudo/ssh/pam/module loading and failed access attempts. Creates tamper-evident trail for administrative and security-critical actions. Limited forensic ability after privilege escalation or policy tampering.
Immutable audit configuration Uses terminal rule -e 2 in audit policy. Prevents runtime audit rule modifications by attackers. Adversaries can disable or alter monitoring to hide activity.
journald persistence Configures persistent storage, compression, retention windows, and syslog forwarding. Preserves boot-to-boot history and supports long-term investigations. Volatile-only logs vanish after reboot and reduce traceability.
Log file permission controls Sets restrictive mode/ownership for key logs and defines logrotate policy. Prevents unauthorized read/write and controls storage lifecycle. Log tampering, data leakage, or disk exhaustion from uncontrolled growth.
Execution Evidence
harden_logging.sh — rsyslog, auditd, journald & log perms
harden_logging.sh — rsyslog, auditd, journald & log perms

rsyslog, auditd, journald persistence, and log permission controls are configured for visibility and traceability — backup files are created before each change.

Firewall Hardening (harden_firewall.sh)

This module enforces a server-grade, defence-in-depth firewall posture using UFW enhanced with low-level iptables rules injected into /etc/ufw/before.rules. The policy spans default-deny inbound traffic, SSH brute-force rate-limiting, anti-spoofing, scan protection, ICMP hardening, an optional strict-outbound allowlist, UFW high-verbosity logging and kernel/sysctl alignment. All rules are idempotent (sentinel comment guard) and backed up via the project’s roll-back mechanism.

Control What is Implemented Why It Matters If Missing, Possible Vulnerability
Default deny inbound Resets UFW and applies deny incoming / deny forward / allow outgoing. Blocks unsolicited access by default. Unnecessary listening services become remotely reachable.
SSH rate-limiting (brute-force protection) ufw limit ssh — allows SSH but throttles repeated connection attempts (6 per 30 s). Mitigates credential-stuffing and brute-force attacks against the SSH daemon. Attacker can attempt unlimited password guesses without penalty.
Anti-spoofing (RFC 1918 / bogon drops) Drops packets arriving on public interfaces claiming RFC 1918 source addresses; injected into before.rules. Prevents source-IP spoofing used in reflective amplification and session-hijack attacks. Spoofed internal-source packets accepted, bypassing access controls.
INVALID state packet drops Drops packets in INVALID conntrack state before other rules evaluate them. Rejects malformed, out-of-sequence or state-table-busting packets used in evasion. Malformed packets can bypass stateful inspection and confuse application-layer filters.
Scan protection (NULL, XMAS, FIN, non-SYN) Drops NULL-flag, XMAS-flag, FIN-flag and non-SYN-initiating TCP packets in before.rules. Eliminates the most common OS-fingerprinting and port-scan probes. Attackers enumerate open ports and OS version silently, enabling targeted exploitation.
ICMP rate-limiting & type restriction Allows echo-request at 1/s (burst 5) via hashlimit; drops all other ICMP types. Permits network reachability checks while blocking ICMP tunnels and flood amplification. Unrestricted ICMP enables covert data exfiltration via ICMP tunnels and ICMP flood DoS.
Optional strict outbound (STRICT_OUTBOUND) When enabled, only allows outbound DNS (53), HTTP (80), HTTPS (443), NTP (123), SMTP (25/587), SSH (22). Restricts post-compromise call-home, lateral movement and data exfiltration vectors. Compromised processes can freely beacon to attacker infrastructure on arbitrary ports.
UFW high-verbosity logging Sets UFW log level to high (all allowed and denied connections logged). Provides complete audit trail of firewall decisions for incident response. Denied traffic invisible to operators; attackers can probe undetected.
UFW/sysctl alignment Patches /etc/ufw/sysctl.conf to prevent UFW from re-enabling IP forwarding or source-routing. Ensures kernel networking parameters remain consistent with the hardened policy across reboots. UFW restores permissive kernel settings on restart, silently undoing OS-level hardening.
Loopback policy Explicit loopback allow and loopback anti-spoof deny rules. Protects local-only trust assumptions from spoofed packets. Loopback spoofing and policy bypass scenarios.
TCP wrappers baseline Configures hosts.deny default-deny and allows sshd in hosts.allow. Adds a host-based service access-control layer on top of the kernel firewall. No additional host ACL gate where wrappers are applicable.
Execution Evidence
harden_firewall.sh — UFW default-deny & SSH allow
harden_firewall.sh — UFW default-deny & SSH allow

UFW is reset and configured with secure default policies while preserving SSH access — loopback interface rules and medium-level logging are confirmed active.

Service Surface Reduction and MAC/Sudo Hardening (harden_services.sh)

This module removes nonessential network-facing software, disables risky daemons, enforces AppArmor, and tightens sudo behavior.

Control What is Implemented Why It Matters If Missing, Possible Vulnerability
Legacy/insecure package removal Purges services such as telnet, ftp, rsh, xinetd, and others where installed. Removes weak or unnecessary remote attack entry points. Legacy plaintext protocols and vulnerable daemons remain exposed.
Systemd service reduction Stops/disables optional services (for example rpcbind, avahi, nginx/apache, snmpd) when enabled. Enforces least functionality and smaller network footprint. Broader attack surface and more patch burden.
AppArmor enforcement Installs/enables AppArmor and enforces profiles where available. Adds mandatory access control containment for compromised processes. Process compromise can lead to wider filesystem/process access.
Sudo accountability controls Enables sudo logfile, input/output logging, and use_pty; validates sudoers syntax. Improves auditability and reduces blind privileged execution. Harder attribution of privileged abuse or command misuse.
Bootloader security reminder Checks for GRUB password presence and warns if absent. Encourages protection against offline single-user boot tampering. Physical attackers can alter boot args and bypass controls.
Execution Evidence
harden_services.sh — service removal & surface reduction
harden_services.sh — service removal & surface reduction

Unnecessary and insecure services are removed or disabled to reduce the host attack surface — telnet, ftp, cups, isc-dhcp-server, and other non-essential daemons are purged or confirmed absent.

Compliance Validation and Reporting (audit/compliance_validator.sh)

The validator re-checks hardening outcomes and computes a compliance score from PASS / FAIL / WARN checks. Reports are generated in text and HTML format for evidence and review.

This supports open-source contributors by making hardening behavior measurable and easy to verify across environments.

PASS: control satisfied WARN: partially met or contextual gap FAIL: expected control missing
Important: Some controls are environment-dependent. For example, disabling IPv6 or removing mail services may not fit every deployment. Review before applying to production and adjust modules for your operational requirements.
Execution Evidence
compliance_validator.sh — filesystem & patch checks
compliance_validator.sh — filesystem & patch checks

Post-hardening validation rechecks all applied CIS controls — filesystem modules are now disabled and /tmp mount options pass.

compliance_validator.sh — SSH, password & kernel checks
compliance_validator.sh — SSH, password & kernel checks

PASS/FAIL status across SSH, password policy, kernel network hardening, and firewall controls is shown here.

compliance_validator.sh — firewall, logging, services & sudo
compliance_validator.sh — firewall, logging, services & sudo

Firewall, logging, file permission, service removal, AppArmor, and sudo controls are all confirmed passing after hardening.

compliance_validator.sh — final compliance score
compliance_validator.sh — final compliance score

The compliance summary highlights remaining gaps and the final measured score — 54 PASS, 19 FAIL, 0 WARN across 73 total controls, yielding a 73% CIS compliance score.

System Rollback & Recovery

🔄

The hardening toolkit follows a "Safe-by-Design" principle. Before any configuration file is modified, an automated backup is created in the same directory (e.g., /etc/ssh/sshd_config.bak). If any system instability is observed post-hardening, the rollback.sh script can be used to restore all original configurations instantly.

Rollback Procedure & Verification
rollback.sh — restoring system state
rollback.sh — restoring system state

Executing the rollback script identifies all modified files and restores them from their .bak counterparts, ensuring a safe return to the baseline state.

Dashboard and HTML Report Outcome

📊

In addition to terminal-based validation, the toolkit generates an HTML compliance dashboard that presents the hardening score, control breakdown, and detailed result table in a browser-readable format. The report is written to the reports/ directory and can be served locally for review and evidence archiving.

73%
CIS Compliance Score
54
Controls Passing
19
Controls Failing
73
Total Checks
Report Screenshots
compliance_report.html — score overview & result breakdown
compliance_report.html — score overview & result breakdown

The dashboard shows the overall CIS compliance score and result distribution — 54 passing and 19 failing checks are rendered as progress bars alongside host metadata.

compliance_report.html — detailed control results table
compliance_report.html — detailed control results table

Detailed control results are presented in a clean browser-based report — each row shows the CIS ID, status badge, and control description for review and evidence.

compliance_report.html — remaining FAIL rows
compliance_report.html — remaining FAIL rows

This final HTML output makes the hardening outcome easier to interpret and document — remaining failures such as SSH configuration and password aging controls are clearly listed for remediation follow-up.