Przeglądaj źródła

fix: sweep labs and lessons for shared temp paths and unsafe pid or kill handling (#260) (#262)

Add tests/test_no_shared_temp_paths.py, which scans labs/ and the fenced
code blocks of docs/wiki for fixed /tmp-style paths, pkill/pgrep with a
literal, and kill of an unchecked pid file, with a reasoned allowlist
(docs/shared-temp-allowlist.txt) and tests that prove each pattern is
caught and each safe form is ignored.

Fixes found by the sweep: Doppler hook download folder (mktemp -d, symlink
and owner check), first-hour drift demo (mktemp -d), pf syntax exercise
(private folder), rate-limiting nginx pid (container /run), Cowrie lure
staging (admin home, not /tmp), CDN lab and DNS lab (private folder,
validated pid files, process identity check before kill). The lesson
planning page names the rule for future authors.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
ChiefGyk3D 1 miesiąc temu
rodzic
commit
d2d8eb8387

+ 7 - 0
docs/shared-temp-allowlist.txt

@@ -0,0 +1,7 @@
+# Exceptions to tests/test_no_shared_temp_paths.py (issue #260).
+# One per line: <path relative to the repository root>:<the matched text> | <reason>
+# The reason is required. Lines starting with # and blank lines are ignored.
+# An entry that no longer matches anything fails the test, so remove it with the code it covered.
+docs/wiki/Deception-and-Honeypots-Alerts-in-the-SIEM.md:/tmp/pwned | Hostile text inside an invented log line to prove the rules ignore it; nothing is created at that path
+docs/wiki/Deception-and-Honeypots-Read-the-Sensor-Logs.md:/tmp/pwned | Hostile text inside an invented log line the reader parses as data; nothing is created at that path
+docs/wiki/Deception-and-Honeypots-Read-the-Sensor-Logs.md:/tmp/x.sh | A command typed by an invented attacker in a made-up sensor log; the lesson only reads it

+ 6 - 2
docs/wiki/Behind-a-CDN-Real-Client-IPs-and-OSI-Basics.md

@@ -409,9 +409,13 @@ cat > ctl.sh <<'LAB_EOF'
 # ctl.sh up MODE [HEADER] | down | reload MODE [HEADER]: start or stop the lab. Run from the lab folder.
 set -euo pipefail
 cd "$(dirname "$0")"
-stop() {
+stop() {  # kill a pid file's process only if the file is ours, holds digits, and the process is the one we started
   for p in cdn origin app; do
-    if [ -f $p.pid ]; then kill "$(cat $p.pid)" 2>/dev/null || true; rm -f $p.pid; fi
+    [ -f $p.pid ] && [ -O $p.pid ] || continue
+    pid="$(cat $p.pid)"
+    case $p in app) want="app.py" ;; *) want="$p.conf" ;; esac
+    if [[ "$pid" =~ ^[0-9]+$ ]] && [[ "$(ps -o command= -p "$pid" 2>/dev/null)" == *"$want"* ]]; then kill "$pid" || true; fi
+    rm -f $p.pid
   done
 }
 case ${1:?up|down|reload} in

+ 22 - 8
docs/wiki/DNS-Cloudflare-and-Hosting-Your-Own-Website.md

