Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 25 min · revision 2

Compliance Scanning and Drift Control as Code

Scan a Debian 12 server with OpenSCAP and the CIS Level 1 profile, enforce the baseline with an idempotent Ansible playbook, store results per host and rule, then introduce drift, detect it with check mode and a rescan, and converge the host again.

Contentsand lesson path

What you will learn

  • Automate baseline compliance checks and remediation with a scanner such as OpenSCAP or Lynis plus configuration management, and track drift over time.

Prerequisites: Linux CLI

01. Goal and setup

In lab 2 you hardened one server by hand. On a real estate, settings drift: someone edits a file during an incident, or a package pulls in an old client. Drift is the gap between the agreed baseline and the real state of a host. In this lab you build the loop that keeps that gap small. A scanner measures the host against the CIS profile, Ansible enforces the baseline as code, and every result is stored, so that you can see which rule changed and when.

You will scan a Debian 12 container with the real CIS Level 1 Server profile, enforce eleven of its rules with a playbook, then break three settings, detect the drift and fix it.

You need: Docker, uv (it installs Python 3.13 and Ansible in the lab folder) and about 800 MB of free disk. Tested versions: Debian 12 (bookworm) packages, OpenSCAP 1.3.7 (the Debian 12 package), SCAP Security Guide 0.1.82, ansible-core 2.21.6 (2.22.0 came out the same day) and the community.docker collection 5.4.0.

OpenSCAP is an open-source scanner for SCAP (Security Content Automation Protocol), a family of standard formats for machine-readable checks. The SCAP Security Guide (SSG), from the ComplianceAsCode project, is the content. For each system it ships a data stream: one XML file with rules, the checks behind them, and profiles that select rules. The scanner reports one result per rule, such as pass, fail or notapplicable. Check which benchmark version a profile follows: the Debian 12 CIS profile in SSG 0.1.82 aligns to CIS Benchmark v1.1.0, not the newest release.

Lynis, from lab 2, is another scanner. Scanners measure and change nothing, so this lab adds configuration management to make the changes.

Lab folder
drift-lab/
├── ansible.cfg           Ansible settings for this folder
├── inventory.ini         the host to manage and how to reach it
├── baseline.yml          the baseline as an Ansible playbook
├── files/60-baseline.conf  kernel parameters (the file from lab 2)
├── rules.txt             the CIS rules this lab tracks
├── exceptions.csv        accepted deviations, with owner and expiry
├── scan.sh               runs OpenSCAP and stores the results
├── trend.py              compares stored scans rule by rule
├── ssg-debian12-ds.xml   SCAP content, downloaded below
└── results/              created by scan.sh

Download SSG 0.1.82, check it against the published SHA-512 file and extract the Debian 12 data stream. Stay in drift-lab/ from now on; you may delete the 180 MB archive.

Terminal
mkdir -p drift-lab/files && cd drift-lab
R=https://github.com/ComplianceAsCode/content/releases/download/v0.1.82
curl -sSLO "$R/scap-security-guide-0.1.82.zip"
curl -sSL "$R/scap-security-guide-0.1.82.zip.sha512" | sha512sum -c
unzip -j -q scap-security-guide-0.1.82.zip \
  scap-security-guide-0.1.82/ssg-debian12-ds.xml
ls -l ssg-debian12-ds.xml | awk '{print $5, $NF}'
Expected output
scap-security-guide-0.1.82.zip: OK
15131621 ssg-debian12-ds.xml

Save the files below. Ansible reads ansible.cfg from the current folder. inventory.ini puts one host, drift-lab, in a group called baseline. Instead of SSH, the community.docker.docker connection runs each task through docker exec. manage_services=false stops the playbook from reloading services, because the container has no init system.

INI · ansible.cfg
[defaults]
inventory = inventory.ini
collections_path = ./collections
interpreter_python = /usr/bin/python3
display_skipped_hosts = False
callback_result_format = yaml
INI · inventory.ini
[baseline]
drift-lab ansible_host=drift-lab

[baseline:vars]
ansible_connection=community.docker.docker
manage_services=false

