TExcelTAD
Home › Programming for Security: Python, Bash, PowerShell & C Tools › Project: Security Configuration Checker

Project: Security Configuration Checker

Most compromises don't need a zero-day. They walk through a configuration: SSH that accepts root logins with passwords, a firewall rule that shadows the one meant to block, a debug flag left on. Configuration checkers (CIS-CAT, OpenSCAP, Lynis, cloud posture tools) compare real settings with a baseline such as the CIS Benchmarks or a company standard. The hard part is not the list of rules; it is reading the configuration the way the program reads it. Security Auditing and Controls checked sshd_config with grep and noted that sshd uses the first value it reads for a keyword. This project builds a checker that implements those semantics, and shows the false "pass" that a naive check gives.

How sshd reads its configuration

  • Keywords are case-insensitive; arguments may be separated by spaces or =; lines starting with # are comments.
  • For most keywords the first obtained value wins; later lines for the same keyword are ignored.
  • Include inserts other files (globs allowed) at that point. Ubuntu's default sshd_config starts with Include /etc/ssh/sshd_config.d/*.conf, so drop-in files override everything below them.
  • Match starts a conditional block that lasts until the next Match or the end of the file; its settings apply only to matching connections.
  • The authoritative answer is sshd -T (print the effective configuration), optionally with -C user=…,host=…,addr=… to evaluate Match blocks. A checker that can run it should; one that reads files offline (from a backup, a container image or a configuration repository) must reproduce the rules.

First-match evaluation is the same idea a firewall uses, with a twist: a firewall stops at the first rule that matches the packet, sshd at the first line that sets the keyword. The lab shows the firewall version: with the "shadowed rules" set, an earlier broad rule makes a later specific rule unreachable.

chain input { type filter hook input priority 0; policy drop; } on 10.10.0.101tcp dport 22 drop2 pkts2ip saddr 10.10.0.0/24 tcp dport 22 acceptshadowed by 10 pkts3tcp dport 443 accept1 pkt4tcp dport 1024-65535 accept2 pkts5tcp dport 8443 dropshadowed by 40 pkts—policy drop (no rule matched)3 pktspackets (source → protocol/destination port, conntrack state)#1203.0.113.7 → tcp/443 newHTTPS visitor✓ accept (rule 3)#210.10.0.21 → tcp/22 newadmin SSH✕ drop (rule 1)#3198.51.100.9 → tcp/22 newSSH from outside✕ drop (rule 1)#4192.0.2.50 → icmp newping✕ drop (policy)#5198.51.100.9 → tcp/3389 newRDP probe✓ accept (rule 4)#6203.0.113.7 → udp/53 newDNS query✕ drop (policy)#7198.51.100.9 → tcp/8443 newadmin panel probe✓ accept (rule 4)#8203.0.113.8 → tcp/80 newHTTP visitor✕ drop (policy)

The checker

The configuration below is a lab server's, as files in a dictionary (in a real tool they are read from disk or an image). The main file ends with a compliant-looking PermitRootLogin no, but a drop-in file included at the top sets it to yes first.

python · try it yourself
import fnmatch, re

FILES = {
    "/etc/ssh/sshd_config": """
Include /etc/ssh/sshd_config.d/*.conf
# Hardened settings (added by the security team)
PermitRootLogin no
PasswordAuthentication no
MaxAuthTries 3
X11Forwarding no
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
Match User backup
    PasswordAuthentication yes
""",
    "/etc/ssh/sshd_config.d/50-cloud-init.conf": "PasswordAuthentication yes\n",
    "/etc/ssh/sshd_config.d/60-vendor.conf": "permitrootlogin=yes\nMaxAuthTries 10\n",
}

TOKEN = re.compile(r"(\S+?)(?:\s*=\s*|\s+)(.*)")      # "Key value", "Key=value", "key = value"

def read_effective(path, files, eff=None, matches=None, depth=0):
    """sshd's rules: first value wins, Include expands in place (sorted), Match lasts to the next Match."""
    eff = {} if eff is None else eff
    matches = [] if matches is None else matches
    if depth > 8:
        raise ValueError("Include nesting too deep")
    block = None
    for n, raw in enumerate(files[path].splitlines(), 1):
        m = TOKEN.match(raw.split("#", 1)[0].strip())
        if not m:
            continue
        key, val, where = m[1].lower(), m[2].strip(), f"{path}:{n}"
        if key == "match":
            block = {"criteria": val, "settings": {}}
            matches.append(block)
        elif block is not None:
            block["settings"].setdefault(key, (val, where))
        elif key == "include":
            for inc in sorted(p for p in files if fnmatch.fnmatch(p, val)):
                read_effective(inc, files, eff, matches, depth + 1)
        else:
            eff.setdefault(key, (val, where))          # first obtained value wins
    return eff, matches

RULES = [
    ("SSH-01", "permitrootlogin", lambda v: v in ("no", "prohibit-password"), "no", "root must not log in with a password"),
    ("SSH-02", "passwordauthentication", lambda v: v == "no", "no", "keys or certificates only"),
    ("SSH-03", "maxauthtries", lambda v: v.isdigit() and int(v) <= 4, "4", "limit guesses per connection"),
    ("SSH-04", "x11forwarding", lambda v: v == "no", "no", "no X11 forwarding on servers"),
    ("SSH-05", "ciphers", lambda v: not re.search(r"cbc|3des|arcfour", v), "(OpenSSH default)", "no CBC or legacy ciphers"),
]
DEFAULTS = {"permitrootlogin": "prohibit-password", "passwordauthentication": "yes",
            "maxauthtries": "6", "x11forwarding": "no", "ciphers": "(OpenSSH default)"}

