Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 08 · 60 minutes

Build a security baseline checker for your own machine

After this lesson you can
  • Define a security baseline as data and map each check to a security goal and a risk
  • Write a read-only Python tool that prints PASS or FAIL and a JSON report
  • Break the baseline on purpose, read the report and fix it
Lab files of this lesson (19)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Your firm has agreed on a few settings that every server must keep: private keys closed, no file that everyone can write, and a configuration file that nobody has changed. A month later nobody knows whether the servers still follow the agreement. Your manager asks for a small tool that checks the settings and says which fix comes first. You build it on your own machine. Then you point it at a test folder that a colleague prepared, and read what it finds.

Recall

Lesson 2: what does the exit code of "sha256sum -c" tell a script, and why does the checker of this lesson use an exit code too?

Exit code 0 means that every file matched, and any other code means a failure. A scheduler or another script can act on the code without reading text. The checker ends with 1 when a check fails, for the same reason.

Lesson 7: if an attacker changes the baseline file so that every check passes, which STRIDE letter is it?

T, tampering: the data that the tool trusts was changed. The control is to keep a copy or a signature of the baseline in a place that the attacker cannot write (lesson 5).

The idea

A baseline is the list of settings that every machine must have. Teams test it again and again, because systems drift: a person opens a permission for a quick test and never closes it. This build uses the whole course.

LessonWhere it appears
1 RiskEach check has a risk number, and the report lists failures from the highest.
2 CIAEach check names the goal that it protects. Permissions guard confidentiality, hashes guard integrity.
4 Least privilegeThe checks look for access that is wider than it must be.
4 Deny by defaultA check that cannot run counts as a FAIL.
5 HashingA chosen file must keep its stored SHA-256.
6 LoggingEvery result goes to a log line, so there is a record of each run.

The baseline is data in a JSON file. The tool is read-only: it never changes your system. It writes only its own log and report.

One run of the checker
Read onlyThe toolIt writesbaseline.jsonYour filesbaseline.pybaseline.logreport.json1234Read onlyThe toolIt writesbaseline.jsonYour filesbaseline.pybaseline.logreport.json1234
  1. baseline.json → baseline.py: the list of checks
  2. Your files → baseline.py: modes and hashes, read only
  3. baseline.py → baseline.log: one line for each result
  4. baseline.py → report.json: failures, highest risk first

Worked example

1. Make a folder and a file to protect

mkdir -p ~/krlab/security-basics/baseline
cd ~/krlab/security-basics/baseline
echo "PermitRootLogin no" > ~/krlab/security-basics/policy.txt

The echo line makes the file to protect. The lab zip does not hold it, so run this line even if you start from the zip.

2. Write the baseline

JSON is a text format for data: curly brackets hold named values, square brackets hold lists. baseline.json has four checks. Each check has a goal and a risk (likelihood times impact, as in lesson 1). The shell fills in the real hash of policy.txt: $(...) runs a command and puts its output in place, cut -d' ' -f1 keeps the first word of the line, and the marker EOF is not quoted, so the shell replaces $HASH with its value.

HASH=$(sha256sum ~/krlab/security-basics/policy.txt | cut -d' ' -f1)
cat > baseline.json <<EOF
{
  "checks": [
    {"id": "home-private", "type": "no_other_access", "path": "~",
     "goal": "confidentiality", "risk": 15},
    {"id": "lab-no-world-writable", "type": "no_world_writable", "path": "~/krlab",
     "goal": "integrity", "risk": 12},
    {"id": "ssh-private-keys-600", "type": "key_modes", "pattern": "~/.ssh/id_*",
     "skip": "*.pub", "mode": "600", "goal": "confidentiality", "risk": 20},
    {"id": "policy-file-unchanged", "type": "sha256", "path": "~/krlab/security-basics/policy.txt",
     "sha256": "$HASH", "goal": "integrity", "risk": 10}
  ]
}
EOF
One check in baseline.json
ssh-private-keys-600check idkey_modescheck type~/.ssh/id_*files to test*.pubskipped600required modeconfidentialitygoal20risk numberssh-private-keys-600check idkey_modescheck type~/.ssh/id_*files to test*.pubskipped600required modeconfidentialitygoal20risk number