The playbook is the baseline as code. Each task states a desired state: this block is at the top of sshd_config, this file has mode 0640, these packages are absent. Ansible changes only what differs and reports changed; a task that found the host correct reports ok. Because a second run on a correct host changes nothing, a property called idempotence, you can run the playbook every night.

Three details matter for security:

  • blockinfile writes the SSH settings at the top of sshd_config, between markers. sshd keeps the first value it reads (lab 2, step 3), so this block wins over later lines and drop-ins. validate tests the new file with sshd -t before it replaces the old one.
  • The last two tasks read the effective settings with sshd -T and assert two values. check_mode: false makes the read run even in check mode (step 8).
  • Handlers reload sshd and apply the kernel settings only after a change, and only when manage_services is true.

The Ciphers line includes aes128-cbc, which the CIS rule rejects. In this story a backup appliance needs it, so the team accepted a deviation until the appliance is replaced.

YAML · baseline.yml
- name: Enforce the Debian 12 server baseline
  hosts: baseline
  vars:
    ssh_baseline: |
      PermitRootLogin no
      PermitEmptyPasswords no
      MaxAuthTries 4
      LoginGraceTime 60
      ClientAliveInterval 300
      ClientAliveCountMax 3
      LogLevel INFO
      Ciphers [email protected],[email protected],aes128-cbc
  tasks:
    - name: SSH settings at the top of sshd_config, before any drop-in
      ansible.builtin.blockinfile:
        path: /etc/ssh/sshd_config
        insertbefore: BOF
        marker: "# {mark} BASELINE (managed by Ansible, do not edit)"
        block: "{{ ssh_baseline }}"
        validate: /usr/sbin/sshd -t -f %s
      notify: Reload sshd

    - name: sshd_config is readable by root only
      ansible.builtin.file:
        path: /etc/ssh/sshd_config
        owner: root
        group: root
        mode: "0600"

    - name: Password hashes are readable by root and group shadow only
      ansible.builtin.file:
        path: /etc/shadow
        owner: root
        group: shadow
        mode: "0640"

    - name: No cleartext remote-access clients or servers
      ansible.builtin.apt:
        name: [inetutils-telnet, inetutils-telnetd, inetutils-ftpd, vsftpd]
        state: absent
        purge: true

    - name: Kernel parameters file
      ansible.builtin.copy:
        src: files/60-baseline.conf
        dest: /etc/sysctl.d/60-baseline.conf
        mode: "0644"
      notify: Apply sysctl

    - name: Read the effective sshd configuration
      ansible.builtin.command: /usr/sbin/sshd -T
      register: sshd_effective
      changed_when: false
      check_mode: false

    - name: Effective settings match the baseline (catches drop-in overrides)
      ansible.builtin.assert:
        that:
          - "'permitrootlogin no' in sshd_effective.stdout_lines"
          - "'maxauthtries 4' in sshd_effective.stdout_lines"
        quiet: true

  handlers:
    - name: Reload sshd
      ansible.builtin.service:
        name: ssh
        state: reloaded
      when: manage_services | bool

    - name: Apply sysctl
      ansible.builtin.command: sysctl --system
      when: manage_services | bool
Text · files/60-baseline.conf
# /etc/sysctl.d/60-baseline.conf: kernel parameters from the baseline.
# Apply on a VM with: sysctl --system
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.rp_filter = 1
net.ipv4.tcp_syncookies = 1
kernel.randomize_va_space = 2
kernel.yama.ptrace_scope = 1
fs.suid_dumpable = 0

rules.txt lists the eleven rules this playbook enforces. exceptions.csv is lesson 1's deviation register in a form a script can read: one accepted failure, with owner, expiry date and ticket.

Text · rules.txt
sshd_disable_root_login
sshd_disable_empty_passwords
sshd_set_max_auth_tries
sshd_set_login_grace_time
sshd_set_idle_timeout
sshd_set_keepalive
sshd_set_loglevel_info
sshd_use_strong_ciphers
file_permissions_sshd_config
file_permissions_etc_shadow
package_inetutils-telnet_removed
CSV · exceptions.csv
rule,host,owner,expires,ticket
sshd_use_strong_ciphers,drift-lab,r.osei,2027-03-31,CHG-4411