eff, matches = read_effective("/etc/ssh/sshd_config", FILES)
print("== naive grep of the main file")
for line in FILES["/etc/ssh/sshd_config"].splitlines():
    if line.startswith(("PermitRootLogin", "PasswordAuthentication")):
        print("  ", line)
print("== effective settings and checks")
fails = 0
for rid, key, ok, want, why in RULES:
    val, where = eff.get(key, (DEFAULTS[key], "default"))
    passed = ok(val.lower())
    fails += not passed
    print(f"{rid} {'PASS' if passed else 'FAIL'} {key}={val}  ({where})" + ("" if passed else f"  want {want}: {why}"))
for m in matches:
    for key, (val, where) in m["settings"].items():
        if key == "passwordauthentication" and val.lower() == "yes":
            print(f"SSH-02 WARN Match {m['criteria']!r} re-enables {key} ({where})")
print("exit code:", 1 if fails else 0)
== naive grep of the main file
   PermitRootLogin no
   PasswordAuthentication no
== effective settings and checks
SSH-01 FAIL permitrootlogin=yes  (/etc/ssh/sshd_config.d/60-vendor.conf:1)  want no: root must not log in with a password
SSH-02 FAIL passwordauthentication=yes  (/etc/ssh/sshd_config.d/50-cloud-init.conf:1)  want no: keys or certificates only
SSH-03 FAIL maxauthtries=10  (/etc/ssh/sshd_config.d/60-vendor.conf:2)  want 4: limit guesses per connection
SSH-04 PASS x11forwarding=no  (/etc/ssh/sshd_config:7)
SSH-05 PASS ciphers=chacha20-poly1305@openssh.com,aes256-gcm@openssh.com  (/etc/ssh/sshd_config:8)
SSH-02 WARN Match 'User backup' re-enables passwordauthentication (/etc/ssh/sshd_config:10)
exit code: 1

The naive view of the main file looks compliant. The effective view, computed with sshd's rules, is not: the vendor drop-in, read first through Include, sets PermitRootLogin yes (written in lower case with =, both legal) and MaxAuthTries 10, and cloud-init's drop-in turns on password authentication. Every finding names the file and line that set the value, which is what the administrator needs to fix it. The Match User backup block is reported separately as a warning, because it only applies to one user.

How misconfigurations are detected

  • Effective configuration first: sshd -T, nginx -T, postconf -n, nft list ruleset, Get-ItemProperty on the registry keys a Group Policy sets. Fall back to parsing only when the program can't be run.
  • Baselines: CIS Benchmarks, DISA STIGs and vendor hardening guides give rule sets with rationale; OpenSCAP and Lynis implement many of them.
  • Drift detection: run the checker on a schedule and in CI against configuration repositories and images, so a change that re-enables passwords fails before it is deployed.

How they are fixed (prevention)

  1. Fix at the source that wins: here the vendor and cloud-init drop-ins, not the main file. Or put the hardening in an early drop-in such as 00-hardening.conf, so it is read first.
  2. Manage configuration as code (Ansible, Puppet, image builds) with the checker as a test, so manual edits are overwritten and reviewed.
  3. Validate before reload: sshd -t checks syntax; a broken config locks administrators out.
  4. Document exceptions (the backup user's password login) with an owner and an expiry date, and make the checker report them as warnings, not silently pass them.

Pitfalls

  • Last-match intuition: many formats (shell scripts, most INI parsers, single-value settings in systemd units) use the last value; sshd uses the first. Know the semantics of each format you check.
  • Defaults: a keyword that is absent still has a value. PasswordAuthentication defaults to yes in OpenSSH; a checker that only looks at present lines passes a config that says nothing.
  • Case and syntax variants: permitrootlogin=yes, tabs, trailing comments. Parse the way the program parses.
  • Untested parsers: every syntax variant above deserves a unit test (Writing Testable Security Tools), including a file that includes itself (the depth limit stops the loop).

Practice

1. Move the hardening lines into a new drop-in /etc/ssh/sshd_config.d/00-hardening.conf in FILES. What does the checker report now, and why?

Because Include expands the glob in sorted order, 00-hardening.conf is read before 50-cloud-init.conf and 60-vendor.conf, so its values win: SSH-01 to SSH-05 pass (the Match warning remains). Order of drop-ins is part of the configuration.

2. Remove the MaxAuthTries lines everywhere. What does the checker report, and is that right?

SSH-03 FAIL maxauthtries=6 (default): OpenSSH's default is 6, above the baseline's 4. Reporting the default with "default" as the source is right; passing an absent setting would be the bug.

3. How would you check the effective configuration for the user backup on a live lab server?

sshd -T -C user=backup,host=ws1.lab.test,addr=10.10.0.5 | grep -i passwordauthentication, run as root on that server. It evaluates the Match block and prints the value sshd would really use.

Test yourself

For most keywords, which value does sshd use when a keyword appears several times?

  1. The last one
  2. The first one it reads
  3. The most restrictive one
  4. It refuses to start

Why did the naive grep give a false pass for PermitRootLogin?

  1. grep is case-sensitive and the file was wrong
  2. The main file's no comes after an Include whose drop-in sets yes first, and sshd keeps the first value
  3. PermitRootLogin has no effect
  4. The Match block changed it

What is the authoritative way to see sshd's effective configuration?

  1. cat /etc/ssh/sshd_config
  2. sshd -T (with -C for Match conditions)
  3. ssh -v
  4. systemctl status ssh

A keyword is absent from every file. What should the checker evaluate?

  1. Nothing; skip the rule
  2. The program's documented default value
  3. Always fail
  4. Always pass