TExcelTAD
Home › Programming for Security: Python, Bash, PowerShell & C Tools › Mini Project: One CLI, Two Tools, Tests and a README

Mini Project: One CLI, Two Tools, Tests and a README

Eight projects in this course each produced a small tool. Tools that live as eight separate scripts in a home directory get lost, drift apart and are never tested again. In this mini project you package two of them as one command-line program with subcommands, shared conventions (exit codes, JSON output, a scope guard where it applies), a test suite, and a README that a colleague can follow without asking you. It is the shape of most real internal security tooling, and the last step before a tool earns a place in a team's repository or a CI pipeline.

The brief

Build labtools, a Python program with at least two subcommands taken from the course's projects, for example:

Subcommand From Input Output
pwcheck Password-Strength Estimator passwords on stdin, one per line estimate, verdict, model per line; exit 1 if any is rejected
authscan Log Analyser an auth.log file JSON findings (burst, spray, success-after-fail); exit 1 on findings
fim File-Integrity Monitor a directory and a signed baseline added, removed and changed files; exit 1 on changes
sshcheck Configuration Checker an sshd_config tree PASS/FAIL per rule with file and line
tcpcheck TCP Connectivity Checker in-scope addresses and ports open/closed/filtered; refuses out-of-scope targets
certcheck TLS Certificate Inspector PEM files expiry, SAN, issuer findings

Requirements:

  1. One entry point main(argv=None) -> int with argparse subcommands (Command-Line Tools with argparse).
  2. Shared conventions: exit 0 clean, 1 findings, 2 usage or input error; findings on stdout (text by default, --json for one object per line); diagnostics on stderr.
  3. Pure cores: each subcommand's logic is a function that takes data and returns findings; only main touches files, stdin and the network.
  4. Tests: at least three per subcommand, including one boundary case and one malformed-input case (Writing Testable Security Tools). All test data synthetic.
  5. Safety: no network access except tcpcheck (if you choose it), whose scope guard is tested; secrets never printed (redact or print lengths).
  6. README following the template below.

A worked skeleton

The skeleton below implements pwcheck and authscan with deliberately small cores, wires them into one parser, and runs its own tests. It runs here in the browser, so "files" and standard input are passed in as text; in your version, main reads them.

python · try it yourself
import argparse, io, json, math, re, sys, unittest
from collections import defaultdict, deque

# ---------- core 1: password strength (simplified from the project lesson) ----------
BLOCKLIST = {"password", "123456", "qwerty", "letmein", "welcome"}
WORDS = {"summer", "winter", "dragon", "monkey", "password"}

def pw_estimate(pw):
    if pw.lower() in BLOCKLIST:
        return 0.0, "blocklisted"
    classes = sum(bool(re.search(p, pw)) * n for p, n in
                  [(r"[a-z]", 26), (r"[A-Z]", 26), (r"\d", 10), (r"[^A-Za-z0-9]", 33)])
    naive = len(pw) * math.log2(classes) if classes else 0.0
    m = re.fullmatch(r"([a-z]+)(\d{0,4})([^a-z0-9]?)", pw.lower())
    if m and m[1] in WORDS:
        bits = math.log2(10_000) + pw[0].isupper() + len(m[2]) * math.log2(10) + (math.log2(33) if m[3] else 0)
        return min(bits, naive), "dictionary+mangling"
    return naive, "charset"

# ---------- core 2: auth log scan (simplified) ----------
LINE = re.compile(r"(?P<t>\d\d:\d\d:\d\d) \S+ sshd\[\d+\]: (?P<r>Failed|Accepted) password for "
                  r"(?:invalid user )?(?P<u>\S+) from (?P<s>\S+)")

def to_sec(t):
    h, m, s = map(int, t.split(":"))
    return h * 3600 + m * 60 + s

def auth_scan(lines, burst=5, window=300):
    q, out, done, bad = defaultdict(deque), [], set(), 0
    for line in lines:
        m = LINE.search(line)
        if not m:
            bad += "sshd[" in line
            continue
        t, src = to_sec(m["t"]), m["s"]
        while q[src] and t - q[src][0] >= window:
            q[src].popleft()
        if m["r"] == "Failed":
            q[src].append(t)
            if len(q[src]) >= burst and ("burst", src) not in done:
                done.add(("burst", src)); out.append({"rule": "burst", "src": src, "at": m["t"]})
        elif len(q[src]) >= burst and ("success-after-fail", src) not in done:
            done.add(("success-after-fail", src)); out.append({"rule": "success-after-fail", "src": src, "user": m["u"], "at": m["t"]})
    if bad:
        out.append({"rule": "parse-error", "count": bad})
    return out

