PromptHub
DevOps Cybersecurity

Stop Leaving Ubuntu Servers Exposed! Use konstruktoid/hardening Instead

B

Bright Coding

Author

14 min read
22 views
Stop Leaving Ubuntu Servers Exposed! Use konstruktoid/hardening Instead

Stop Leaving Ubuntu Servers Exposed! Use konstruktoid/hardening Instead

Your server is already under attack. Right now. While you read this, automated bots are hammering SSH ports, probing for kernel vulnerabilities, and hunting for misconfigured services. The terrifying truth? Most Ubuntu servers are deployed with security as an afterthought—if it's considered at all.

Here's the gut punch: a default Ubuntu installation is designed for compatibility, not security. It ships with unnecessary services, permissive kernel modules, and SSH configurations that welcome attackers with open arms. Every day you delay hardening is another day your data, your users, and your reputation hang in the balance.

But what if you could transform a vanilla Ubuntu server into a fortress in under 30 minutes? What if a single command could enforce CIS benchmarks, lock down systemd, disable dangerous kernel modules, and configure military-grade SSH settings?

Enter konstruktoid/hardening—the open-source secret weapon that security-conscious developers and DevOps engineers are quietly deploying across their infrastructure. This isn't another bloated security framework. It's a surgical, battle-tested bash automation that hardens Ubuntu servers with precision. Born from real-world production needs and aligned with DISA STIG and CIS benchmarks, this repository is your fastest path from "vulnerable by default" to "auditable and resilient."

Ready to stop gambling with your infrastructure? Let's dive deep into why konstruktoid/hardening deserves a permanent place in your security toolkit.

What is konstruktoid/hardening?

konstruktoid/hardening is a comprehensive Ubuntu server hardening script collection built around systemd, created by Thomas Sjögren (konstruktoid). The project delivers a fast, opinionated approach to securing Ubuntu servers through automated configuration changes that align with industry-recognized security standards.

The repository's philosophy is brutally honest: "Read the code and do not run this script without first testing in a non-operational environment." This transparency sets it apart from black-box security tools. Every function is documented, every configuration is inspectable, and the entire process is designed to be understood—not blindly executed.

Why it's trending now:

  • Compliance pressure is exploding: With GDPR, SOC 2, and ISO 27001 requirements tightening, organizations need provable security baselines—not hand-waving promises.
  • Systemd ubiquity: As systemd became the default init system across major Linux distributions, security tools that leverage its capabilities (coredump control, journald hardening, service sandboxing) gained critical relevance.
  • Supply chain attacks: High-profile breaches like SolarWinds and xz utils backdoor have made "secure by default" infrastructure non-negotiable.
  • DevSecOps maturation: Security is shifting left, and teams need automated hardening that integrates into CI/CD pipelines without friction.

The project explicitly supports Ubuntu 22.04 (Jammy Jellyfish) and Ubuntu 24.04 (Noble Numbat), with testing infrastructure that includes approximately 760 Bats tests, Lynis audits, and OpenSCAP CIS benchmark validation. For production environments, the maintainers recommend using the companion ansible-role-hardening for idempotent, configuration-managed deployments.

Crucially, the project includes SLSA (Supply-chain Levels for Software Artifacts) provenance attestation, allowing you to cryptographically verify the integrity of downloaded files. In an era of supply chain paranoia, this isn't optional—it's essential.

Key Features That Make It Exceptional

The konstruktoid/hardening repository isn't a superficial checklist. It's a 40-function deep hardening pipeline that systematically dismantles attack vectors. Here's what separates it from amateur scripts:

Kernel-Level Lockdown

The script doesn't just configure userspace—it rewrites the kernel's attack surface. It sets /sys/module/nf_conntrack/parameters/hashsize to 1048576 for connection tracking resilience, enables kernel lockdown mode to confidentiality when available (preventing even root from extracting sensitive kernel data), and mass-disables dangerous kernel modules including dccp, sctp, bluetooth, firewire-core, usb-storage, and uvcvideo.

Systemd-Centric Security Architecture

Unlike legacy hardening guides that ignore systemd's security capabilities, this tool exploits them fully:

  • Coredump elimination: Storage=none and ProcessSizeMax=0 prevent information leaks from crashed processes
  • Journald integrity: Persistent, compressed logging with strict file permissions (0600)
  • Service sandboxing: Resource limits (DefaultLimitCORE=0, DefaultLimitNOFILE=1024, DefaultLimitNPROC=1024) and CrashShell=no prevent fork bombs and core dump abuse
  • DNS-over-TLS: Opportunistic encryption via systemd-resolved

SSH Fortification

