TExcelTAD

Designing a Small Security Tool

Security tools are written in a hurry and then trusted for years. A script that "just greps the auth log" during an incident ends up in a cron job, then in a monitoring pipeline, and one day it meets a log line its author never imagined: a user name with a space, a line cut in half by log rotation, a non-UTF-8 byte from an attacker's client. If the tool crashes, nobody gets the alert. If it silently skips the line, the attacker's activity disappears from the report. A security tool has to be designed for hostile input from the first line.

This lesson sets out the skeleton that every project in this course follows, and builds a tiny tool with it.

What a small tool needs

Property Why it matters in security work How to get it
One job easy to review, easy to trust a single function that turns input into findings
Untrusted input handled logs, packets and files may be crafted by an attacker parse defensively, count what you could not parse, never eval
Fail loudly, not silently a skipped line is a missed attack report malformed input as its own finding; non-zero exit on errors
Meaningful exit codes other tools and CI pipelines read them 0 clean, 1 findings, 2 usage or input error (the convention of diff; grep also uses 2 for errors, but exits 0 when it finds a match)
Machine-readable output the next tool in the pipeline is a program one JSON object per finding, or CSV; human text as an option
No side effects by default a checker must not change what it checks read-only; changes only behind an explicit flag
Scope guard a tool pointed at the wrong host is an incident refuse targets outside an allowlist
Deterministic and tested the same input must give the same report pure functions, fixed test data, a test for every rule

Definitions

  • Finding: one thing the tool reports: a rule, where it fired, and the evidence.
  • Fail open / fail closed: on an error, a fail-open tool lets things through (or reports nothing); a fail-closed tool blocks (or reports the error). Security checks should fail closed.
  • Pure function: output depends only on the input, with no files, network or clock. Pure functions are trivial to test.
  • Scope guard: a check, before any network action, that the target is in the authorized ranges.

The skeleton

The tool below reads sshd-style log lines and reports every failed password. It is small, but it has every part of the table: a pure analyse function, a separate main that handles exit codes and output, a counter for lines it could not parse, and a scope guard that a network tool would call before connecting.

python · try it yourself
import ipaddress, json, re

FAILED = re.compile(r"Failed password for (invalid user )?(?P<user>\S+) from (?P<ip>\S+) port \d+")
SCOPE = [ipaddress.ip_network("127.0.0.0/8"), ipaddress.ip_network("10.10.0.0/24")]

def in_scope(target):
    """Scope guard: only loopback and the lab network may be touched."""
    try:
        addr = ipaddress.ip_address(target)
    except ValueError:
        return False                      # not an address at all: refuse
    return any(addr in net for net in SCOPE)

def analyse(lines):
    """Pure function: lines in, (findings, unparsed count) out."""
    findings, unparsed = [], 0
    for n, line in enumerate(lines, 1):
        if "sshd[" not in line:
            continue                      # not our program: ignore quietly
        m = FAILED.search(line)
        if m:
            findings.append({"line": n, "rule": "ssh-failed-password",
                             "user": m["user"], "src": m["ip"]})
        elif "Failed" in line:
            unparsed += 1                 # looks relevant but did not parse: count it
    return findings, unparsed

def main(lines):
    findings, unparsed = analyse(lines)
    for f in findings:
        print(json.dumps(f))
    if unparsed:
        print(json.dumps({"rule": "parse-error", "count": unparsed}))
    return 1 if findings or unparsed else 0

log = [
    "Jan 15 10:00:01 web1 sshd[811]: Accepted publickey for alice from 10.10.0.5 port 50110 ssh2",
    "Jan 15 10:00:07 web1 sshd[812]: Failed password for root from 203.0.113.7 port 40022 ssh2",
    "Jan 15 10:00:09 web1 sshd[813]: Failed password for invalid user admin from 203.0.113.7 port 40024 ssh2",
    "Jan 15 10:00:10 web1 CRON[900]: (root) CMD (run-parts /etc/cron.hourly)",
    "Jan 15 10:00:12 web1 sshd[814]: Failed password for",          # cut by log rotation
]
code = main(log)
print("exit code:", code)
for t in ["127.0.0.1", "10.10.0.10", "192.0.2.10", "lab.test"]:
    print(f"scope check {t:<11} ->", "allowed" if in_scope(t) else "REFUSED")
{"line": 2, "rule": "ssh-failed-password", "user": "root", "src": "203.0.113.7"}
{"line": 3, "rule": "ssh-failed-password", "user": "admin", "src": "203.0.113.7"}
{"rule": "parse-error", "count": 1}
exit code: 1
scope check 127.0.0.1   -> allowed
scope check 10.10.0.10  -> allowed
scope check 192.0.2.10  -> REFUSED
scope check lab.test    -> REFUSED