# ---------- the CLI ----------
def main(argv=None, text=None, files=None):
    files = files or {}
    p = argparse.ArgumentParser(prog="labtools", exit_on_error=False,
                                description="Small defensive tools. Synthetic or own data only.")
    p.add_argument("--json", action="store_true", help="one JSON object per finding")
    sub = p.add_subparsers(dest="cmd", required=True)
    sub.add_parser("pwcheck", help="estimate password strength (reads standard input)", exit_on_error=False)
    a = sub.add_parser("authscan", help="find login bursts in an auth.log", exit_on_error=False)
    a.add_argument("logfile")
    a.add_argument("--burst", type=int, default=5)
    try:
        args = p.parse_args(argv)
    except argparse.ArgumentError as e:
        print(f"labtools: error: {e}", file=sys.stderr)
        return 2
    if args.cmd == "pwcheck":
        findings = []
        if text is None:
            text = open(0, encoding="utf-8").read()     # fd 0 = standard input
        for n, pw in enumerate(text.splitlines(), 1):
            bits, model = pw_estimate(pw)
            verdict = "reject" if bits < 40 else "weak" if bits < 60 else "ok"
            findings.append({"line": n, "length": len(pw), "bits": round(bits, 1), "verdict": verdict, "model": model})
        bad = [f for f in findings if f["verdict"] == "reject"]
    else:
        if args.logfile not in files:
            print(f"labtools: error: cannot read {args.logfile}", file=sys.stderr)
            return 2
        findings = bad = auth_scan(files[args.logfile].splitlines(), burst=args.burst)
    for f in findings:
        print(json.dumps(f) if args.json else " ".join(f"{k}={v}" for k, v in f.items()))
    return 1 if bad else 0

# ---------- tests ----------
LOG = "\n".join([f"09:00:{i:02d} web1 sshd[1]: Failed password for root from 203.0.113.7 port 1 ssh2" for i in range(5)]
                + ["09:00:30 web1 sshd[2]: Accepted password for root from 203.0.113.7 port 2 ssh2",
                   "09:01:00 web1 sshd[3]: Failed password for"])

def run(argv, text="", files=None):
    out, err = io.StringIO(), io.StringIO()
    old = sys.stdout, sys.stderr
    sys.stdout, sys.stderr = out, err
    try:
        code = main(argv, text, files)
    finally:
        sys.stdout, sys.stderr = old
    return code, out.getvalue(), err.getvalue()

class LabtoolsTests(unittest.TestCase):
    def test_pw_blocklisted_rejected(self):
        self.assertEqual(pw_estimate("Password"), (0.0, "blocklisted"))
    def test_pw_mangled_word_is_weak(self):
        bits, model = pw_estimate("Summer2025!")
        self.assertEqual(model, "dictionary+mangling"); self.assertLess(bits, 40)
    def test_pw_never_prints_password(self):
        code, out, _ = run(["pwcheck"], "Summer2025!\nk9vX!2mQ#pL8zR4w\n")
        self.assertEqual(code, 1); self.assertNotIn("Summer2025!", out)
    def test_auth_burst_and_success(self):
        rules = [f["rule"] for f in auth_scan(LOG.splitlines())]
        self.assertEqual(rules, ["burst", "success-after-fail", "parse-error"])
    def test_auth_below_threshold(self):
        self.assertEqual(auth_scan(LOG.splitlines()[:4] + LOG.splitlines()[5:6]), [])
    def test_missing_file_exit_2(self):
        self.assertEqual(run(["authscan", "/nope.log"], files={})[0], 2)
    def test_bad_usage_exit_2(self):
        self.assertEqual(run(["authscan", "x.log", "--burst", "many"])[0], 2)

stream = io.StringIO()
res = unittest.TextTestRunner(stream=stream, verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(LabtoolsTests))
print("tests:", res.testsRun, "failures:", len(res.failures), "errors:", len(res.errors))
for line in stream.getvalue().splitlines():
    if line.endswith(("FAIL", "ERROR")):
        print(" ", line)

