Using AI to systematically reduce attack surfaces, enforce compliance, and automate the hardening of infrastructure at scale.
Harden a vulnerable server configuration to pass all automated security checks.
Security hardening techniques should only be applied to systems you own or have authorization to configure. Improper hardening can cause service outages.
Default configurations are designed for ease of use, not security. Every unpatched default is an open door for attackers.
AI can audit thousands of configuration files against hardening standards in seconds, generate remediation scripts, and explain why each change matters — turning a week-long audit into a one-hour workflow.
No single control is sufficient. Layer multiple defenses so that failure of one does not compromise the system.
Every user, process, and service should operate with the minimum permissions required to function.
rootGRANT ALLappuserSELECT, INSERT only0640 root:appgroupDisable, remove, or restrict everything that is not explicitly required.
apt purge telnet rsh-clientsystemctl disable avahi-daemon cupsFeed your system's ss -tlnp output and installed package list to the AI. Ask it to flag every listening service and package that is not in your approved baseline.
Industry-standard hardening baselines that define exactly how a system should be configured.
| Standard | Publisher | Scope | Format |
|---|---|---|---|
| CIS Benchmarks | Center for Internet Security | OS, cloud, containers, apps | PDF + automated tools |
| DISA STIGs | US Department of Defense | OS, network devices, apps | XCCDF / SCAP |
| NIST 800-123 | NIST | General server hardening | Guidelines document |
| Microsoft SCT | Microsoft | Windows, Edge, Office | GPO baselines |
Instead of manually reading a 300-page CIS PDF, use AI to map your configuration to specific benchmark controls.
# AI-assisted CIS benchmark audit
prompt = """You are a CIS Benchmark auditor for Ubuntu 22.04 (Level 1).
Analyze this sshd_config and report:
1. Each CIS control ID that applies
2. PASS or FAIL status
3. Remediation command for failures
sshd_config:
{config_content}
Output as a markdown table: | CIS ID | Description | Status | Remediation |"""
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
messages=[{"role": "user", "content": prompt.format(
config_content=open("/etc/ssh/sshd_config").read()
)}]
)
SSH is the most critical remote access service. A hardened sshd_config is the first line of defense.
# /etc/ssh/sshd_config — Hardened Configuration
Protocol 2
Port 2222
# Authentication
PermitRootLogin no
MaxAuthTries 3
PubkeyAuthentication yes
PasswordAuthentication no
PermitEmptyPasswords no
AuthenticationMethods publickey
# Session Security
ClientAliveInterval 300
ClientAliveCountMax 2
LoginGraceTime 60
MaxSessions 3
MaxStartups 10:30:60
# Cryptography (CIS 5.2.13-5.2.15)
KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
# Restrictions
AllowGroups sshusers
X11Forwarding no
AllowTcpForwarding no
AllowAgentForwarding no
Banner /etc/issue.net
Kernel parameters control networking behavior, memory protection, and system security at the deepest OS level.
# /etc/sysctl.d/99-hardening.conf
# Network Security
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.log_martians = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.tcp_syncookies = 1
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_ra = 0
# Memory Protection
kernel.randomize_va_space = 2
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
kernel.yama.ptrace_scope = 2
# Filesystem Hardening
fs.protected_hardlinks = 1
fs.protected_symlinks = 1
fs.suid_dumpable = 0
Apply with: sudo sysctl --system
Pluggable Authentication Modules (PAM) control login policy. Sudoers defines privilege escalation rules.
minlen = 14
dcredit = -1
ucredit = -1
ocredit = -1
lcredit = -1
maxrepeat = 3
difok = 8
reject_username
enforce_for_root
# Require password re-entry after 5 minutes
Defaults timestamp_timeout=5
Defaults passwd_tries=3
Defaults logfile="/var/log/sudo.log"
Defaults log_input, log_output
Defaults use_pty
Defaults !visiblepw
# Specific command allowlists — never use ALL
%ops ALL=(ALL) /usr/bin/systemctl restart nginx, \
/usr/bin/systemctl restart postgresql
%deploy ALL=(deploy) NOPASSWD: /opt/deploy/run.sh
Critical system files must have strict ownership and permissions to prevent tampering.
#!/bin/bash
# AI-generated file permission hardening script
# Critical file permissions (CIS Benchmark 6.1)
chmod 644 /etc/passwd
chmod 000 /etc/shadow
chmod 644 /etc/group
chmod 000 /etc/gshadow
chmod 600 /etc/ssh/sshd_config
chmod 700 /root
chmod 600 /boot/grub/grub.cfg
# Find world-writable files (excluding expected paths)
find / -xdev -type f -perm -0002 \
-not -path '/proc/*' \
-not -path '/sys/*' \
-exec chmod o-w {} \;
# Find SUID/SGID binaries
find / -xdev \( -perm -4000 -o -perm -2000 \) -type f \
| while read f; do
echo "REVIEW: $f has SUID/SGID bit set"
done
# Mount options hardening in /etc/fstab
# /tmp tmpfs defaults,noexec,nosuid,nodev 0 0
# /var/tmp tmpfs defaults,noexec,nosuid,nodev 0 0
# /dev/shm tmpfs defaults,noexec,nosuid,nodev 0 0
Mandatory Access Control (MAC) systems confine processes to only the resources they need, even if they run as root.
# Check status
aa-status
# Set profile to enforce mode
aa-enforce /etc/apparmor.d/usr.sbin.nginx
# Example nginx profile
/usr/sbin/nginx {
/etc/nginx/** r,
/var/log/nginx/** w,
/var/www/** r,
/run/nginx.pid rw,
network inet stream,
deny /etc/shadow r,
deny /home/** rwx,
}
# Check status
getenforce
# Set enforcing
setenforce 1
# View context labels
ls -Z /var/www/html/
# Fix context after file move
restorecon -Rv /var/www/html/
# Audit denials
ausearch -m avc -ts recent \
| audit2why
Group Policy Objects (GPOs) are the primary mechanism for enforcing security configuration across Windows environments.
# Export current security policy for AI analysis
secedit /export /cfg C:\Temp\secpol.cfg
# Key GPO hardening settings
# Computer Configuration > Windows Settings > Security Settings
# Account Policies > Password Policy
# - Minimum password length: 14 characters
# - Password complexity: Enabled
# - Maximum password age: 60 days
# - Enforce password history: 24 passwords
# Account Policies > Account Lockout Policy
# - Account lockout threshold: 5 invalid attempts
# - Account lockout duration: 30 minutes
# - Reset counter after: 30 minutes
# Local Policies > User Rights Assignment
# - Deny log on locally: Guests
# - Deny access from network: Guests, Local account
# - Debug programs: (empty — remove all users)
Windows Defender configuration and comprehensive logging are essential for detection and forensics.
# Windows Defender hardening
Set-MpPreference -DisableRealtimeMonitoring $false
Set-MpPreference -MAPSReporting Advanced
Set-MpPreference -SubmitSamplesConsent SendAllSamples
Set-MpPreference -PUAProtection Enabled
Set-MpPreference -EnableNetworkProtection Enabled
# Attack Surface Reduction (ASR) rules
$rules = @(
"BE9BA2D9-53EA-4CDC-84E5-9B1EEEE46550", # Block executable content from email
"D4F940AB-401B-4EFC-AADC-AD5F3C50688A", # Block Office child processes
"3B576869-A4EC-4529-8536-B80A7769E899", # Block Office creating executables
"75668C1F-73B5-4CF0-BB93-3ECF5CB7CC84", # Block Office code injection
"D3E037E1-3EB8-44C8-A917-57927947596D" # Block JS/VBS launching executables
)
foreach ($rule in $rules) {
Add-MpPreference -AttackSurfaceReductionRules_Ids $rule `
-AttackSurfaceReductionRules_Actions Enabled
}
# PowerShell script block logging (critical for forensics)
# Via GPO: Administrative Templates > Windows PowerShell
# - Turn on Module Logging: Enabled (*)
# - Turn on Script Block Logging: Enabled
# - Turn on Transcription: Enabled, include invocation headers
Advanced audit policies generate the events needed to detect intrusions, lateral movement, and privilege escalation.
# Configure advanced audit policies via auditpol
auditpol /set /subcategory:"Logon" /success:enable /failure:enable
auditpol /set /subcategory:"Logoff" /success:enable
auditpol /set /subcategory:"Account Lockout" /success:enable /failure:enable
auditpol /set /subcategory:"Special Logon" /success:enable
auditpol /set /subcategory:"Process Creation" /success:enable
auditpol /set /subcategory:"Sensitive Privilege Use" /success:enable /failure:enable
auditpol /set /subcategory:"Security Group Management" /success:enable
auditpol /set /subcategory:"User Account Management" /success:enable /failure:enable
auditpol /set /subcategory:"Authentication Policy Change" /success:enable
# Enable command-line logging in process creation events
reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\Audit" `
/v ProcessCreationIncludeCmdLine_Enabled /t REG_DWORD /d 1 /f
# Verify configuration
auditpol /get /category:*
Feed audit policy output to AI: "Compare my auditpol configuration against MITRE ATT&CK data sources. Which techniques would I miss detecting with my current logging?"
Containers inherit the host kernel but their images can be hardened to minimize risk.
# HARDENED Dockerfile — multi-stage, non-root, minimal
FROM python:3.11-slim AS builder
WORKDIR /build
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
FROM python:3.11-slim
# Security: create non-root user
RUN groupadd -r appgroup && \
useradd -r -g appgroup -d /app -s /sbin/nologin appuser
# Security: copy only what we need
COPY --from=builder /install /usr/local
COPY --chown=appuser:appgroup . /app
WORKDIR /app
# Security: drop all capabilities, remove shells
RUN apt-get purge -y --auto-remove && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* && \
rm -f /usr/bin/wget /usr/bin/curl && \
chmod -R 550 /app
# Security: read-only filesystem friendly
ENV PYTHONDONTWRITEBYTECODE=1
EXPOSE 8080
# Security: run as non-root
USER appuser:appgroup
# Security: use exec form, no shell
ENTRYPOINT ["python", "app.py"]
Seccomp profiles restrict which system calls a container can make. Read-only filesystems prevent runtime tampering.
{
"defaultAction": "SCMP_ACT_ERRNO",
"architectures": ["SCMP_ARCH_X86_64"],
"syscalls": [
{
"names": [
"read", "write", "open", "close", "stat", "fstat",
"mmap", "mprotect", "munmap", "brk", "ioctl",
"access", "pipe", "select", "poll", "socket",
"connect", "accept", "bind", "listen", "clone",
"execve", "exit", "exit_group", "futex",
"getpid", "getuid", "getgid"
],
"action": "SCMP_ACT_ALLOW"
}
]
}
# Run container with hardening flags
docker run -d \
--read-only \
--tmpfs /tmp:noexec,nosuid,size=64m \
--security-opt no-new-privileges:true \
--security-opt seccomp=hardened-profile.json \
--cap-drop ALL \
--cap-add NET_BIND_SERVICE \
--memory 512m --cpus 1 \
--pids-limit 100 \
myapp:latest
A comprehensive checklist for container security, suitable for AI-assisted auditing.
| Category | Check | Severity |
|---|---|---|
| Image | Base image is minimal (alpine/distroless) | High |
| Image | No secrets baked into image layers | Critical |
| Image | Image is signed and from a trusted registry | High |
| Runtime | Container runs as non-root user | Critical |
| Runtime | All capabilities dropped, only needed ones added | High |
| Runtime | Read-only root filesystem | Medium |
| Runtime | Resource limits set (memory, CPU, PIDs) | Medium |
| Runtime | no-new-privileges flag enabled | High |
| Network | Host network mode disabled | High |
| Storage | Sensitive mounts are read-only | Medium |
Kubernetes Pod Security Standards (PSS) replace the deprecated PodSecurityPolicy with three built-in profiles.
| Profile | Description | Use Case |
|---|---|---|
| Privileged | No restrictions | System-level workloads (logging agents) |
| Baseline | Prevents known privilege escalations | Most workloads |
| Restricted | Best-practice pod hardening | Security-sensitive workloads |
# Enforce restricted profile on a namespace
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/enforce-version: latest
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/warn: restricted
A production-ready pod spec that passes the Restricted Pod Security Standard.
apiVersion: v1
kind: Pod
metadata:
name: hardened-app
namespace: production
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
fsGroup: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: registry.example.com/myapp:v1.2.3@sha256:abc123...
resources:
limits:
memory: "256Mi"
cpu: "500m"
requests:
memory: "128Mi"
cpu: "250m"
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir:
sizeLimit: 64Mi
By default, all pods can communicate with all other pods. NetworkPolicies implement microsegmentation.
# Default deny all ingress and egress
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: production
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
---
# Allow specific traffic: web -> api on port 8080
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-web-to-api
namespace: production
spec:
podSelector:
matchLabels:
app: api
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: web
ports:
- protocol: TCP
port: 8080
Role-Based Access Control in Kubernetes must follow least privilege. Overly broad ClusterRoles are a common attack vector.
# BAD: Overly permissive ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: too-permissive
rules:
- apiGroups: ["*"]
resources: ["*"]
verbs: ["*"] # NEVER DO THIS
---
# GOOD: Scoped Role for a deployment operator
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: deployment-operator
namespace: production
rules:
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "list", "watch", "update", "patch"]
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
- apiGroups: [""]
resources: ["pods/log"]
verbs: ["get"]
Export all roles with kubectl get clusterroles,roles -A -o yaml and ask AI to identify any that grant wildcard permissions, secrets access, or pod exec capabilities.
Admission controllers intercept API requests before persistence, enforcing policies at the cluster gate.
# Kyverno policy: require non-root containers
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-non-root
spec:
validationFailureAction: Enforce
rules:
- name: check-non-root
match:
any:
- resources:
kinds: ["Pod"]
validate:
message: "Containers must run as non-root"
pattern:
spec:
containers:
- securityContext:
runAsNonRoot: true
Use AI to generate comprehensive, auditable hardening scripts tailored to your specific environment.
hardening_prompt = """Generate a bash hardening script for Ubuntu 22.04 LTS
that implements CIS Benchmark Level 1. The script must:
1. Be idempotent (safe to run multiple times)
2. Log every change to /var/log/hardening.log
3. Create backups before modifying any file
4. Include rollback instructions in comments
5. Cover these categories:
- Filesystem configuration (mount options, permissions)
- SSH hardening
- Kernel parameters (sysctl)
- Firewall rules (UFW)
- Service disablement
- Authentication (PAM, password policy)
- Audit daemon configuration
Output the complete script with section headers."""
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=8192,
messages=[{"role": "user", "content": hardening_prompt}]
)
# Save and review before executing
with open("harden.sh", "w") as f:
f.write(response.content[0].text)
Never execute AI-generated hardening scripts without manual review. Test in a staging environment first. Incorrect changes can lock you out of the system.
Ask AI to produce structured, role-specific hardening checklists from your infrastructure context.
checklist_prompt = """Based on the following server role and configuration,
generate a security hardening checklist in JSON format.
Server role: PostgreSQL database server
OS: Ubuntu 22.04
Network: Internal only, accessed from app tier
Compliance: SOC 2 Type II
For each item include:
- category (os, network, database, auth, logging)
- check: what to verify
- command: verification command
- expected: expected output
- remediation: fix command
- cis_ref: CIS Benchmark reference if applicable
- severity: critical, high, medium, low"""
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=8192,
messages=[{"role": "user", "content": checklist_prompt}]
)
Combine traditional scanning tools with AI analysis for deeper, more actionable results.
import subprocess
import json
# Step 1: Run OpenSCAP baseline scan
result = subprocess.run(
["oscap", "xccdf", "eval",
"--profile", "xccdf_org.ssgproject.content_profile_cis_level1_server",
"--results-arf", "/tmp/scan-results.xml",
"--report", "/tmp/scan-report.html",
"/usr/share/xml/scap/ssg/content/ssg-ubuntu2204-ds.xml"],
capture_output=True, text=True
)
# Step 2: Parse results to extract failures
failures = parse_arf_results("/tmp/scan-results.xml")
# Step 3: Feed failures to AI for prioritized remediation
analysis_prompt = f"""You are a security hardening specialist.
These are the failed CIS Benchmark checks from an OpenSCAP scan:
{json.dumps(failures, indent=2)}
For each failure:
1. Explain the risk in plain language
2. Provide the exact remediation command
3. Rate the risk if left unpatched (1-10)
4. Flag any that could cause service disruption
5. Suggest a safe order of remediation
Sort by risk rating descending."""
ai_analysis = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=8192,
messages=[{"role": "user", "content": analysis_prompt}]
)
A complete pipeline from scanning to AI-prioritized remediation and drift detection.
oscap, auditpol)| Tool | Target | Standards |
|---|---|---|
| OpenSCAP | Linux servers | CIS, DISA STIG |
| InSpec | Any infrastructure | CIS, custom profiles |
| Prowler | AWS accounts | CIS AWS, PCI-DSS |
| kube-bench | Kubernetes clusters | CIS Kubernetes Benchmark |
| ScoutSuite | Multi-cloud | CIS, custom rules |
Common mistakes that make hardening efforts ineffective or counterproductive.
| Layer | Key Actions | AI Use |
|---|---|---|
| Linux OS | sysctl, PAM, SSH, file perms, MAC | Audit configs against CIS, generate scripts |
| Windows | GPO, Defender ASR, audit policies | Analyze secpol exports, map to ATT&CK |
| Containers | Non-root, read-only FS, seccomp, cap-drop | Review Dockerfiles, generate seccomp profiles |
| Kubernetes | PSS, NetworkPolicy, RBAC, admission | Audit RBAC, generate policies from intent |
| Compliance | CIS Benchmarks, STIGs, continuous scanning | Prioritize findings, explain risk, generate fixes |
AI does not replace security expertise — it amplifies it. Use AI to handle the tedious configuration auditing at scale, while human judgment drives risk prioritization and exception handling.
You are given a deliberately misconfigured server. Your mission: harden it to pass all automated security checks.
A web server running Ubuntu 22.04 has been deployed with default settings. It runs SSH, Nginx, and a Python API. The compliance scanner currently reports 47 failures against CIS Level 1. You must bring it to zero failures.
| Category | Points | Criteria |
|---|---|---|
| SSH Hardening | 20 | All CIS SSH controls pass |
| Kernel Parameters | 15 | All sysctl hardening applied |
| File Permissions | 15 | Critical files properly secured |
| Service Minimization | 10 | Unnecessary services disabled |
| Firewall Configuration | 10 | Default deny, explicit allow rules |
| Container Hardening | 15 | Non-root, read-only, cap-drop, limits |
| Authentication | 10 | PAM, password policy, sudoers locked down |
| Bonus: AI Usage | 5 | Document how AI assisted your approach |
Run the provided check_hardening.sh script. A score of 90+ points means the server is hardened. Full marks require zero CIS Level 1 failures and a documented AI-assisted workflow.
cisecurity.org/cis-benchmarks (free PDF registration)public.cyber.mil/stigsopen-scap.orggithub.com/aquasecurity/kube-benchgithub.com/docker/docker-bench-securitycisofy.com/lynis (Linux auditing tool)Network traffic analysis and intrusion detection — using AI to identify anomalies in packet captures and flow data.
Security hardening techniques should only be applied to systems you own or have authorization to configure. Improper hardening can cause service outages.