Lesson 04 AI-Assisted Security Hardening
Theme:
Lesson 04 · Slide 1

AI-Assisted Security Hardening

Using AI to systematically reduce attack surfaces, enforce compliance, and automate the hardening of infrastructure at scale.

What You Will Learn

  • Core hardening principles
  • CIS Benchmarks & STIG compliance
  • Linux, Windows, container & K8s hardening
  • AI-generated hardening scripts

CTF Challenge

Harden a vulnerable server configuration to pass all automated security checks.

Warning: Educational Use Only

Security hardening techniques should only be applied to systems you own or have authorization to configure. Improper hardening can cause service outages.

Lesson 04 · Slide 2

Why Security Hardening Matters

Default configurations are designed for ease of use, not security. Every unpatched default is an open door for attackers.

The AI Advantage

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.

Lesson 04 · Slide 3

Hardening Principle 1: Defense in Depth

No single control is sufficient. Layer multiple defenses so that failure of one does not compromise the system.

Notes: Ask the AI: "Given this architecture diagram, identify which layers lack hardening controls and suggest additions for each gap."
Lesson 04 · Slide 4

Hardening Principle 2: Least Privilege

Every user, process, and service should operate with the minimum permissions required to function.

Before (Over-Privileged)

  • App runs as root
  • Database user has GRANT ALL
  • Service account has admin API keys
  • World-readable config files

After (Least Privilege)

  • App runs as dedicated appuser
  • DB user has SELECT, INSERT only
  • Scoped API keys per service
  • Config files 0640 root:appgroup
Notes: AI prompt: "Audit this sudoers file and identify any entries that violate least privilege. Suggest specific replacements."
Lesson 04 · Slide 5

Hardening Principle 3: Attack Surface Reduction

Disable, remove, or restrict everything that is not explicitly required.

AI-Assisted Surface Audit

Feed 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.

Lesson 04 · Slide 6

CIS Benchmarks & STIG Compliance

Industry-standard hardening baselines that define exactly how a system should be configured.

StandardPublisherScopeFormat
CIS BenchmarksCenter for Internet SecurityOS, cloud, containers, appsPDF + automated tools
DISA STIGsUS Department of DefenseOS, network devices, appsXCCDF / SCAP
NIST 800-123NISTGeneral server hardeningGuidelines document
Microsoft SCTMicrosoftWindows, Edge, OfficeGPO baselines
Notes: CIS Benchmarks have two profiles: Level 1 (practical, minimal disruption) and Level 2 (defense-in-depth, may impact usability).
Lesson 04 · Slide 7

Using AI to Audit Against CIS Benchmarks

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()
    )}]
)
Notes: Always validate AI output against the official CIS benchmark document. AI may hallucinate control IDs.
Lesson 04 · Slide 8

Linux Hardening: SSH Configuration

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
Lesson 04 · Slide 9

Linux Hardening: Kernel Parameters (sysctl)

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

Lesson 04 · Slide 10

Linux Hardening: PAM & Sudoers

Pluggable Authentication Modules (PAM) control login policy. Sudoers defines privilege escalation rules.

PAM Password Quality (/etc/security/pwquality.conf)

minlen = 14
dcredit = -1
ucredit = -1
ocredit = -1
lcredit = -1
maxrepeat = 3
difok = 8
reject_username
enforce_for_root

Hardened Sudoers (/etc/sudoers.d/hardening)

# 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
Lesson 04 · Slide 11

Linux Hardening: File Permissions & Filesystem

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
Lesson 04 · Slide 12

Linux Hardening: AppArmor & SELinux

Mandatory Access Control (MAC) systems confine processes to only the resources they need, even if they run as root.

AppArmor (Ubuntu/Debian)

# 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,
}

SELinux (RHEL/CentOS)

# 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
Notes: Ask AI: "Generate an AppArmor profile for my custom Python web application running in /opt/myapp that needs access to /var/log/myapp and port 8080."
Lesson 04 · Slide 13

Windows Hardening: Group Policy

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)
Notes: Feed the exported secpol.cfg to AI and ask: "Compare this against CIS Windows Server 2022 Benchmark Level 1 and list all failures."
Lesson 04 · Slide 14

Windows Hardening: Defender & PowerShell Logging

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
Lesson 04 · Slide 15

Windows Hardening: Audit Policies

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:*

AI-Assisted Log Analysis

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?"

Lesson 04 · Slide 16

Container Hardening: Dockerfile Best Practices

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"]
Lesson 04 · Slide 17

Container Hardening: Seccomp & Read-Only FS

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
Lesson 04 · Slide 18

Container Hardening Checklist

A comprehensive checklist for container security, suitable for AI-assisted auditing.

CategoryCheckSeverity
ImageBase image is minimal (alpine/distroless)High
ImageNo secrets baked into image layersCritical
ImageImage is signed and from a trusted registryHigh
RuntimeContainer runs as non-root userCritical
RuntimeAll capabilities dropped, only needed ones addedHigh
RuntimeRead-only root filesystemMedium
RuntimeResource limits set (memory, CPU, PIDs)Medium
Runtimeno-new-privileges flag enabledHigh
NetworkHost network mode disabledHigh
StorageSensitive mounts are read-onlyMedium
Lesson 04 · Slide 19

Kubernetes Hardening: Pod Security Standards