The SSH hardening is aggressive and correct:

  • Modern cipher suites: chacha20-poly1305@openssh.com, aes256-gcm@openssh.com
  • Key exchange: curve25519-sha256@libssh.org with ECDH fallbacks
  • MACs: EtM variants of SHA-512 and SHA-256
  • Password authentication disabled entirely—key-based only
  • MaxAuthTries 3, ClientAliveInterval 200, LoginGraceTime 20—brute force starvation
  • AllowGroups sudo with AllowTcpForwarding no and X11Forwarding no

Filesystem Hardening with Precision Mount Options

The fstab function enforces nosuid, nodev, noexec on sensitive mountpoints and implements hidepid=2 on /proc—preventing users from seeing each other's processes, a critical privacy and security boundary on multi-user systems.

Comprehensive Audit Trail

With auditd integration using three rule sets (base, aggressive, Docker-specific), every security-relevant system call becomes traceable. The script configures faillock for account lockout, pwquality for strong passwords, and AIDE for filesystem integrity monitoring with automated systemd timer checks.

Network Intrusion Detection

PSAD (Port Scan Attack Detector) installation and configuration enables real-time detection and alerting of port scan activities, with email notifications to configured administrators.

Use Cases: Where konstruktoid/hardening Shines

1. Compliance-Bound Production Servers

Organizations facing CIS benchmarks, DISA STIG, or PCI-DSS audits can deploy this as their golden image baseline. The 760+ automated tests provide evidence of configuration state, while the alignment with official Ubuntu STIGs reduces audit preparation from weeks to hours.

2. CI/CD Pipeline Baseline Images

DevOps teams building AMIs, container hosts, or VM templates can integrate the Ansible role variant into Packer pipelines. The resulting hardened images become immutable infrastructure foundations that satisfy security gates without manual review bottlenecks.

3. Breach Recovery and Incident Response

Post-compromise, teams need trustworthy rebuilds. The script's deterministic hardening eliminates configuration drift and ensures rebuilt systems match security policy exactly—critical when attackers may have backdoored configuration files.

4. Development Environment Security

Developers running local Ubuntu VMs or cloud instances often skip hardening for "convenience." This script bridges the gap: run once, secure permanently. The AUTOFILL='Y' option even guesses appropriate FW_ADMIN and SSH_GRPS values for rapid deployment.

5. Security Research and Training

The extensively commented codebase serves as an executable textbook for Linux security internals. Each function maps to specific attack vectors, making it invaluable for red teamers studying defenses and blue teamers understanding their tools.

Step-by-Step Installation & Setup Guide

Prerequisites

  • Fresh Ubuntu 22.04 or 24.04 server installation (minimized recommended)
  • Root or sudo access
  • Network connectivity for package installation

Installation Steps

1. Start with a clean Ubuntu Server (minimized)

During installation:

  • Select "Ubuntu Server (minimized)"
  • Do NOT install OpenSSH server (the script installs and hardens it properly)
  • Skip all "Featured Server Snaps" and additional packages
  • Follow recommended partitioning (see below)

2. Recommended partition layout

/boot       (rw)
/home       (rw,nosuid,nodev)
/var/log    (rw,nosuid,nodev,noexec)
/var/log/audit  (rw,nosuid,nodev,noexec)
/var/tmp    (rw,nosuid,nodev,noexec)

The script automatically handles /tmp via systemd tmpfs mount.

3. Post-installation hardening

Log in and execute:

# Install minimal required packages
sudo apt-get -y install git net-tools procps --no-install-recommends

# Clone the hardening repository
git clone https://github.com/konstruktoid/hardening.git

# Navigate to the directory
cd hardening

# CRITICAL: Edit configuration before running!
nano ubuntu.cfg

4. Configuration (ubuntu.cfg)

# Essential variables - CHANGEME must not be empty!
FW_ADMIN='192.168.1.100 10.0.0.5'      # Your admin IP addresses
SSH_GRPS='sudo'                         # SSH access group
SSH_PORT='22'                           # Change from default in production!
CHANGEME='I_READ_THE_DOCS_2024'         # Required safety acknowledgment

# Security-sensitive settings
AUDITD_MODE='1'                         # 0=silent, 1=printk, 2=panic
ADMINEMAIL="security@yourcompany.com"   # PSAD alert destination
KEEP_SNAPD='N'                          # Remove snapd if not needed
VERBOSE='Y'                             # Detailed output for verification

# File paths (defaults are sane, modify if needed)
SYSCTL_CONF='./misc/sysctl.conf'
AUDITD_RULES='./misc/audit-base.rules ./misc/audit-aggressive.rules'
LOGROTATE_CONF='./misc/logrotate.conf'

5. Execute hardening

# Run with root privileges
sudo bash ubuntu.sh

# Monitor output for any errors
# Reboot when complete
sudo reboot

6. Post-hardening verification

# Run the comprehensive test suite
sudo apt-get -y install bats
cd hardening/tests/
sudo bats .

# Or generate full audit report
bash ./runHostTests.sh

