- Posted on
- • Artificial Intelligence
Artificial Intelligence Linux Compliance Automation
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Artificial Intelligence + Linux Compliance Automation: From Scan to Remediation
If you’ve ever prepped Linux fleets for an audit, you know the grind: endless checklists, inconsistent hosts, and brittle scripts. What if you could plug deterministic scanners into an AI that triages findings, writes safe Bash remediations, and keeps you in continuous compliance?
This post shows how to build a practical, privacy-preserving workflow that turns compliance scans into actionable, reviewable Bash — using open tooling you can run on any distro.
Problem: Manual compliance is slow, error-prone, and doesn’t scale across heterogeneous fleets and fast-changing requirements.
Value: AI accelerates triage and remediation, while established scanners (OpenSCAP, Lynis) provide objective measurements. Together they deliver fast, explainable, and repeatable hardening.
Why AI for Linux compliance makes sense
Compliance is structured text: Scanner outputs (XCCDF, ARF, logs) map well to LLM summarization and code generation.
Most fixes are repeatable: Kernel params, SSH, file perms, and audit rules lend to idempotent Bash/Ansible.
AI reduces toil, not control: You still review changes; AI just drafts them faster.
Runs locally: With a local model runner, no sensitive data must leave your network.
Step 1: Install the core tooling
We’ll use:
OpenSCAP + SCAP Security Guide (SSG) for policy-aligned scans (CIS, DISA STIG, etc.)
Lynis for a second opinion and hygiene checks
auditd for audit capabilities
jq, xmlstarlet for parsing
Ollama to run a local LLM for triage/remediation suggestions
Install with your package manager:
- Debian/Ubuntu (apt):
sudo apt update
sudo apt install -y openscap-scanner scap-security-guide lynis auditd jq xmlstarlet curl
- Fedora/RHEL/CentOS (dnf):
sudo dnf install -y openscap-scanner scap-security-guide jq xmlstarlet curl audit
# Lynis is available in Fedora. On RHEL/CentOS enable EPEL first:
# sudo dnf install -y epel-release
sudo dnf install -y lynis
- openSUSE/SLE (zypper):
sudo zypper refresh
sudo zypper install -y openscap scap-security-guide lynis audit jq xmlstarlet curl
Install Ollama (runs local models; one-liner works on most distros):
curl -fsSL https://ollama.com/install.sh | sh
# After install, start the service if it didn't auto-start:
# systemctl --user start ollama
# Pull a small, capable model:
ollama pull llama3:8b
Notes:
Package names can vary slightly by distro/version. Adjust if necessary.
On RHEL-like systems,
auditprovidesauditd.If you can’t install Ollama system-wide, you can run it via container (Docker/Podman) or use another local runner (llama.cpp).
Step 2: Scan and collect machine-readable results
Find your SSG datastream and profile, then run a scan.
List available SSG datastreams:
ls /usr/share/xml/scap/ssg/content/*-ds*.xml
Inspect profiles inside a chosen datastream (replace $DS_PATH):
DS_PATH="/usr/share/xml/scap/ssg/content/ssg-rhel9-ds.xml" # example; pick what matches your OS
oscap info "$DS_PATH" | grep -E 'Profile|Id:'
Run an evaluation with results you can parse:
PROFILE="xccdf_org.ssgproject.content_profile_cis" # choose from oscap info output
sudo oscap xccdf eval \
--profile "$PROFILE" \
--results results-xccdf.xml \
--report report.html \
"$DS_PATH"
Run Lynis (produces lynis-report.dat and logs):
sudo lynis audit system --quiet --logfile lynis.log --report-file lynis-report.dat
Quickly extract failing OpenSCAP rule IDs (for triage):
xmlstarlet sel -t -m "//rule-result[result='fail']" -v "@idref" -n results-xccdf.xml | sort -u > failed-rules.txt
Step 3: Let AI draft safe, idempotent Bash remediations (locally)
We’ll prompt a local model to:
Propose minimal, idempotent remediations
Include rollbacks and comments
Target only the failing rules
Create a prompt and feed it findings:
PROMPT='You are a Linux compliance assistant. Based on the failing OpenSCAP rules
and Lynis notes, output a single, POSIX-compliant, idempotent Bash script that:
- Backs up any file it changes with a timestamp suffix.
- Uses set -Eeuo pipefail and safe defaults.
- Makes the minimal change needed to pass the checks.
- Adds comments mapping each change to the relevant rule/findings.
- Exits non-zero if any step fails.
Output ONLY the script, nothing else.'
FAILED_RULES="$(cat failed-rules.txt | paste -sd, -)"
LYNIS_TOP="$(grep -E 'warning|suggestion' -i lynis.log | tail -n 50)"
printf "%s\n\nFailed OpenSCAP rules:\n%s\n\nRecent Lynis notes:\n%s\n" \
"$PROMPT" "$FAILED_RULES" "$LYNIS_TOP" \
| ollama run llama3:8b > remediate.sh
Always review and lint before running:
head -n 40 remediate.sh
bash -n remediate.sh
chmod +x remediate.sh
Optional: constrain the model further by including exact rule descriptions. You can extract them like:
xmlstarlet sel -t -m "//Rule" -v "@id" -o " :: " -v "title" -n "$DS_PATH" \
| grep -Ff failed-rules.txt > failed-rule-titles.txt
Then append failed-rule-titles.txt into your prompt context.
Step 4: Apply, verify, and record evidence
Apply the generated script on a test host or container first:
sudo ./remediate.sh
Re-run scans to confirm:
sudo oscap xccdf eval \
--profile "$PROFILE" \
--results results-post-xccdf.xml \
--report report-post.html \
"$DS_PATH"
diff -u <(xmlstarlet sel -t -m "//rule-result[result='fail']" -v "@idref" -n results-xccdf.xml | sort) \
<(xmlstarlet sel -t -m "//rule-result[result='fail']" -v "@idref" -n results-post-xccdf.xml | sort) \
|| true
Archive artifacts for audit evidence:
tar czf evidence-$(date -u +%Y%m%dT%H%MZ).tar.gz \
report.html report-post.html results-xccdf.xml results-post-xccdf.xml \
lynis.log lynis-report.dat remediate.sh
Step 5: Operationalize (cron/systemd) for continuous compliance
Create a lightweight orchestrator script:
sudo install -m 0755 /dev/stdin /usr/local/sbin/compliance_scan.sh <<'EOF'
#!/usr/bin/env bash
set -Eeuo pipefail
DS_PATH="$(ls /usr/share/xml/scap/ssg/content/*-ds*.xml | head -n1)"
PROFILE="${PROFILE:-xccdf_org.ssgproject.content_profile_cis}"
RUN_DIR="/var/log/compliance"
mkdir -p "$RUN_DIR"
cd "$RUN_DIR"
TS="$(date -u +%Y%m%dT%H%MZ)"
oscap xccdf eval --profile "$PROFILE" --results "results-$TS.xml" --report "report-$TS.html" "$DS_PATH" || true
xmlstarlet sel -t -m "//rule-result[result='fail']" -v "@idref" -n "results-$TS.xml" | sort -u > "failed-$TS.txt"
if [ -s "failed-$TS.txt" ]; then
LYN="$(grep -E 'warning|suggestion' -i lynis.log 2>/dev/null | tail -n 50 || true)"
PROMPT='You are a Linux compliance assistant. Output only an idempotent Bash script (see previous instructions).'
printf "%s\n\nFailed OpenSCAP rules:\n%s\n\nRecent Lynis notes:\n%s\n" \
"$PROMPT" "$(paste -sd, "failed-$TS.txt")" "$LYN" \
| ollama run llama3:8b > "remediate-$TS.sh" || true
if head -n1 "remediate-$TS.sh" | grep -qE '^#!/'; then
bash -n "remediate-$TS.sh" && chmod +x "remediate-$TS.sh"
# Uncomment after review process is in place:
# sudo "./remediate-$TS.sh" || true
fi
fi
# Re-run Lynis periodically
if [ ! -f lynis.log ] || [ "$(find lynis.log -mtime +1 2>/dev/null | wc -l)" -gt 0 ]; then
sudo lynis audit system --quiet --logfile lynis.log --report-file lynis-report.dat || true
fi
EOF
Add a systemd timer:
sudo tee /etc/systemd/system/compliance-scan.service >/dev/null <<'EOF'
[Unit]
Description=AI-assisted Linux compliance scan and triage
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/compliance_scan.sh
EOF
sudo tee /etc/systemd/system/compliance-scan.timer >/dev/null <<'EOF'
[Unit]
Description=Run compliance scan daily
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now compliance-scan.timer
Real-world example: Hardening SSH with AI assistance
Typical failures: root login via SSH, weak ciphers/MACs, excessive auth tries. An AI-generated remediation might produce a script that:
Edits
sshd_configviasedwith a timestamped backupSets
PermitRootLogin no,PasswordAuthentication no(if keys are enforced),MaxAuthTries 3Restricts
Ciphers,MACs, andKexAlgorithmsto strong setsRestarts
sshdsafely if syntax validates (sshd -t)
Example snippet from a good remediation (review first!):
#!/usr/bin/env bash
set -Eeuo pipefail
TS="$(date -u +%Y%m%dT%H%MZ)"
CFG="/etc/ssh/sshd_config"
sudo cp -a "$CFG" "${CFG}.${TS}.bak"
apply_kv() {
local key="$1" val="$2"
sudo sed -ri "s|^[#\s]*${key}\b.*|${key} ${val}|g" "$CFG" || echo "${key} ${val}" | sudo tee -a "$CFG" >/dev/null
}
# Map to OpenSCAP rules: disable root login, strict auth, strong crypto
apply_kv "PermitRootLogin" "no"
apply_kv "MaxAuthTries" "3"
apply_kv "PasswordAuthentication" "no"
apply_kv "Ciphers" "chacha20-poly1305@openssh.com,aes256-gcm@openssh.com"
apply_kv "MACs" "hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com"
apply_kv "KexAlgorithms" "curve25519-sha256@libssh.org"
sudo sshd -t
sudo systemctl reload sshd
echo "SSHD hardened; backup at ${CFG}.${TS}.bak"
Re-scan after applying to verify the findings are resolved.
Guardrails and good practice
Always review AI output and test in staging first.
Keep changes minimal and reversible; commit scripts to version control.
Align profiles to your OS/version (CIS for Ubuntu 22.04 vs RHEL 9, etc.).
Document justified exceptions rather than fighting the scanner.
Prefer local models for sensitive data; if using a remote API, redact hostnames/paths.
Conclusion and next steps
AI won’t replace your security judgement — it multiplies it. By pairing deterministic scanners with a local LLM, you can move from “weeks of manual hardening” to “hours of reviewable automation,” with reproducible evidence for auditors.
Your next steps: 1. Install the toolchain with your package manager (see commands above). 2. Run OpenSCAP and Lynis on a non-production host. 3. Use Ollama to draft remediations; review, apply, and re-scan. 4. Automate with systemd timers and keep artifacts for audits.
Want a deeper dive or a ready-made repo with scripts and unit files? Tell me your distro and compliance target (CIS, STIG, PCI-DSS), and I’ll tailor a starter kit.