scan.sh runs only the tracked rules of the CIS profile (--rule may repeat). It keeps the ARF file (Asset Reporting Format), the full machine-readable result an auditor can read later, and appends one row per date, host and rule to results.csv. The oscap manual says exit code 2 means the scan worked but the system is not compliant, so the script accepts it. The date is a parameter to keep this lab repeatable; a scheduler would pass today's date.

Bash · scan.sh
#!/bin/bash
# scan.sh SCAN_DATE: run the tracked CIS rules with OpenSCAP inside the
# container, keep the raw ARF report, and append one CSV row per rule.
set -euo pipefail
scan_date=$1
container=${CONTAINER:-drift-lab}
profile=xccdf_org.ssgproject.content_profile_cis_level1_server
args=()
while read -r rule; do
  args+=(--rule "xccdf_org.ssgproject.content_rule_$rule")
done < rules.txt
mkdir -p results
# oscap exits 2 when any rule fails; that is a result, not an error.
docker exec "$container" oscap xccdf eval --profile "$profile" "${args[@]}" \
  --results-arf /tmp/arf.xml /ssg/ds.xml > "results/$scan_date.txt" 2>/dev/null \
  || [ $? -eq 2 ]
docker cp -q "$container:/tmp/arf.xml" "results/$scan_date-arf.xml"
host=$(docker exec "$container" hostname)
[ -f results/results.csv ] || echo "scan_date,host,rule,result" > results/results.csv
awk -v d="$scan_date" -v h="$host" '
  /^Rule/   { r = $2; sub(/.*content_rule_/, "", r) }
  /^Result/ { print d "," h "," r "," $2 }' "results/$scan_date.txt" \
  | sort >> results/results.csv
grep "^$scan_date," results/results.csv | cut -d, -f4 | sort | uniq -c \
  | awk -v d="$scan_date" '{printf "%s %s=%s\n", d, $2, $1}'

trend.py reads the stored scans in date order. For each scan it prints the counts, then a line for each rule whose status changed: REGRESSED for pass to fail, fixed for fail to pass or excepted. A failure listed in exceptions.csv counts as excepted until the expiry date.

Python · trend.py
"""trend.py: summarise stored scan results and show what changed per rule."""
import csv
from collections import defaultdict

exceptions = {}
with open("exceptions.csv", newline="") as f:
    for row in csv.DictReader(f):
        exceptions[(row["host"], row["rule"])] = row

scans = defaultdict(dict)  # scan_date -> {(host, rule): status}
with open("results/results.csv", newline="") as f:
    for row in csv.DictReader(f):
        key = (row["host"], row["rule"])
        status = row["result"]
        exc = exceptions.get(key)
        # ISO dates compare correctly as strings.
        if status == "fail" and exc and row["scan_date"] <= exc["expires"]:
            status = "excepted"
        scans[row["scan_date"]][key] = status

previous = {}
for scan_date in sorted(scans):
    current = scans[scan_date]
    counts = defaultdict(int)
    for status in current.values():
        counts[status] += 1
    print(f"{scan_date}  pass={counts['pass']:<3} fail={counts['fail']:<3} "
          f"excepted={counts['excepted']}")
    for key in sorted(current):
        before, after = previous.get(key), current[key]
        if before == "pass" and after == "fail":
            print(f"    REGRESSED {key[0]} {key[1]}")
        elif before == "fail" and after in ("pass", "excepted"):
            print(f"    fixed     {key[0]} {key[1]} ({after})")
    previous = current

02. Step 1: Start the server

Start a Debian 12 container with the data stream mounted read-only, and install Python (for Ansible), the OpenSSH server and the OpenSCAP scanner.

SSG skips many rules when the target looks like a container (it checks for /.dockerenv) or has no kernel package (it checks for linux-base). Removing the file and installing the package make those rules apply. Do this only in a lab; in a real container image those rules really do not apply.