Look at what the tool did with the last line. It was cut in half, so the regular expression did not match. A naive tool would skip it; this one reports a parse-error finding, so the analyst knows the report is incomplete. The scope guard refuses 192.0.2.10 (a documentation address, outside the allowlist) and also refuses a host name it cannot check without a DNS lookup.

How failures are detected

The usual ways a small tool fails, and how you find out before an attacker does:

  • Crash on odd input. Feed it empty input, a binary file, a 10 MB line, invalid UTF-8, and lines that are almost right. A crash is a test failure. The testing lesson does this systematically.
  • Silent skip. Count lines seen, lines matched and lines that looked relevant but did not parse, and print the counts. If they do not add up, the tool is wrong.
  • Wrong exit code. Run it in a shell and check $? for the clean case, the findings case and the error case.
  • Scope drift. Log every target the tool touches. Review that log against the written scope.

How they are prevented

  1. Separate the pure part from the I/O part. analyse() never opens files, prints or exits, so tests can call it with lists.
  2. Read bytes, decode on purpose. open(path, "rb") and line.decode("utf-8", "replace") never crash on bad bytes (next lesson: Bytes, Encodings, Hex and Base64).
  3. Make the dangerous thing impossible, not just discouraged. The scope guard runs inside the connect function, not in the documentation.
  4. Prefer allowlists. "Only these networks" fails closed; "not these networks" fails open when someone forgets one.

Pitfalls

  • Printing findings and errors to the same stream. Put findings on stdout and diagnostics on stderr, so tool | jq still works when something goes wrong.
  • Exiting 0 on error. A wrapper script then reports "all clear". Use 2 for "I could not do my job".
  • Trusting the hostname. in_scope("lab.test") cannot know where the name points. Resolve once, check the address, then connect to that address.
  • Regular expressions that are too strict or too loose. Failed password for (\S+) captures invalid for invalid users; the optional group in the example fixes that.

Practice

1. Add a rule that reports "Accepted password" (not public key) logins as a finding of their own. What exit code should a log with only that line give?

Add a second pattern such as r"Accepted password for (?P<user>\S+) from (?P<ip>\S+)" and append a finding with rule ssh-password-login. A password login is a policy finding, so the exit code is 1. If your policy only wants to know about it, make it a separate severity rather than a separate exit code.

2. Why does in_scope return False for "not an address" instead of raising an exception?

Failing closed: any input the guard cannot understand is treated as out of scope. Raising would also stop the tool, but a caller might catch the exception broadly and continue; returning False makes the safe outcome the default.

3. The log contains 10,000 lines from CRON and none from sshd. What should the tool print, and should it exit 0?

No findings, so exit 0 is correct, but a careful tool also reports how many sshd lines it saw (zero). An sshd log with no sshd lines usually means the wrong file or a logging failure, which is worth a warning on stderr.

Test yourself

A log checker finds problems in the input. Following the course's convention (the one diff uses), which exit code should it return?

  1. 0
  2. 1
  3. 2
  4. 127

Why does the example count lines that contain Failed but do not match the pattern?

  1. To make the output longer
  2. So that a truncated or unexpected line is reported instead of silently skipped
  3. Because regular expressions are slow
  4. To detect CRON jobs

Which scope guard design fails closed?

  1. A blocklist of networks the tool must not touch
  2. An allowlist of networks the tool may touch, refusing anything it cannot parse
  3. A warning printed when the target looks external
  4. No guard; the user is responsible

What makes analyse() in the skeleton easy to test?

  1. It reads the log file itself
  2. It is a pure function: a list of lines in, findings out, no files, printing or exiting
  3. It uses JSON
  4. It is short