print("\n$ labtools pwcheck < passwords.txt")
code, out, err = run(["pwcheck"], "Summer2025!\ncorrect horse battery staple\nk9vX!2mQ#pL8zR4w\n")
print(out + f"exit {code}")
print("\n$ labtools --json authscan auth.log")
code, out, err = run(["--json", "authscan", "auth.log"], files={"auth.log": LOG})
print(out + f"exit {code}")
tests: 7 failures: 0 errors: 0

$ labtools pwcheck < passwords.txt
line=1 length=11 bits=32.6 verdict=reject model=dictionary+mangling
line=2 length=28 bits=164.7 verdict=ok model=charset
line=3 length=16 bits=105.1 verdict=ok model=charset
exit 1

$ labtools --json authscan auth.log
{"rule": "burst", "src": "203.0.113.7", "at": "09:00:04"}
{"rule": "success-after-fail", "src": "203.0.113.7", "user": "root", "at": "09:00:30"}
{"rule": "parse-error", "count": 1}
exit 1

Subparsers don't inherit exit_on_error=False from the main parser, so each add_parser call sets it too; without that, the bad-usage test fails with SystemExit (the first draft of this skeleton did exactly that). The tests pin down the conventions as well as the logic: a rejected password gives exit 1 and never appears in the output; a missing file and a malformed option give exit 2. The pwcheck output reports the length, never the password. Note that this simplified estimator rates the passphrase by its characters only (it has no passphrase model); the project lesson's version rates it far lower. Bringing that model back, with a test, is part of the assignment.

Steps

  1. Pick your two (or more) subcommands and copy their cores from the project lessons into one file or a small package (labtools/__init__.py, labtools/pw.py, …).
  2. Write the tests first for each boundary you know about, then make them pass. Run them with python3 -m unittest -v (or pytest).
  3. Wire up main: real files with open(path, "rb") and explicit decoding, stdin with sys.stdin, exit with sys.exit(main()).
  4. Run hostile input against it: an empty file, a binary file, a 1 MB line, a missing file, a name starting with -.
  5. Run a linter (python3 -m pyflakes or ruff) and, if it wraps any external program, check every subprocess call against Running Commands Safely.
  6. Write the README and ask someone to follow it without your help.

README template

text
# labtools

Small defensive tools for <team / lab>. Use only on systems and data you own or
are authorized to assess (see SCOPE below).

## Install
python3 -m venv .venv && . .venv/bin/activate && pip install -e .     # or: copy labtools.py

## Usage
labtools pwcheck < passwords.txt            # strength estimates, never prints passwords
labtools authscan /var/log/auth.log         # login bursts, spraying, success after failures
labtools --json authscan auth.log | jq .    # machine-readable

## Exit codes
0 = no findings   1 = findings   2 = usage or input error

## What each check means
| rule                | logic                                   | threshold (default) |
|---------------------|-----------------------------------------|---------------------|
| burst               | >= N failures from one source in W s    | N=5, W=300          |
| success-after-fail  | a success after a burst from the source | same                |
| parse-error         | relevant lines that did not parse       | any                 |

## Scope and safety
- Reads local files and stdin only. No network access.   (tcpcheck: 127.0.0.0/8, 10.10.0.0/24 only)
- Output never contains passwords or secrets.
- Test data in tests/ is synthetic.

## Limitations
<what it does not detect; known false positives; log formats supported>

## Tests
python3 -m unittest -v

## Changelog
<date> <version> <change and reason, especially threshold changes>

Write-up and assessment

Hand in the code, the tests and a one-page write-up with: the two tools you chose and why; one bug your tests or hostile inputs found, with the test that now covers it; one detection limit of each tool (what an attacker could do to stay under it); and the output of a full test run.

Criterion Done when
Conventions exit codes 0/1/2 and stdout/stderr split verified by tests
Correctness every rule has a boundary test; all tests pass
Robustness empty, binary, huge and missing inputs give clear errors, no tracebacks
Safety no secrets in output; scope guard tested (if networked); no shell=True
Usability a colleague ran it from the README alone

Test yourself

Why does each subcommand keep its logic in a pure function separate from main?

  1. Python requires it
  2. So tests can call the logic with fixed data, and only main touches files, stdin and the network
  3. To make the program longer
  4. argparse needs it

What does the test test_pw_never_prints_password protect?

  1. Speed
  2. The rule that output never contains secrets, so reports can be shared
  3. The exit code only
  4. The help text

labtools authscan /nope.log with a missing file should exit with:

  1. 0
  2. 1
  3. 2
  4. It should crash with a traceback