Terminal
docker run -d --init --name drift-lab --hostname drift-lab \
  -v "$PWD/ssg-debian12-ds.xml":/ssg/ds.xml:ro debian:12-slim sleep infinity >/dev/null
docker exec drift-lab bash -c 'apt-get update -qq &&
  apt-get install -y -qq --no-install-recommends python3 openssh-server \
  openscap-scanner linux-base >/dev/null 2>&1 && echo "packages installed"
  rm -f /.dockerenv; mkdir -p /run/sshd; oscap --version | head -1'
Expected output
packages installed
OpenSCAP command line tool (oscap) 1.3.7

03. Step 2: Install Ansible and reach the host

Install a pinned ansible-core and the Docker connection collection into the lab folder, then check that Ansible reaches the container. The ping module runs Python on the target; it is not a network ping.

Terminal
uv venv -q --python 3.13 .venv
uv pip install -q --python .venv/bin/python ansible-core==2.21.6
.venv/bin/ansible-galaxy collection install -p ./collections \
  community.docker:==5.4.0 >/dev/null
.venv/bin/ansible --version | head -1
.venv/bin/ansible drift-lab -m ansible.builtin.ping
Expected output
ansible [core 2.21.6]
drift-lab | SUCCESS =>
    changed: false
    ping: pong

04. Step 3: Run the full CIS profile once

Run the whole Level 1 Server profile once, to see the size of the job. The command counts the results by type. oscap puts a carriage return before each result to redraw the terminal line; tr -d "\r" removes it and cut -f2 keeps the result word.

Terminal
docker exec drift-lab bash -c 'oscap xccdf eval \
  --profile xccdf_org.ssgproject.content_profile_cis_level1_server \
  /ssg/ds.xml 2>/dev/null | grep "^Result" | tr -d "\r" | cut -f2 | sort | uniq -c'
Illustrative output (counts depend on the image build and package versions)
      1 error
    104 fail
     82 notapplicable
      1 notchecked
    212 pass
      3 unknown

A little over 400 rules were evaluated. Notapplicable means the rule's platform check excluded it. Error, unknown and notchecked mean that the check could not decide, and on a report those need a person. Nobody fixes a hundred failures in one change; the rest of the lab tracks one batch.

05. Step 4: Take the first tracked scan

Terminal
./scan.sh 2026-11-02
.venv/bin/python trend.py
Expected output
2026-11-02 fail=9
2026-11-02 pass=2
2026-11-02  pass=2   fail=8   excepted=1

oscap counted nine failures, but the trend shows eight, because the cipher failure matches the exception. On a fresh install only two rules pass. The files in results/, not the console, are the record of the scan.

06. Step 5: Enforce the baseline, twice

Terminal
.venv/bin/ansible-playbook baseline.yml | tr -s " "
Expected output
PLAY [Enforce the Debian 12 server baseline] ***********************************

TASK [Gathering Facts] *********************************************************
ok: [drift-lab]

TASK [SSH settings at the top of sshd_config, before any drop-in] **************
changed: [drift-lab]

TASK [sshd_config is readable by root only] ************************************
changed: [drift-lab]

TASK [Password hashes are readable by root and group shadow only] **************
ok: [drift-lab]

TASK [No cleartext remote-access clients or servers] ***************************
ok: [drift-lab]

TASK [Kernel parameters file] **************************************************
changed: [drift-lab]

TASK [Read the effective sshd configuration] ***********************************
ok: [drift-lab]

TASK [Effective settings match the baseline (catches drop-in overrides)] *******
ok: [drift-lab]

PLAY RECAP *********************************************************************
drift-lab : ok=8 changed=3 unreachable=0 failed=0 skipped=2 rescued=0 ignored=0

Three tasks changed the host; the others report ok. skipped=2 counts the two handlers, skipped because manage_services is false (their lines are hidden by display_skipped_hosts). Now run the playbook again to test idempotence.

Terminal
.venv/bin/ansible-playbook baseline.yml | tail -n 2 | tr -s " "
Expected output
drift-lab : ok=8 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