REAL Code Examples from the Repository

The konstruktoid/hardening repository's power lies in its meticulously crafted functions. Let's examine three critical implementations that demonstrate its technical sophistication.

Example 1: SSH Daemon Hardening (sshdconfig)

This is the complete generated SSH configuration that replaces vulnerable defaults:

# /etc/ssh/sshd_config.d/hardening.conf
# Generated by konstruktoid/hardening - DO NOT EDIT MANUALLY

AcceptEnv LANG LC_*
AllowAgentForwarding no          # Prevent agent hijacking attacks
AllowGroups sudo                 # Only sudo group members may SSH
AllowTcpForwarding no            # Block tunneling abuse
Banner /etc/issue.net            # Legal warning banner
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes256-ctr
ClientAliveCountMax 3            # Drop dead connections quickly
ClientAliveInterval 200          # Keepalive every 200 seconds
Compression no                   # CVE-2016-0777 mitigation
GSSAPIAuthentication no          # Disable unused Kerberos
HostbasedAuthentication no       # Prevent trust-based attacks
IgnoreUserKnownHosts yes         # Enforce strict host key checking
KbdInteractiveAuthentication no  # Disable keyboard-interactive
KerberosAuthentication no        # No Kerberos fallback
KexAlgorithms curve25519-sha256@libssh.org,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group-exchange-sha256
LogLevel VERBOSE                 # Audit all connection attempts
LoginGraceTime 20                # 20 seconds to authenticate
Macs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512,hmac-sha2-256
MaxAuthTries 3                   # Lock out brute forcers fast
MaxSessions 3                    # Limit concurrent sessions
MaxStartups 10:30:60             # Connection rate limiting
PasswordAuthentication no        # KEYS ONLY - critical security control
PermitEmptyPasswords no          # Double-check empty passwords blocked
PermitRootLogin no               # Root never logs in directly
PermitUserEnvironment no         # Prevent user environment injection
Port 22                          # Change this in production!
PrintLastLog yes                 # Show last login information
PrintMotd no                     # Reduce information leakage
RekeyLimit 512M 1h               # Rekey after 512MB or 1 hour
StrictModes yes                  # Enforce strict file permissions
TCPKeepAlive no                  # Prevent hijacking via keepalives
UseDNS no                        # Eliminate DNS-based delays/attacks
UsePAM yes                       # Required for AllowGroups
X11Forwarding no                 # Disable X11 tunneling entirely

Why this matters: Every line addresses a specific CVE or attack pattern. The cipher and MAC selections eliminate all known weak algorithms. PasswordAuthentication no is the single most important SSH hardening control—yet most servers still permit it. The MaxStartups 10:30:60 syntax implements probabilistic connection dropping under load, a elegant DoS mitigation.

Example 2: Systemd Security Configuration (systemdconf)

# Applied to /etc/systemd/system.conf and /etc/systemd/user.conf

[Manager]
CrashShell=no              # No emergency shell on crash (prevents physical access exploits)
DefaultLimitCORE=0         # Disable core dumps for all services
DefaultLimitNOFILE=1024    # Restrict file descriptors per process
DefaultLimitNPROC=1024     # Prevent fork bombs and resource exhaustion
DumpCore=no                # Explicit core dump prohibition

The security architecture: Systemd's [Manager] section controls defaults for all spawned services. By setting these globally, the script ensures even misconfigured third-party packages inherit restrictive limits. CrashShell=no is particularly subtle—without it, systemd drops to a root shell on critical failures, which attackers with physical or VM console access can exploit.

Example 3: Kernel Module Disabling (disablenet and disablemod)

# /etc/modprobe.d/disablenet.conf
# Network protocol modules with historical vulnerabilities

install dccp /bin/true     # Datagram Congestion Control Protocol
install sctp /bin/true     # Stream Control Transmission Protocol  
install rds /bin/true      # Reliable Datagram Sockets (multiple CVEs)
install tipc /bin/true     # Transparent Inter-Process Communication
# /etc/modprobe.d/disablemod.conf
# Hardware and peripheral modules

install bluetooth /bin/true
install bnep /bin/true
install btusb /bin/true
install firewire-core /bin/true    # DMA attack vector
install floppy /bin/true           # Legacy, rarely used
install thunderbolt /bin/true      # Thunderclap DMA attacks
install usb-storage /bin/true      # Removable media control

Attack surface mathematics: Each install [module] /bin/true line prevents the kernel from loading that module—even if root requests it. The dccp protocol alone has multiple CVEs enabling remote code execution. firewire-core and thunderbolt enable DMA attacks where malicious devices read arbitrary memory. The script's comment explicitly warns about usb-storage: if USB devices are needed, USBGuard should replace this blunt disable.

Advanced Usage & Best Practices

Production Deployment Pattern