3. Write the first checker

Write baseline.py. Start small: two check types, a loop and an exit code. Each check type is one small function that returns a pair: did it pass, and a short detail. The standard library gives the parts:

  • os.lstat reads the facts of a file without following a link, and stat.S_IMODE keeps the permission bits. mode & 0o007 tests the bits of "others": & keeps the bits that both numbers have, and 0o writes an octal number. {mode:o} prints a number in octal, as ls shows modes (750, not 488).
  • os.path.expanduser turns the ~ of a path into your home folder, so that the JSON can say ~/krlab.
  • hashlib.sha256 hashes bytes, and .hexdigest() gives the hash as text.
  • TYPES is a dictionary of functions. The type of a check picks the function to call.
  • The try ... except block catches any error, so that a check that cannot run is a FAIL and not a crash.

baseline.py

import hashlib
import json
import os
import stat
import sys


def mode_of(path):
    return stat.S_IMODE(os.lstat(path).st_mode)


def no_other_access(c):
    mode = mode_of(os.path.expanduser(c["path"]))
    return mode & 0o007 == 0, f"mode {mode:o}"


def sha256(c):
    with open(os.path.expanduser(c["path"]), "rb") as f:
        digest = hashlib.sha256(f.read()).hexdigest()
    return digest == c["sha256"], f"hash {digest[:12]}"


TYPES = {"no_other_access": no_other_access, "sha256": sha256}

baseline_file = sys.argv[1] if len(sys.argv) > 1 else "baseline.json"
with open(baseline_file) as f:
    baseline = json.load(f)

failed = 0
for check in baseline["checks"]:
    try:
        ok, detail = TYPES[check["type"]](check)
    except Exception as e:  # fail closed: a check that cannot run is a FAIL
        ok, detail = False, f"error: {e}"
    if not ok:
        failed += 1
    print(f"{'PASS' if ok else 'FAIL'}  {check['id']:<24} {detail}")

print(f"{len(baseline['checks']) - failed} passed, {failed} failed")
sys.exit(1 if failed else 0)

4. Run it on your machine

python3 baseline.py
PASS  home-private             mode 750
FAIL  lab-no-world-writable    error: 'no_world_writable'
FAIL  ssh-private-keys-600     error: 'key_modes'
PASS  policy-file-unchanged    hash 44c91857f34b
2 passed, 2 failed

The tool does not know two check types yet, so it says FAIL and not PASS. A check that cannot run proves nothing. This is deny by default (lesson 4). The exit code is 1.

On some systems your home folder is open to others, and the first line says FAIL. That is a real finding. chmod 750 ~ fixes it: you keep full access, your group can enter and read the folder, and other users get nothing. It can break a web server that serves files from your home folder, so skip the change if you run one.

5. Add the two other checks

If your file does not run at this step or the next, copy the finished file of step 9 over it and go on from step 7.

Add import fnmatch and import glob above import hashlib. Two more tools are new here:

  • os.walk visits every folder under a path, and gives for each one its path, its sub-folders and its files. dirs + files joins the two lists. glob.glob finds the files that match a pattern such as ~/.ssh/id_*, and fnmatch.fnmatch tests one name against a pattern such as *.pub. int(c["mode"], 8) reads the text 600 as an octal number.
  • A list comprehension, [p for p in paths if test], builds a list of the items that pass a test (Python course, lesson 3). os.path.islink stops the tool from following a link out of the folder.

Add these two functions above the line TYPES = ...:

def no_world_writable(c):
    bad = []
    for root, dirs, files in os.walk(os.path.expanduser(c["path"])):
        for name in dirs + files:
            path = os.path.join(root, name)
            if not os.path.islink(path) and mode_of(path) & 0o002:
                bad.append(path)
    return not bad, f"{len(bad)} world-writable" + (f": {bad[0]}" if bad else "")


def key_modes(c):
    paths = [p for p in glob.glob(os.path.expanduser(c["pattern"]))
             if not fnmatch.fnmatch(p, c["skip"])]
    bad = [p for p in paths if mode_of(p) != int(c["mode"], 8)]
    return not bad, f"{len(paths)} key(s) found, {len(bad)} wrong" + (f": {bad[0]}" if bad else "")