changed=0. A task that reports a change on every run would hide real drift, so fix it before scheduling the playbook.

07. Step 6: Scan again and read the trend

Terminal
./scan.sh 2026-11-03
.venv/bin/python trend.py
Expected output
2026-11-03 fail=1
2026-11-03 pass=10
2026-11-02  pass=2   fail=8   excepted=1
2026-11-03  pass=10  fail=0   excepted=1
    fixed     drift-lab file_permissions_sshd_config (pass)
    fixed     drift-lab sshd_disable_empty_passwords (pass)
    fixed     drift-lab sshd_disable_root_login (pass)
    fixed     drift-lab sshd_set_idle_timeout (pass)
    fixed     drift-lab sshd_set_keepalive (pass)
    fixed     drift-lab sshd_set_login_grace_time (pass)
    fixed     drift-lab sshd_set_loglevel_info (pass)
    fixed     drift-lab sshd_set_max_auth_tries (pass)

Eight rules moved from fail to pass. excepted=1 is the agreed state, not perfection: the weak cipher stays visible until its exception expires on 31 March 2027.

08. Step 7: Introduce drift

Now play the colleague who changes the server by hand during an incident. Raise MaxAuthTries to 10, make /etc/shadow readable by everyone, and install the telnet client.

Terminal
docker exec drift-lab bash -c '
  sed -i "s/^MaxAuthTries 4$/MaxAuthTries 10/" /etc/ssh/sshd_config
  chmod 644 /etc/shadow
  apt-get install -y -qq --no-install-recommends inetutils-telnet >/dev/null 2>&1
  echo "drift introduced"'
Expected output
drift introduced

09. Step 8: Detect the drift two ways

First ask Ansible what it would change: --check changes nothing, and --diff shows each change. PIPESTATUS[0] is the exit code of ansible-playbook, not of tr.

Terminal
.venv/bin/ansible-playbook baseline.yml --check --diff | tr -s ' '
echo "ansible exit code: ${PIPESTATUS[0]}"
Expected output (the Origin line shows your own folder)
PLAY [Enforce the Debian 12 server baseline] ***********************************

TASK [Gathering Facts] *********************************************************
ok: [drift-lab]

TASK [SSH settings at the top of sshd_config, before any drop-in] **************
--- before: /etc/ssh/sshd_config (content)
+++ after: /etc/ssh/sshd_config (content)
@@ -1,7 +1,7 @@
 # BEGIN BASELINE (managed by Ansible, do not edit)
 PermitRootLogin no
 PermitEmptyPasswords no
-MaxAuthTries 10
+MaxAuthTries 4
 LoginGraceTime 60
 ClientAliveInterval 300
 ClientAliveCountMax 3

changed: [drift-lab]

TASK [sshd_config is readable by root only] ************************************
ok: [drift-lab]

TASK [Password hashes are readable by root and group shadow only] **************
--- before
+++ after
@@ -1,3 +1,3 @@
- mode: '0644'
+ mode: '0640'
 path: /etc/shadow


changed: [drift-lab]

TASK [No cleartext remote-access clients or servers] ***************************
The following package was automatically installed and is no longer required:
 netbase
Use 'apt autoremove' to remove it.
The following packages will be REMOVED:
 inetutils-telnet*
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
changed: [drift-lab]

TASK [Kernel parameters file] **************************************************
ok: [drift-lab]

TASK [Read the effective sshd configuration] ***********************************
ok: [drift-lab]

TASK [Effective settings match the baseline (catches drop-in overrides)] *******
[ERROR]: Task failed: Action failed: Assertion failed
Origin: /home/you/drift-lab/baseline.yml:56:7

54 check_mode: false
55
56 - name: Effective settings match the baseline (catches drop-in overrides)
 ^ column 7