Never run directly on production. The recommended workflow:

  1. Build golden image: Execute hardening on a template VM
  2. Validate comprehensively: Run all 760+ Bats tests, Lynis, and OpenSCAP
  3. Snapshot and distribute: Use the validated image for all deployments
  4. Maintain with Ansible: Use konstruktoid/ansible-role-hardening for ongoing drift correction

Customization Without Compromise

The ubuntu.cfg variables enable surgical customization. Critical pro tips:

  • Set FW_ADMIN before first run: Locking yourself out is embarrassingly easy
  • Use AUTOFILL='Y' cautiously: It guesses based on current session, which may not match your bastion hosts
  • Customize AUDITD_RULES: The aggressive ruleset generates significant load—benchmark before production deployment
  • Preserve CHANGEME as audit trail: Use unique values per environment to track which baseline was applied

Verification Automation

# Continuous compliance checking
0 2 * * * cd /opt/hardening/tests && sudo bats . >> /var/log/hardening-check.log 2>&1

Troubleshooting Common Issues

Symptom Cause Resolution
SSH connection refused AllowGroups sudo mismatch Verify user group membership: groups $USER
Package install fails on /tmp noexec aptget_noexec not yet applied Run with TMPDIR=/var/tmp or apply aptget_noexec first
AIDE database errors Container/LXC paths Verify /var/lib/lxcfs/cgroup exclusion in aide function
USB devices not mounting usb-storage disabled Configure USBGuard and remove from disablemod

Comparison with Alternatives

Tool Approach Idempotent Systemd-Native Test Coverage Learning Curve
konstruktoid/hardening Bash automation No (by design) Yes 760+ Bats, Lynis, OpenSCAP Low
ansible-role-hardening Ansible playbook Yes Yes Same test suite Medium
CIS-CAT Pro Commercial scanner N/A Partial Vendor tests High (cost)
Lynis Audit-only tool N/A Partial Built-in checks Low
OpenSCAP Policy engine Yes Partial NIST-certified High
DevSec Hardening Framework Chef/Ansible modules Yes No Community tests Medium

Why choose konstruktoid/hardening?

  • Transparency: Every change is inspectable bash, not opaque compiled binaries
  • Speed: Single-script execution vs. multi-hour Ansible runs for initial hardening
  • Systemd depth: No competitor matches the systemd integration granularity
  • Zero cost, full compliance alignment: Matches commercial tools' benchmark coverage at no licensing cost

The explicit non-idempotency is actually a feature for initial hardening—it fails fast and visibly rather than silently skipping critical changes. For ongoing management, the Ansible role provides the idempotent complement.

FAQ

Q: Will this break my existing applications? A: Test first! The script is explicitly non-idempotent and makes aggressive changes. The VERBOSE='Y' setting shows exactly what's modified. Run in a staging environment that mirrors production.

Q: Can I use this on Ubuntu derivatives like Linux Mint or Pop!_OS? A: The script targets Ubuntu Server specifically. Derivatives may work but aren't tested. The systemd dependencies require systemd as init system.

Q: How does this compare to cloud provider CIS-hardened images? A: Cloud CIS images are excellent starting points but often lag behind latest benchmarks and include provider-specific configurations. This script provides current, customizable hardening you control completely.

Q: Is password authentication really disabled? How do I log in? A: Yes, PasswordAuthentication no is enforced. You must configure SSH key authentication before running, or use console access to add keys afterward. This is intentional—passwords are fundamentally insecure for server access.

Q: What about containers and Kubernetes? A: The script includes audit-docker.rules for container runtime auditing. For Kubernetes nodes, run as part of node image building. Don't run directly on running K8s nodes without understanding the kubelet impacts.

Q: How often should I re-run hardening? A: The bash script is for initial image creation. For running systems, use the Ansible role for continuous compliance, or rebuild nodes periodically from updated golden images.

Q: Can I contribute or report issues? A: Absolutely. The project welcomes contributions via GitHub issues and pull requests. Sponsorship is also available through GitHub Sponsors.

Conclusion

The gap between "works" and "secure" is where breaches are born. konstruktoid/hardening bridges that gap with ruthless efficiency, transforming Ubuntu's permissive defaults into a defensible, auditable, benchmark-aligned foundation.

This isn't security theater—it's 760 automated tests, SLSA-provenance, DISA STIG alignment, and decades of collective Linux security wisdom distilled into executable form. Whether you're building compliance-bound infrastructure, recovering from incidents, or simply refusing to be the next headline, this tool belongs in your arsenal.

The best time to harden your servers was before you deployed them. The second-best time is right now.

Clone konstruktoid/hardening today. Read the code. Test in your environment. Then sleep better knowing your attack surface just shrank by an order of magnitude. Your future self—and your security auditors—will thank you.

Comments (0)

Comments are moderated before appearing.

No comments yet. Be the first to share your thoughts!

Support us! ☕