Then replace the TYPES line with:

TYPES = {"no_other_access": no_other_access, "no_world_writable": no_world_writable,
         "key_modes": key_modes, "sha256": sha256}
python3 baseline.py
PASS  home-private             mode 750
PASS  lab-no-world-writable    0 world-writable
PASS  ssh-private-keys-600     0 key(s) found, 0 wrong
PASS  policy-file-unchanged    hash 44c91857f34b
4 passed, 0 failed

If you have SSH keys, the third line counts them. If it says FAIL, the line names a key that is open to others: chmod 600 on that file is the right fix, so run it and run the tool again. If the second line says FAIL, it names the first world-writable path. That is a real finding from your own lab: remove it with chmod o-w path and run again.

6. Add the log and the report

Add import logging below import json, and add import time and from datetime import datetime, timezone below import sys. logging writes a timestamped line to a log file (time.gmtime makes the stamp UTC, as lesson 6 asks), and json.dump writes the report. In the last block, sorted((r for r in results if ...), key=lambda r: -r["risk"]) takes the failed results (a generator expression is a comprehension that hands over one item at a time) and sorts them by risk. lambda r: -r["risk"] is a one-line function with no name. The minus sign puts the highest risk first. Replace everything from the line failed = 0 to the end of the file with:

logging.Formatter.converter = time.gmtime
logging.basicConfig(filename="baseline.log", level=logging.INFO, datefmt="%Y-%m-%dT%H:%M:%SZ",
                    format="%(asctime)s baseline: %(message)s")
results = []
for check in baseline["checks"]:
    try:
        ok, detail = TYPES[check["type"]](check)
    except Exception as e:  # fail closed: a check that cannot run is a FAIL
        ok, detail = False, f"error: {e}"
    status = "PASS" if ok else "FAIL"
    print(f"{status}  {check['id']:<24} {detail}")
    logging.info("%s %s %s", status, check["id"], detail)
    results.append({"id": check["id"], "status": status, "goal": check["goal"],
                    "risk": check["risk"], "detail": detail})

failed = sorted((r for r in results if r["status"] == "FAIL"), key=lambda r: -r["risk"])
report = {
    "time": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    "passed": len(results) - len(failed),
    "failed": len(failed),
    "fix_first": [r["id"] for r in failed],
    "results": results,
}
with open("report.json", "w") as f:
    json.dump(report, f, indent=2)
print(f"{report['passed']} passed, {report['failed']} failed. Report: report.json")
sys.exit(1 if failed else 0)
python3 baseline.py | tail -1
4 passed, 0 failed. Report: report.json

7. Break two rules on purpose

touch makes an empty file. chmod 666 lets everyone read and write it. Then change the protected file. head -8 prints the first eight lines of the report.