fatal: [drift-lab]: FAILED! =>
 assertion: '''maxauthtries 4'' in sshd_effective.stdout_lines'
 changed: false
 evaluated_to: false
 msg: Assertion failed

PLAY RECAP *********************************************************************
drift-lab : ok=7 changed=3 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0

ansible exit code: 2

Check mode found all three changes, and the assertion failed because the sshd -T read ran for real and saw maxauthtries 10. The exit code is 2, so a scheduled check job fails and alerts someone, and nothing on the host changed.

The second way is the scanner, which knows nothing about the playbook.

Terminal
./scan.sh 2026-11-10
.venv/bin/python trend.py | sed -n '/^2026-11-10/,$p'
Expected output
2026-11-10 fail=4
2026-11-10 pass=7
2026-11-10  pass=7   fail=3   excepted=1
    REGRESSED drift-lab file_permissions_etc_shadow
    REGRESSED drift-lab package_inetutils-telnet_removed
    REGRESSED drift-lab sshd_set_max_auth_tries

Each REGRESSED line names the host and the rule. A falling compliance score only says that something changed; stored per-rule results say what changed and when. The methods also cover each other: check mode sees only what the playbook manages, and the scanner sees only what its rules test.

10. Step 9: Converge and confirm

Apply the same playbook, scan again and print the whole history.

Terminal
.venv/bin/ansible-playbook baseline.yml | tail -n 2 | tr -s " "
./scan.sh 2026-11-11
.venv/bin/python trend.py
Expected output
drift-lab : ok=8 changed=3 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0

2026-11-11 fail=1
2026-11-11 pass=10
2026-11-02  pass=2   fail=8   excepted=1
2026-11-03  pass=10  fail=0   excepted=1
    fixed     drift-lab file_permissions_sshd_config (pass)
    fixed     drift-lab sshd_disable_empty_passwords (pass)
    fixed     drift-lab sshd_disable_root_login (pass)
    fixed     drift-lab sshd_set_idle_timeout (pass)
    fixed     drift-lab sshd_set_keepalive (pass)
    fixed     drift-lab sshd_set_login_grace_time (pass)
    fixed     drift-lab sshd_set_loglevel_info (pass)
    fixed     drift-lab sshd_set_max_auth_tries (pass)
2026-11-10  pass=7   fail=3   excepted=1
    REGRESSED drift-lab file_permissions_etc_shadow
    REGRESSED drift-lab package_inetutils-telnet_removed
    REGRESSED drift-lab sshd_set_max_auth_tries
2026-11-11  pass=10  fail=0   excepted=1
    fixed     drift-lab file_permissions_etc_shadow (pass)
    fixed     drift-lab package_inetutils-telnet_removed (pass)
    fixed     drift-lab sshd_set_max_auth_tries (pass)

The playbook changed exactly the three drifted settings, and each regression shows as fixed. In production, schedule the check and the scan nightly, and the real run after review. Keep results/ where the scanned hosts cannot write, so that nobody can change a host and its history. Finally, remove the container.

Terminal
docker rm -f drift-lab

11. Check your understanding

Practice check · 3 questions

Reading this lab's results

Three questions about the playbook, the scans and the trend report.

Q1. Someone installs `vsftpd`, an FTP server, on drift-lab. Which of the two methods in step 8 reports it?
Q2. Between two scans, one person fixes `sshd_set_loglevel_info` and another breaks `file_permissions_etc_shadow`. The counts stay the same. What does `trend.py` print for the second scan?
Q3. The weak cipher is still configured on 2027-04-01, the day after its exception expires. What does `trend.py` report for that scan?
Practice only: not graded, not saved, not evidence.

12. Apply it

Move toward the skill project:

  • Run the loop against your Ubuntu Server VM with ssg-ubuntu2404-ds.xml from the same archive, which has a cis_level1_server profile. Connect over SSH and set manage_services=true.
  • Add --report before.html to the first full scan and --report after.html to the last: that is your before-and-after evidence.
  • Schedule the check and the scan with a systemd timer or CI, and copy results/ off the VM.

13. Review prompt

Without looking back, explain: what OpenSCAP, SSG and a profile are; why the lab removes /.dockerenv; what idempotence means and how you tested it; what oscap's exit code 2 means; how check mode and a scan each found the drift, and what each can miss; and why results are stored per host and per rule rather than as one score.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check