@@ -548,7 +548,21 @@ Two `dnsmasq` programs on the loopback address (`127.0.0.1`, reachable only from
 Create a folder and the generator script (it writes the zone, so you can regenerate it with a different address later):
 
 ```bash
-mkdir -p ~/dns-lab && cd ~/dns-lab
+mkdir -p -m 700 ~/dns-lab && cd ~/dns-lab
+[ "$(stat -c %u .)" = "$(id -u)" ] && [ -z "$(find . -maxdepth 0 -perm /022)" ] || { echo "~/dns-lab is not private to you; stop" >&2; exit 1; }   # the pid files live here, so only you may write to it
+cat > stop-dns.sh <<'STOP_EOF'
+#!/usr/bin/env bash
+# stop-dns.sh NAME...: stop the dnsmasq started with NAME.conf (auth, resolver or tofu-auth).
+# It kills only when the pid file is ours, holds only digits, and that process is a dnsmasq using NAME.conf.
+for n in "$@"; do
+  case $n in tofu-auth) f="$PWD/tofu.pid" ;; *) f="$PWD/$n.pid" ;; esac
+  [ -f "$f" ] && [ -O "$f" ] || continue
+  pid="$(cat "$f")"
+  if [[ "$pid" =~ ^[0-9]+$ ]] && [[ "$(ps -o command= -p "$pid" 2>/dev/null)" == *"dnsmasq"*"$n.conf"* ]]; then kill "$pid"; fi
+  rm -f "$f"
+done
+STOP_EOF
+chmod +x stop-dns.sh
 cat > make-auth.sh <<'EOF'
 #!/usr/bin/env bash
 # make-auth.sh [IPV4_FOR_WWW] writes auth.conf: the zone example.test (www defaults to 192.0.2.10)
@@ -604,15 +618,15 @@ cat auth.pid resolver.pid
 
 `dnsmasq` is a small server that is not a full authoritative implementation (its zone support is a subset, so the apex must exist as a host record and the addresses must fall inside the subnets given to `auth-zone`), but it answers real DNS and is enough to teach every concept here. The lab's `dns-rr` line builds a `CAA` record's data from text at run time, so no opaque hex string is stored in the page. The addresses are RFC 5737 and RFC 3849 documentation ranges.
 
-**Stop it** whenever you finish (never `pkill -f`, which can match your own shell; the pid files name exactly the two processes you started):
+**Stop it** whenever you finish (never `pkill -f`, which can match your own shell; `stop-dns.sh` reads each pid file, checks that it holds only digits, belongs to you and names a `dnsmasq` running that config, and only then stops it):
 
 ```bash
-kill "$(cat ~/dns-lab/auth.pid)" "$(cat ~/dns-lab/resolver.pid)"
+cd ~/dns-lab && ./stop-dns.sh auth resolver
 ```
 
 ```powershell
 # Inside WSL, the same Bash commands; from Windows:
-wsl -e bash -c 'kill "$(cat ~/dns-lab/auth.pid)" "$(cat ~/dns-lab/resolver.pid)"'   # est.
+wsl -e bash -c 'cd ~/dns-lab && ./stop-dns.sh auth resolver'   # est.
 ```
 
 #### Exercise 3: ask every record type
@@ -685,7 +699,7 @@ echo "--- ask again 4 seconds later: the TTL has counted down"
 dig +noall +answer @127.0.0.1 -p 5301 www.example.test
 
 echo "--- BREAK: change www at the authoritative server"
-kill "$(cat auth.pid)"; sleep 1; ./make-auth.sh 192.0.2.99; dnsmasq -C auth.conf; sleep 1
+./stop-dns.sh auth; sleep 1; ./make-auth.sh 192.0.2.99; dnsmasq -C auth.conf; sleep 1
 echo "authoritative says:"; dig +short @127.0.0.1 -p 5300 www.example.test
 echo "resolver still says:"; dig +noall +answer @127.0.0.1 -p 5301 www.example.test
 
@@ -708,7 +722,7 @@ dig +noall +answer @127.0.0.1 -p 5301 www.example.test
 
 ```bash
 cd ~/dns-lab
-kill "$(cat auth.pid)"; sleep 1
+./stop-dns.sh auth; sleep 1
 ./make-auth.sh
 echo 'cname=old.example.test,gone.example.test' >> auth.conf
 dnsmasq -C auth.conf; sleep 1
@@ -742,7 +756,7 @@ EOF
 dnsmasq -C tofu-auth.conf
 dig +noall +answer @127.0.0.1 -p 5302 www.example.test
 dig +noall +answer @127.0.0.1 -p 5302 blog.example.test
-kill "$(cat tofu.pid)"
+./stop-dns.sh tofu-auth
 ```
 
 On 2026-10-22, `www` returned `192.0.2.10` and `blog` returned the CNAME to `www.example.test.` followed by that address. Edit a value in `main.tf`, run `tofu plan`, and read the one-line difference before you apply. **Undo:** `tofu destroy -auto-approve` and delete the folder.
@@ -811,7 +825,7 @@ A small loop in the local lab (nothing here touches a real domain).
 
 ```bash
 cd ~/dns-lab
-kill "$(cat auth.pid)"; sleep 1
+./stop-dns.sh auth; sleep 1
 ./make-auth.sh
 echo 'host-record=www.example.test,198.51.100.66' >> auth.conf
 dnsmasq -C auth.conf; sleep 1

+ 11 - 5
docs/wiki/Deception-and-Honeypots-Cloud-Cowrie-Weekend.md

@@ -311,18 +311,24 @@ What each line does, from the default configuration file (read 2026-10-22): `hos
 The fake home and the lure. Cowrie's `HONEYFS` documentation says a file the visitor can read needs both an entry in the fake file system and content for it. The installation page says the bundled file system is read-only for operators: copy it out, point Cowrie at the copy, and edit the copy with `fsctl`. Copy the lure from your computer first (the `scp` runs on **your** side):
 
 ```bash
-scp -P 49152 -r lure admin@SENSOR:/tmp/lure
+scp -P 49152 -r lure admin@SENSOR:lure-incoming
 ```
 
 ```powershell
-scp -P 49152 -r lure admin@SENSOR:/tmp/lure
+scp -P 49152 -r lure admin@SENSOR:lure-incoming
 ```
 
-On the server, as `cowrie` (still in `~/my-honeypot` with the environment active; the `cowrie` user has no `sudo`, so these commands use only its own files and the copy in `/tmp` that `scp` left readable):
+`scp` put the copy in the `admin` home folder, not in the shared `/tmp`, where another local user could swap the file before you used it. On the server, as `admin` (the `cowrie` user has no `sudo`), hand the file to `cowrie` and remove the staging copy:
+
+```bash
+sudo install -d -o cowrie -m 700 /home/cowrie/lure
+sudo install -o cowrie -m 600 lure-incoming/deploy-notes-OLD.txt /home/cowrie/lure/
+rm -r lure-incoming
+```
+
+Then as `cowrie` (still in `~/my-honeypot` with the environment active):
 
 ```bash
-mkdir -p /home/cowrie/lure
-cp /tmp/lure/deploy-notes-OLD.txt /home/cowrie/lure/
 python -c "from cowrie.core.resources import read_data_bytes; open('var/lib/cowrie/fs.pickle', 'wb').write(read_data_bytes('fs.pickle'))"
 SIZE=$(wc -c < /home/cowrie/lure/deploy-notes-OLD.txt)
 echo "$SIZE"

+ 10 - 9
docs/wiki/First-Hour-on-a-New-System-Updates-and-Baseline.md

@@ -290,18 +290,19 @@ Then the drift demo, saved as `drift.sh`. It runs **inside a throwaway container
 # drift.sh - runs INSIDE a throwaway container: baseline, drift, baseline, compare.
 set -eu
 B=/usr/local/bin/baseline.sh
-$B snapshot /tmp/before.txt
+W="$(mktemp -d)"   # a private scratch folder, not a fixed name in the shared /tmp
+$B snapshot "$W/before.txt"
 # drift 1: a tiny local package built at run time (no network needed)
-mkdir -p /tmp/pkg/DEBIAN
-printf 'Package: cah-demo\nVersion: 1.0\nArchitecture: all\nMaintainer: lab <lab@example.com>\nDescription: drift demo\n' > /tmp/pkg/DEBIAN/control
-dpkg-deb --build /tmp/pkg /tmp/cah-demo.deb >/dev/null
-dpkg -i /tmp/cah-demo.deb >/dev/null
+mkdir -p "$W/pkg/DEBIAN"
+printf 'Package: cah-demo\nVersion: 1.0\nArchitecture: all\nMaintainer: lab <lab@example.com>\nDescription: drift demo\n' > "$W/pkg/DEBIAN"/control
+dpkg-deb --build "$W/pkg" "$W/cah-demo.deb" >/dev/null
+dpkg -i "$W/cah-demo.deb" >/dev/null
 # drift 2: a new account, as an attacker or a careless install might add
 useradd -M -s /bin/bash cah-drift
 # drift 3: a config file edited
 echo "# edited" >> /etc/hosts 2>/dev/null || true
-$B snapshot /tmp/after.txt
-$B compare /tmp/before.txt /tmp/after.txt || true
+$B snapshot "$W/after.txt"
+$B compare "$W/before.txt" "$W/after.txt" || true
 ```
 
 **Predict.** Name the three sections of the diff that will show a change, before you run it.
@@ -324,8 +325,8 @@ podman run --rm --network none -v "${PWD}/baseline.sh:/usr/local/bin/baseline.sh
 **Check.** What I got, trimmed, from an Ubuntu 24.04 container on 2026-10-22 (hashes shortened):
 
 ```text
-wrote /tmp/before.txt (192 lines)
-wrote /tmp/after.txt (194 lines)
+wrote <random scratch folder>/before.txt (192 lines)
+wrote <random scratch folder>/after.txt (194 lines)
 @@ -14,6 +14,7 @@
  ca-certificates 20260601~24.04.1
 +cah-demo 1.0

+ 4 - 0
docs/wiki/How-This-Project-Is-Planned.md

@@ -155,6 +155,10 @@ Exceptions, kept exactly as written: direct quotes and vendor text, code and con
 
 `tests/test_american_english.py` fails when a clear British spelling appears in any Markdown page, in a Python, HCL, YAML or shell comment or docstring, or in a threat-model description, outside code fences, inline code and URLs. `tests/test_markdown_anchors.py` checks that every link to a heading still points at one. If a page must keep one on purpose, add a line to `docs/american-english-allowlist.txt` with the page, the word and the reason.
 
+## Writing labs and lessons: no shared temp paths
+
+Every lab and every command block in a lesson follows one rule: state lives in a folder only you can use, never at a fixed name in a shared place such as `/tmp`. On a shared machine another local user can plant a file, a link or a pid file at a predictable path before your lab uses it. Make the folder with `mktemp -d`, or with `mkdir -m 700` under `$XDG_RUNTIME_DIR` or `$HOME/.cache`, and refuse a folder that already exists but is a symlink, is not yours or is writable by others. Before a script kills a process it started in an earlier run, read the pid file, check that it holds only digits, belongs to you and names the process you expect (`ps -o command=`), and never reach for `pkill` or `pgrep` with a literal name, which can match your own shell. Killing the pid in `$!` from the same shell is fine. `tests/test_no_shared_temp_paths.py` scans `labs/` and the code blocks in `docs/wiki/` for these patterns. A real exception, such as hostile text inside an invented log line, goes in `docs/shared-temp-allowlist.txt` with a reason.
+
 ## Feedback from readers
 
 Readers are part of the plan. [Give feedback and open an issue](Give-Feedback-and-Open-an-Issue.md) explains how to report a mistake, a failed command or a question, and the repository has issue forms, a `SECURITY.md` and a `CONTRIBUTING.md` for it. A report becomes an issue like any other and goes through the flow above.

+ 5 - 5
docs/wiki/Packet-Filters-Compared-iptables-nftables-ufw-pf.md

@@ -843,15 +843,15 @@ The same matrix as before from five commands. UFW enabled the IPv6 half by itsel
 
 **Predict.** `pfctl -nf` only parses. What will it print for a correct file, and what for a file with a misspelled keyword?
 
-**Do (BSD shell, in the VM).** Save the `pf.conf` from above as `/tmp/lesson-pf.conf`. On FreeBSD change `ext_if` to the VM's interface name and, on FreeBSD 13 or older, the `match ... scrub` line as the notes say. Then:
+**Do (BSD shell, in the VM).** Save the `pf.conf` from above as `lesson-pf.conf` in a new folder only you can use (`mkdir -m 700 "$HOME/pf-lab" && cd "$HOME/pf-lab"`), not in the shared `/tmp`. On FreeBSD change `ext_if` to the VM's interface name and, on FreeBSD 13 or older, the `match ... scrub` line as the notes say. Then:
 
 ```sh
-pfctl -nf /tmp/lesson-pf.conf && echo SYNTAX-OK
-sed 's/flush global/flush globl/' /tmp/lesson-pf.conf > /tmp/bad-pf.conf
-pfctl -nf /tmp/bad-pf.conf; echo exit=$?
+pfctl -nf lesson-pf.conf && echo SYNTAX-OK
+sed 's/flush global/flush globl/' lesson-pf.conf > bad-pf.conf
+pfctl -nf bad-pf.conf; echo exit=$?
 ```
 
-**Check (est.).** The first command prints nothing and then `SYNTAX-OK`. The second prints a syntax error with a line number and exits non-zero. Neither loads anything (`-n`). To load the file and watch it, `pfctl -f /tmp/lesson-pf.conf` then `pfctl -sr` (show the rules as `pf` interpreted them), and `tcpdump -n -e -ttt -i pflog0` to see logged packets. **Do not load a default-deny file over SSH to a VM you cannot reach from its console**; the FreeBSD handbook gives the same caution about remote firewall edits.
+**Check (est.).** The first command prints nothing and then `SYNTAX-OK`. The second prints a syntax error with a line number and exits non-zero. Neither loads anything (`-n`). To load the file and watch it, `pfctl -f lesson-pf.conf` then `pfctl -sr` (show the rules as `pf` interpreted them), and `tcpdump -n -e -ttt -i pflog0` to see logged packets. **Do not load a default-deny file over SSH to a VM you cannot reach from its console**; the FreeBSD handbook gives the same caution about remote firewall edits.
 
 **PowerShell.** None; use the VM's shell.
 

+ 1 - 1
docs/wiki/Rate-Limiting-at-Every-Layer.md

@@ -501,7 +501,7 @@ Save this as `nginx.conf` in the `rl-lab` folder. Read the comments; every line
 ```nginx
 # rl-lab nginx.conf - a rate limiting lab for 127.0.0.1 only. Not a production configuration.
 worker_processes 1;
-pid /tmp/nginx.pid;
+pid /run/nginx.pid;   # inside the container, as the official image does
 error_log /dev/stderr notice;
 events { worker_connections 256; }
 

+ 12 - 2
scripts/spacelift/doppler-env.sh

@@ -33,7 +33,9 @@
 CAH_DOPPLER_VERSION="3.77.0"
 CAH_DOPPLER_SHA256_AMD64="92587cb89c2ff82fc2ddec2b2a9f275ff320994a44e16cd9310b55a429a82084"
 CAH_DOPPLER_SHA256_ARM64="3aa603d60bc8502ec67d9a57e917925f357ac2822eead484acda3875fe6a4d95"
-CAH_DOPPLER_DIR="${CAH_DOPPLER_DIR:-/tmp/cah-doppler}"
+# CAH_DOPPLER_DIR is optional. When it is not set, a new private folder is made
+# with mktemp -d (never a fixed name in the shared /tmp, where another local user
+# could plant the file this script then runs).
 
 cah_doppler_log() {
   printf 'doppler-env: %s\n' "$*"
@@ -58,7 +60,15 @@ cah_doppler_install() {
 
   _tar="doppler_${CAH_DOPPLER_VERSION}_linux_${_arch}.tar.gz"
   _url="https://github.com/DopplerHQ/cli/releases/download/${CAH_DOPPLER_VERSION}/${_tar}"
-  mkdir -p "$CAH_DOPPLER_DIR" || return 1
+  if [ -z "${CAH_DOPPLER_DIR:-}" ]; then
+    CAH_DOPPLER_DIR=$(mktemp -d) || return 1
+  else
+    mkdir -p -m 700 "$CAH_DOPPLER_DIR" || return 1
+  fi
+  if [ -L "$CAH_DOPPLER_DIR" ] || [ ! -d "$CAH_DOPPLER_DIR" ] || [ ! -O "$CAH_DOPPLER_DIR" ]; then
+    cah_doppler_log "refusing: $CAH_DOPPLER_DIR is a symlink, not a folder, or not yours"
+    return 1
+  fi
 
   if ! curl -fsSL --proto '=https' --tlsv1.2 --retry 3 -o "$CAH_DOPPLER_DIR/$_tar" "$_url"; then
     cah_doppler_log "download failed: $_url"

+ 33 - 1
tests/test_doppler_env.py

@@ -17,7 +17,7 @@ import pytest
 SCRIPT = (
     Path(__file__).resolve().parent.parent / "scripts" / "spacelift" / "doppler-env.sh"
 )
-TOOLS = ["uname", "sed", "mkdir", "rm", "sha256sum", "tar", "cat", "env", "printf"]
+TOOLS = ["uname", "sed", "mkdir", "rm", "sha256sum", "tar", "cat", "env", "printf", "mktemp"]
 SECRET = "dp_test_SECRET_VALUE_123"
 
 DOPPLER_STUB = """#!/bin/sh
@@ -212,6 +212,38 @@ def test_bad_checksum_refuses_to_run_downloaded_cli(sandbox):
     assert not any((tmp_path / "dl").glob("*.tar.gz"))
 
 
+def test_download_folder_is_never_a_fixed_shared_name():
+    text = SCRIPT.read_text()
+    assert "/tmp/cah-doppler" not in text
+    assert "mktemp -d" in text
+
+
+def test_unset_download_folder_is_a_new_private_folder(sandbox):
+    tmp_path, _ = sandbox
+    scratch = tmp_path / "scratch"
+    scratch.mkdir()
+    result = run(
+        sandbox,
+        "DIGITALOCEAN_TOKEN",
+        env_extra={"CAH_DOPPLER_DIR": "", "TMPDIR": str(scratch)},
+        with_doppler=False,
+    )
+    assert "checksum mismatch" in result.stdout  # it got as far as the download, into the new folder
+    made = list(scratch.iterdir())
+    assert len(made) == 1 and made[0].is_dir()
+    assert stat.S_IMODE(made[0].stat().st_mode) == 0o700
+
+
+def test_a_symlinked_download_folder_is_refused(sandbox):
+    tmp_path, _ = sandbox
+    elsewhere = tmp_path / "elsewhere"
+    elsewhere.mkdir()
+    (tmp_path / "link").symlink_to(elsewhere)
+    result = run(sandbox, "DIGITALOCEAN_TOKEN", env_extra={"CAH_DOPPLER_DIR": str(tmp_path / "link")}, with_doppler=False)
+    assert "refusing" in result.stdout and "rc=1" in result.stdout
+    assert list(elsewhere.iterdir()) == []
+
+
 def test_script_has_no_trace_or_unsafe_echo():
     text = SCRIPT.read_text()
     assert "set -x" not in text

+ 242 - 0
tests/test_no_shared_temp_paths.py

@@ -0,0 +1,242 @@
+# SPDX-License-Identifier: Apache-2.0
+"""No lab or lesson snippet may keep state in a predictable shared path or kill an unchecked pid.
+
+Issue #260. A fixed name in a shared folder such as /tmp lets another local user plant a file, a
+link or a pid file before the lab uses it. This test scans labs/ (every text file) and the fenced
+code blocks of docs/wiki/*.md for three patterns:
+
+  fixed-shared-path   /tmp/<name>, /var/tmp/<name>, /dev/shm/<name>, $TMPDIR/<name>, a quoted
+                      "/tmp" in code, or a Windows temp folder joined to a fixed name
+  kill-by-pattern     pkill, pgrep or killall with a literal (it can match your own shell)
+  unchecked-pid-file  kill of a pid read straight from a file, in a file or code block that never
+                      checks the pid is digits and the process identity (ps -o command=)
+
+Safe forms are not flagged: mktemp (mktemp -d), $XDG_RUNTIME_DIR, $HOME/.cache, Python tempfile,
+a per-user folder made with mkdir -m 700, and kill of a pid taken from $! in the same shell.
+
+Exceptions live in docs/shared-temp-allowlist.txt, one per line, with a required reason:
+    <path relative to the repository root>:<the matched text> | <reason>
+A stale entry (one that no longer matches anything) also fails, so the list cannot rot.
+"""
+
+import re
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+ALLOWLIST = ROOT / "docs" / "shared-temp-allowlist.txt"
+SHARED = r"(?:/tmp|/var/tmp|/dev/shm)"
+
+FIXED_PATH = re.compile(
+    rf"(?<![\w.$/~-]){SHARED}/[\w.%{{$][^\s'\"`)]*"  # /tmp/name
+    r"|\$\{?TMPDIR\}?/[\w.%{$][^\s'\"`)]*"  # $TMPDIR/name
+    rf"|[\"']{SHARED}[\"']"  # Path("/tmp") in code
+    r"|gettempdir\(\)"  # Python shared folder, then a fixed name
+    r"|GetTempPath\(\)\)?[^\n]*[\"'][\w.-]+[\"']\)?"  # PowerShell, joined to a literal
+)
+# A line that makes its own random name is the safe form, even if it mentions /tmp.
+RANDOM_NAME = re.compile(r"mktemp|mkdtemp|mkstemp|TemporaryDirectory|NamedTemporaryFile|NewGuid|GetRandomFileName")
+KILL_BY_PATTERN = re.compile(r"\b(?:pkill|pgrep|killall)\b(?:\s+-\S+)*\s+(?![\"']?\$|-)\S+")
+# kill ... $(cat X.pid), kill ... $(<X.pid), kill ... `cat X.pid`
+KILL_PID_FILE = re.compile(r"\bkill\b[^\n;|&]*?(?:\$\(\s*(?:cat\s+)?<?\s*[^)\n]*pid|`\s*cat\s+[^`\n]*pid)")
+PID_IS_DIGITS = re.compile(r"=~\s*\^\[0-9\]\+\$|\[\[:digit:\]\]|\^\\d\+\$|isdigit\(\)|\^\[0-9\]\+\\\$")
+PID_IDENTITY = re.compile(r"ps\s+-o\s+command=|/proc/\$?\{?\w+\}?/cmdline|psutil|\.cmdline\(\)")
+FENCE = re.compile(r"^\s*(`{3,}|~{3,})")
+TEXT_SUFFIXES = {".sh", ".ps1", ".py", ".yml", ".yaml", ".conf", ".template", ".md", ".txt", ".cfg", ".ini", ".json", ".toml", ""}
+
+
+def code_units(text, markdown):
+    """Yield (first_line_number, lines) for each unit checked for pid validation.
+
+    A markdown file is split into its fenced blocks; anything else is one unit.
+    """
+    lines = text.splitlines()
+    if not markdown:
+        yield 1, lines
+        return
+    block, start, fence = [], 0, None
+    for number, line in enumerate(lines, 1):
+        m = FENCE.match(line)
+        if fence is None and m:
+            fence, start, block = m.group(1)[0], number + 1, []
+        elif fence is not None and m and m.group(1)[0] == fence:
+            yield start, block
+            fence = None
+        elif fence is not None:
+            block.append(line)
+    if fence is not None:
+        yield start, block
+
+
+def scan_text(text, markdown=False):
+    """Return a list of (line_number, rule, matched_text) for one file's text."""
+    found = []
+    for first, block in code_units(text, markdown):
+        joined = "\n".join(block)
+        validated = bool(PID_IS_DIGITS.search(joined) and PID_IDENTITY.search(joined))
+        for offset, line in enumerate(block):
+            number = first + offset
+            code = line.strip()
+            if code.startswith(("#", "//")):
+                continue
+            if not RANDOM_NAME.search(line):
+                found += [(number, "fixed-shared-path", m.group(0)) for m in FIXED_PATH.finditer(line)]
+            found += [(number, "kill-by-pattern", m.group(0)) for m in KILL_BY_PATTERN.finditer(line)]
+            if not validated:
+                found += [(number, "unchecked-pid-file", m.group(0)) for m in KILL_PID_FILE.finditer(line)]
+    return found
+
+
+def scanned_files():
+    for path in sorted((ROOT / "labs").rglob("*")):
+        if path.is_file() and path.suffix in TEXT_SUFFIXES and path.stat().st_size < 1_000_000:
+            yield path
+    yield from sorted((ROOT / "docs" / "wiki").glob("*.md"))
+
+
+def findings():
+    out = []
+    for path in scanned_files():
+        try:
+            text = path.read_text(encoding="utf-8")
+        except UnicodeDecodeError:
+            continue
+        rel = path.relative_to(ROOT).as_posix()
+        out += [(rel, n, rule, hit) for n, rule, hit in scan_text(text, markdown=path.suffix == ".md")]
+    return out
+
+
+def parse_allowlist(text):
+    """Return {(path, matched text): reason}; raise ValueError for a line with no reason."""
+    entries = {}
+    for number, raw in enumerate(text.splitlines(), 1):
+        line = raw.strip()
+        if not line or line.startswith("#"):
+            continue
+        key, sep, reason = line.partition(" | ")
+        if not sep or not reason.strip():
+            raise ValueError(f"line {number}: an allowlist entry needs ' | <reason>'")
+        path, colon, hit = key.partition(":")
+        if not colon or not path.strip() or not hit.strip():
+            raise ValueError(f"line {number}: expected '<path>:<matched text> | <reason>'")
+        entries[(path.strip(), hit.strip())] = reason.strip()
+    return entries
+
+
+def test_no_shared_temp_paths_or_unchecked_kills_in_labs_and_lessons():
+    allowed = parse_allowlist(ALLOWLIST.read_text())
+    bad = [
+        f"{rel}:{n}  {rule}  {hit!r}" for rel, n, rule, hit in findings() if (rel, hit) not in allowed
+    ]
+    assert not bad, (
+        "Use a private per-user folder (mkdir -m 700 under $XDG_RUNTIME_DIR or $HOME/.cache, or mktemp -d), "
+        "check a pid file and the process before kill, and never pkill or pgrep with a literal. "
+        "A true exception goes in docs/shared-temp-allowlist.txt with a reason.\n" + "\n".join(bad)
+    )
+
+
+def test_every_allowlist_entry_has_a_reason_and_still_matches_something():
+    allowed = parse_allowlist(ALLOWLIST.read_text())
+    live = {(rel, hit) for rel, _n, _rule, hit in findings()}
+    stale = sorted(set(allowed) - live)
+    assert not stale, f"allowlist entries that match nothing now (remove them): {stale}"
+
+
+def test_allowlist_without_a_reason_is_rejected():
+    for bad in ("a.md:/tmp/x", "a.md:/tmp/x | ", "a.md:/tmp/x |   ", "nocolon | reason"):
+        try:
+            parse_allowlist(bad)
+        except ValueError:
+            continue
+        raise AssertionError(f"accepted: {bad!r}")
+    assert parse_allowlist("# c\n\na.md:/tmp/x | it is data, not state\n") == {("a.md", "/tmp/x"): "it is data, not state"}
+
+
+# ---- the scanner itself: it catches each banned pattern ----------------------------------------
+
+
+def rules(text, markdown=False):
+    return {rule for _n, rule, _hit in scan_text(text, markdown)}
+
+
+def test_scanner_catches_fixed_shared_paths():
+    for snippet in (
+        "mkdir -p /tmp/lab",
+        "echo hi > /tmp/lab.txt",
+        "pid /tmp/nginx.pid;",
+        "cd /var/tmp/work",
+        "touch /dev/shm/state",
+        'LAB="$TMPDIR/lab"',
+        "LAB=${TMPDIR}/lab",
+        'p = Path("/tmp") / "state"',
+        "d = tempfile.gettempdir() + '/lab'",
+        "$d = Join-Path ([IO.Path]::GetTempPath()) 'cah-lab'",
+    ):
+        assert "fixed-shared-path" in rules(snippet), snippet
+
+
+def test_scanner_catches_kill_by_pattern():
+    for snippet in ("pkill -f nginx", "pkill nginx", "pgrep -f 'my server'", "killall python3", "kill $(pgrep -f app.py)"):
+        assert "kill-by-pattern" in rules(snippet), snippet
+
+
+def test_scanner_catches_kill_of_an_unvalidated_pid_file():
+    for snippet in (
+        'kill "$(cat app.pid)"',
+        "kill $(cat ~/lab/auth.pid)",
+        'kill -9 "$(cat "$WORK/a.pid")" || true',
+        'kill "$(<server.pid)"',
+        "kill `cat app.pid`",
+    ):
+        assert "unchecked-pid-file" in rules(snippet), snippet
+
+
+def test_scanner_catches_inside_a_fenced_block_but_not_in_prose():
+    page = "Never use /tmp/lab in prose.\n\n```bash\nmkdir /tmp/lab\n```\n\nAfter the block /tmp/other is prose again.\n"
+    hits = scan_text(page, markdown=True)
+    assert [(n, rule, hit) for n, rule, hit in hits] == [(4, "fixed-shared-path", "/tmp/lab")]
+
+
+# ---- the scanner ignores the safe forms --------------------------------------------------------
+
+
+def test_scanner_ignores_safe_temp_forms():
+    for snippet in (
+        'LAB="$(mktemp -d)"',
+        "tmp=$(mktemp -d /tmp/cah.XXXXXX)",
+        'WORK="${XDG_RUNTIME_DIR:-$HOME/.cache}/cah-lab"',
+        'mkdir -m 700 "$HOME/.cache/cah-lab"',
+        "with tempfile.TemporaryDirectory() as tmp:",
+        "fd, name = tempfile.mkstemp(prefix='x')",
+        "home = Path(tempfile.mkdtemp(prefix='x', dir='/tmp'))",
+        '$d = Join-Path ([IO.Path]::GetTempPath()) ("lab-" + [guid]::NewGuid())',
+        "ls /tmp",
+        "cat /etc/tmp.conf",
+        "cp ./tmp/body lab/tmp/body",
+        "# pkill -f nginx would match your own shell",
+        'pkill -f "$name"',
+    ):
+        assert rules(snippet) == set(), snippet
+
+
+def test_scanner_ignores_kill_of_a_child_pid_and_a_checked_pid_file():
+    assert rules('python3 -m http.server & pid=$!\nkill "$pid"; wait "$pid"') == set()
+    checked = (
+        "pid_ok() {\n"
+        '  [ -f "$1" ] && [ -O "$1" ] || return 1\n'
+        '  pid="$(cat "$1")"\n'
+        '  [[ "$pid" =~ ^[0-9]+$ ]] || return 1\n'
+        '  [[ "$(ps -o command= -p "$pid")" == *moto.server* ]]\n'
+        "}\n"
+        'pid_ok a.pid && kill "$(cat a.pid)"\n'
+    )
+    assert rules(checked) == set()
+    # Only a digits check, or only an identity check, is not enough.
+    assert "unchecked-pid-file" in rules('[[ "$p" =~ ^[0-9]+$ ]]\nkill "$(cat a.pid)"')
+    assert "unchecked-pid-file" in rules('ps -o command= -p 1\nkill "$(cat a.pid)"')
+
+
+def test_the_checked_pid_pattern_is_per_fenced_block_in_a_page():
+    good = "```bash\n" + '[[ "$p" =~ ^[0-9]+$ ]]; ps -o command= -p "$p"; kill "$(cat a.pid)"\n' + "```\n"
+    other = "```bash\n" + 'kill "$(cat a.pid)"\n' + "```\n"
+    assert rules(good, markdown=True) == set()
+    assert rules(good + "\n" + other, markdown=True) == {"unchecked-pid-file"}