touch ~/krlab/security-basics/shared.txt
chmod 666 ~/krlab/security-basics/shared.txt
echo "PermitRootLogin yes" > ~/krlab/security-basics/policy.txt
python3 baseline.py
echo "exit code: $?"
head -8 report.json
PASS  home-private             mode 750
FAIL  lab-no-world-writable    1 world-writable: /home/you/krlab/security-basics/shared.txt
PASS  ssh-private-keys-600     0 key(s) found, 0 wrong
FAIL  policy-file-unchanged    hash e7be8a5b1805
2 passed, 2 failed. Report: report.json
exit code: 1
{
  "time": "2026-11-21T08:40:17Z",
  "passed": 2,
  "failed": 2,
  "fix_first": [
    "lab-no-world-writable",
    "policy-file-unchanged"
  ],

The tool found both. The exit code 1 lets a scheduler stop on a failure. Do not change your real SSH keys for this test.

8. Fix and check again

tail -2 prints the last two lines of the log.

chmod 644 ~/krlab/security-basics/shared.txt
echo "PermitRootLogin no" > ~/krlab/security-basics/policy.txt
python3 baseline.py | tail -1
tail -2 baseline.log
4 passed, 0 failed. Report: report.json
2026-11-21T08:41:30Z baseline: PASS ssh-private-keys-600 0 key(s) found, 0 wrong
2026-11-21T08:41:30Z baseline: PASS policy-file-unchanged hash 44c91857f34b
One line of baseline.log
2026-11-21T08:41:30Zwhen (UTC)baseline:the programPASSthe resultpolicy-file-unchangedthe check idhash 44c91857f34bthe detail2026-11-21T08:41:30Zwhen (UTC)baseline:the programPASSthe resultpolicy-file-unchangedthe check idhash 44c91857f34bthe detail

The log keeps every run, so a later reader can see when the machine drifted.

9. The finished files

These are the whole files as they stand after the steps above, with the real SHA-256 of policy.txt in place of $HASH. The lab files of the course hold them.

The finished files: baseline.py and baseline.json

The file baseline.py:

baseline.py

import fnmatch
import glob
import hashlib
import json
import logging
import os
import stat
import sys
import time
from datetime import datetime, timezone


def mode_of(path):
    return stat.S_IMODE(os.lstat(path).st_mode)


def no_other_access(c):
    mode = mode_of(os.path.expanduser(c["path"]))
    return mode & 0o007 == 0, f"mode {mode:o}"


def sha256(c):
    with open(os.path.expanduser(c["path"]), "rb") as f:
        digest = hashlib.sha256(f.read()).hexdigest()
    return digest == c["sha256"], f"hash {digest[:12]}"


def no_world_writable(c):
    bad = []
    for root, dirs, files in os.walk(os.path.expanduser(c["path"])):
        for name in dirs + files:
            path = os.path.join(root, name)
            if not os.path.islink(path) and mode_of(path) & 0o002:
                bad.append(path)
    return not bad, f"{len(bad)} world-writable" + (f": {bad[0]}" if bad else "")


def key_modes(c):
    paths = [p for p in glob.glob(os.path.expanduser(c["pattern"]))
             if not fnmatch.fnmatch(p, c["skip"])]
    bad = [p for p in paths if mode_of(p) != int(c["mode"], 8)]
    return not bad, f"{len(paths)} key(s) found, {len(bad)} wrong" + (f": {bad[0]}" if bad else "")


TYPES = {"no_other_access": no_other_access, "no_world_writable": no_world_writable,
         "key_modes": key_modes, "sha256": sha256}

baseline_file = sys.argv[1] if len(sys.argv) > 1 else "baseline.json"
with open(baseline_file) as f:
    baseline = json.load(f)

logging.Formatter.converter = time.gmtime
logging.basicConfig(filename="baseline.log", level=logging.INFO, datefmt="%Y-%m-%dT%H:%M:%SZ",
                    format="%(asctime)s baseline: %(message)s")
results = []
for check in baseline["checks"]:
    try:
        ok, detail = TYPES[check["type"]](check)
    except Exception as e:  # fail closed: a check that cannot run is a FAIL
        ok, detail = False, f"error: {e}"
    status = "PASS" if ok else "FAIL"
    print(f"{status}  {check['id']:<24} {detail}")
    logging.info("%s %s %s", status, check["id"], detail)
    results.append({"id": check["id"], "status": status, "goal": check["goal"],
                    "risk": check["risk"], "detail": detail})

failed = sorted((r for r in results if r["status"] == "FAIL"), key=lambda r: -r["risk"])
report = {
    "time": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    "passed": len(results) - len(failed),
    "failed": len(failed),
    "fix_first": [r["id"] for r in failed],
    "results": results,
}
with open("report.json", "w") as f:
    json.dump(report, f, indent=2)
print(f"{report['passed']} passed, {report['failed']} failed. Report: report.json")
sys.exit(1 if failed else 0)

And the file baseline.json:

baseline.json

{
  "checks": [
    {"id": "home-private", "type": "no_other_access", "path": "~",
     "goal": "confidentiality", "risk": 15},
    {"id": "lab-no-world-writable", "type": "no_world_writable", "path": "~/krlab",
     "goal": "integrity", "risk": 12},
    {"id": "ssh-private-keys-600", "type": "key_modes", "pattern": "~/.ssh/id_*",
     "skip": "*.pub", "mode": "600", "goal": "confidentiality", "risk": 20},
    {"id": "policy-file-unchanged", "type": "sha256", "path": "~/krlab/security-basics/policy.txt",
     "sha256": "44c91857f34b1ec68e246ebcbad66c4b9380b41c3490c719bdfd6696ba7b40b5", "goal": "integrity", "risk": 10}
  ]
}

Your turn

A colleague prepared a test folder for a small web service. Save the program below as make_site.py in the baseline folder and run it with Python. It makes the folder ~/krlab/security-basics/site with fixed content and fixed modes. It is a test setup, so some of its files are open on purpose.

make_site.py

import os

base = os.path.expanduser("~/krlab/security-basics/site")
files = {  # path: (content, mode)
    "app.conf": ("debug=true\n", 0o644),
    "keys/id_web": ("web key\n", 0o600),
    "keys/id_backup": ("backup key\n", 0o600),
    "keys/id_deploy": ("deploy key\n", 0o644),
    "keys/id_web.pub": ("web public key\n", 0o644),
    "uploads/a.txt": ("upload a\n", 0o666),
    "uploads/b.txt": ("upload b\n", 0o666),
    "uploads/c.txt": ("upload c\n", 0o644),
}
for name, (text, mode) in files.items():
    path = os.path.join(base, name)
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w") as f:
        f.write(text)
    os.chmod(path, mode)
os.chmod(os.path.join(base, "keys"), 0o700)
print("wrote", len(files), "files in", base)

The agreed settings are in this table. Write a new baseline file, baseline2.json, with these four checks, and run baseline.py with it. All paths are under ~/krlab/security-basics/site. The vendor published the SHA-256 9844f3630c1726c745398bf5d97af53a07bf00624e24f0877a2e9871a0e34364 for the correct app.conf.

idWhat to checkGoalRisk
keys-600The files keys/id_* (not the .pub file) have the mode 600confidentiality20
uploads-no-world-writeNothing under uploads is writable by everyoneintegrity12
app-conf-unchangedapp.conf has the published hashintegrity10
keys-dir-privateThe folder keys gives others no accessconfidentiality8

When you are done, write down what you would fix first and why, using the risk numbers. Then delete the folder site, because its open files would make the baseline of your own lab fail.

Compare with this

Fix keys-600 first, risk 20: the key id_deploy has the mode 644, so every user of the machine can read it (chmod 600 closes it). Next comes uploads-no-world-write, risk 12: two upload files are open for everyone to change. Last comes app-conf-unchanged, risk 10: the file does not match the published hash, so restore it from the vendor and ask why it changed. The folder keys passes, so it needs no fix. The order follows the risk numbers, and your reason should name the goal at stake: a leaked key breaks confidentiality, and open or changed files break integrity.

Check yourself

Why does the tool count an unknown check type or a missing file as FAIL and not as PASS?

A check that cannot run proves nothing. A PASS here would be a false statement of safety. Deny by default (lesson 4) means that only a clear success is a pass.

You store the expected hash in baseline.json on the same machine. What can an attacker with write access do?

Change the file and change the hash in the baseline, and every check passes. Keep a copy of the baseline off the machine or sign it (lesson 5), and compare before each run.

Why is the tool read-only?

A checker that also fixes things can break a system without anyone deciding to. The report says what is wrong, and a reviewed change fixes it. A read-only tool is also safe to run often.

Field notes

  • The CIS Benchmarks give baselines for operating systems and software, with a pass or fail test for each setting. NIST SP 800-53 has the controls CM-2 (baseline configuration) and CM-6 (configuration settings) that ask for such a baseline.
  • In production, OpenSCAP and Lynis run published baselines, and your own tool fills the gaps that are specific to you.
  • Run the checker on a schedule and send the report to central storage. A baseline tested once is a snapshot.
  • A hash proves a file's content only against a trusted record. For system files, use the package manager's own check (dpkg --verify, rpm -V) and file-integrity monitoring with the database kept off the host.
  • Keep an exception list with an owner and an expiry date for every check that you decide to skip, as in the risk acceptance of lesson 1.