Kubernetes Pod Security Standards (PSS) replace the deprecated PodSecurityPolicy with three built-in profiles.

ProfileDescriptionUse Case
PrivilegedNo restrictionsSystem-level workloads (logging agents)
BaselinePrevents known privilege escalationsMost workloads
RestrictedBest-practice pod hardeningSecurity-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
Lesson 04 · Slide 20

Kubernetes: Hardened Pod Specification

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
Lesson 04 · Slide 21

Kubernetes: NetworkPolicies

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
Notes: AI prompt: "Given these service dependencies, generate NetworkPolicies that implement a zero-trust microsegmentation model."
Lesson 04 · Slide 22

Kubernetes: RBAC Hardening

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"]

AI RBAC Audit

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.

Lesson 04 · Slide 23

Kubernetes: Admission Controllers

Admission controllers intercept API requests before persistence, enforcing policies at the cluster gate.

Built-in Controllers

  • PodSecurity — enforces Pod Security Standards
  • LimitRanger — enforces resource defaults
  • ResourceQuota — caps namespace resource usage
  • NodeRestriction — limits kubelet API access

Policy Engines

  • OPA/Gatekeeper — Rego-based policy
  • Kyverno — K8s-native YAML policies
  • Kubewarden — WebAssembly policies
  • AI-generated policies from natural language
# 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
Lesson 04 · Slide 24

AI-Generated Hardening Scripts

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)

Always Review Before Running

Never execute AI-generated hardening scripts without manual review. Test in a staging environment first. Incorrect changes can lock you out of the system.

Lesson 04 · Slide 25

AI-Generated Audit Checklists

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}]
)
Notes: These checklists can be converted into automated test suites — each "command" and "expected" pair becomes an assertion in a compliance scanner.
Lesson 04 · Slide 26

Automated Compliance Scanning with AI Overlay

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}]
)
Lesson 04 · Slide 27

Compliance Scanning Architecture

A complete pipeline from scanning to AI-prioritized remediation and drift detection.

Pipeline Flow

  1. Collect — Gather configs from hosts (Ansible facts, oscap, auditpol)
  2. Scan — Run against CIS/STIG baselines (OpenSCAP, InSpec, Prowler)
  3. Analyze — AI prioritizes failures by risk, blast radius, and dependencies
  4. Remediate — AI generates idempotent fix scripts with rollback
  5. Verify — Re-scan to confirm fixes, AI validates before/after delta
  6. Monitor — Continuous drift detection alerts on regression
ToolTargetStandards
OpenSCAPLinux serversCIS, DISA STIG
InSpecAny infrastructureCIS, custom profiles
ProwlerAWS accountsCIS AWS, PCI-DSS
kube-benchKubernetes clustersCIS Kubernetes Benchmark
ScoutSuiteMulti-cloudCIS, custom rules
Lesson 04 · Slide 28

Hardening Anti-Patterns

Common mistakes that make hardening efforts ineffective or counterproductive.

Do Not

  • Harden without testing — changes can break applications silently
  • Copy-paste configs — every environment needs tailored settings
  • Harden once, forget — drift happens within days
  • Ignore application layer — OS hardening alone is insufficient
  • Disable SELinux/AppArmor because it is "annoying"

Best Practices

  • Test in staging before production rollout
  • Version-control configs and track changes in Git
  • Continuous compliance scanning on schedule
  • Document exceptions with risk acceptance sign-off
  • Use AI to explain each setting to the team
Lesson 04 · Slide 29

Full-Stack Hardening Summary

LayerKey ActionsAI Use
Linux OSsysctl, PAM, SSH, file perms, MACAudit configs against CIS, generate scripts
WindowsGPO, Defender ASR, audit policiesAnalyze secpol exports, map to ATT&CK
ContainersNon-root, read-only FS, seccomp, cap-dropReview Dockerfiles, generate seccomp profiles
KubernetesPSS, NetworkPolicy, RBAC, admissionAudit RBAC, generate policies from intent
ComplianceCIS Benchmarks, STIGs, continuous scanningPrioritize findings, explain risk, generate fixes

Key Takeaway

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.

Lesson 04 · Slide 30

CTF Challenge: Harden the Vulnerable Server

You are given a deliberately misconfigured server. Your mission: harden it to pass all automated security checks.

Scenario

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.

Vulnerabilities to Find and Fix

Notes: Students should use AI to analyze the initial configuration dump, generate a prioritized remediation plan, and produce hardening scripts — then verify with a compliance scanner.
Lesson 04 · Slide 31

CTF Challenge: Scoring Rubric

CategoryPointsCriteria
SSH Hardening20All CIS SSH controls pass
Kernel Parameters15All sysctl hardening applied
File Permissions15Critical files properly secured
Service Minimization10Unnecessary services disabled
Firewall Configuration10Default deny, explicit allow rules
Container Hardening15Non-root, read-only, cap-drop, limits
Authentication10PAM, password policy, sudoers locked down
Bonus: AI Usage5Document how AI assisted your approach

Success Criteria

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.

Lesson 04 · Slide 32

Resources & Next Steps

Up Next: Lesson 05

Network traffic analysis and intrusion detection — using AI to identify anomalies in packet captures and flow data.

Warning: Educational Use Only

Security hardening techniques should only be applied to systems you own or have authorization to configure. Improper hardening can cause service outages.

1 / ?