test_no_shared_temp_paths.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. # SPDX-License-Identifier: Apache-2.0
  2. """No lab or lesson snippet may keep state in a predictable shared path or kill an unchecked pid.
  3. Issue #260. A fixed name in a shared folder such as /tmp lets another local user plant a file, a
  4. link or a pid file before the lab uses it. This test scans labs/ (every text file) and the fenced
  5. code blocks of docs/wiki/*.md for three patterns:
  6. fixed-shared-path /tmp/<name>, /var/tmp/<name>, /dev/shm/<name>, $TMPDIR/<name>, a quoted
  7. "/tmp" in code, or a Windows temp folder joined to a fixed name
  8. kill-by-pattern pkill, pgrep or killall with a literal (it can match your own shell)
  9. unchecked-pid-file kill of a pid read straight from a file, in a file or code block that never
  10. checks the pid is digits and the process identity (ps -o command=)
  11. Safe forms are not flagged: mktemp (mktemp -d), $XDG_RUNTIME_DIR, $HOME/.cache, Python tempfile,
  12. a per-user folder made with mkdir -m 700, and kill of a pid taken from $! in the same shell.
  13. Exceptions live in docs/shared-temp-allowlist.txt, one per line, with a required reason:
  14. <path relative to the repository root>:<the matched text> | <reason>
  15. A stale entry (one that no longer matches anything) also fails, so the list cannot rot.
  16. """
  17. import re
  18. from pathlib import Path
  19. ROOT = Path(__file__).resolve().parent.parent
  20. ALLOWLIST = ROOT / "docs" / "shared-temp-allowlist.txt"
  21. SHARED = r"(?:/tmp|/var/tmp|/dev/shm)"
  22. FIXED_PATH = re.compile(
  23. rf"(?<![\w.$/~-]){SHARED}/[\w.%{{$][^\s'\"`)]*" # /tmp/name
  24. r"|\$\{?TMPDIR\}?/[\w.%{$][^\s'\"`)]*" # $TMPDIR/name
  25. rf"|[\"']{SHARED}[\"']" # Path("/tmp") in code
  26. r"|gettempdir\(\)" # Python shared folder, then a fixed name
  27. r"|GetTempPath\(\)\)?[^\n]*[\"'][\w.-]+[\"']\)?" # PowerShell, joined to a literal
  28. )
  29. # A line that makes its own random name is the safe form, even if it mentions /tmp.
  30. RANDOM_NAME = re.compile(r"mktemp|mkdtemp|mkstemp|TemporaryDirectory|NamedTemporaryFile|NewGuid|GetRandomFileName")
  31. KILL_BY_PATTERN = re.compile(r"\b(?:pkill|pgrep|killall)\b(?:\s+-\S+)*\s+(?![\"']?\$|-)\S+")
  32. # kill ... $(cat X.pid), kill ... $(<X.pid), kill ... `cat X.pid`
  33. KILL_PID_FILE = re.compile(r"\bkill\b[^\n;|&]*?(?:\$\(\s*(?:cat\s+)?<?\s*[^)\n]*pid|`\s*cat\s+[^`\n]*pid)")
  34. PID_IS_DIGITS = re.compile(r"=~\s*\^\[0-9\]\+\$|\[\[:digit:\]\]|\^\\d\+\$|isdigit\(\)|\^\[0-9\]\+\\\$")
  35. PID_IDENTITY = re.compile(r"ps\s+-o\s+command=|/proc/\$?\{?\w+\}?/cmdline|psutil|\.cmdline\(\)")
  36. FENCE = re.compile(r"^\s*(`{3,}|~{3,})")
  37. TEXT_SUFFIXES = {".sh", ".ps1", ".py", ".yml", ".yaml", ".conf", ".template", ".md", ".txt", ".cfg", ".ini", ".json", ".toml", ""}
  38. def code_units(text, markdown):
  39. """Yield (first_line_number, lines) for each unit checked for pid validation.
  40. A markdown file is split into its fenced blocks; anything else is one unit.
  41. """
  42. lines = text.splitlines()
  43. if not markdown:
  44. yield 1, lines
  45. return
  46. block, start, fence = [], 0, None
  47. for number, line in enumerate(lines, 1):
  48. m = FENCE.match(line)
  49. if fence is None and m:
  50. fence, start, block = m.group(1)[0], number + 1, []
  51. elif fence is not None and m and m.group(1)[0] == fence:
  52. yield start, block
  53. fence = None
  54. elif fence is not None:
  55. block.append(line)
  56. if fence is not None:
  57. yield start, block
  58. def scan_text(text, markdown=False):
  59. """Return a list of (line_number, rule, matched_text) for one file's text."""
  60. found = []
  61. for first, block in code_units(text, markdown):
  62. joined = "\n".join(block)
  63. validated = bool(PID_IS_DIGITS.search(joined) and PID_IDENTITY.search(joined))
  64. for offset, line in enumerate(block):
  65. number = first + offset
  66. code = line.strip()
  67. if code.startswith(("#", "//")):
  68. continue
  69. if not RANDOM_NAME.search(line):
  70. found += [(number, "fixed-shared-path", m.group(0)) for m in FIXED_PATH.finditer(line)]
  71. found += [(number, "kill-by-pattern", m.group(0)) for m in KILL_BY_PATTERN.finditer(line)]
  72. if not validated:
  73. found += [(number, "unchecked-pid-file", m.group(0)) for m in KILL_PID_FILE.finditer(line)]
  74. return found
  75. def scanned_files():
  76. for path in sorted((ROOT / "labs").rglob("*")):
  77. if path.is_file() and path.suffix in TEXT_SUFFIXES and path.stat().st_size < 1_000_000:
  78. yield path
  79. yield from sorted((ROOT / "docs" / "wiki").glob("*.md"))
  80. def findings():
  81. out = []
  82. for path in scanned_files():
  83. try:
  84. text = path.read_text(encoding="utf-8")
  85. except UnicodeDecodeError:
  86. continue
  87. rel = path.relative_to(ROOT).as_posix()
  88. out += [(rel, n, rule, hit) for n, rule, hit in scan_text(text, markdown=path.suffix == ".md")]
  89. return out
  90. def parse_allowlist(text):
  91. """Return {(path, matched text): reason}; raise ValueError for a line with no reason."""
  92. entries = {}
  93. for number, raw in enumerate(text.splitlines(), 1):
  94. line = raw.strip()
  95. if not line or line.startswith("#"):
  96. continue
  97. key, sep, reason = line.partition(" | ")
  98. if not sep or not reason.strip():
  99. raise ValueError(f"line {number}: an allowlist entry needs ' | <reason>'")
  100. path, colon, hit = key.partition(":")
  101. if not colon or not path.strip() or not hit.strip():
  102. raise ValueError(f"line {number}: expected '<path>:<matched text> | <reason>'")
  103. entries[(path.strip(), hit.strip())] = reason.strip()
  104. return entries
  105. def test_no_shared_temp_paths_or_unchecked_kills_in_labs_and_lessons():
  106. allowed = parse_allowlist(ALLOWLIST.read_text())
  107. bad = [
  108. f"{rel}:{n} {rule} {hit!r}" for rel, n, rule, hit in findings() if (rel, hit) not in allowed
  109. ]
  110. assert not bad, (
  111. "Use a private per-user folder (mkdir -m 700 under $XDG_RUNTIME_DIR or $HOME/.cache, or mktemp -d), "
  112. "check a pid file and the process before kill, and never pkill or pgrep with a literal. "
  113. "A true exception goes in docs/shared-temp-allowlist.txt with a reason.\n" + "\n".join(bad)
  114. )
  115. def test_every_allowlist_entry_has_a_reason_and_still_matches_something():
  116. allowed = parse_allowlist(ALLOWLIST.read_text())
  117. live = {(rel, hit) for rel, _n, _rule, hit in findings()}
  118. stale = sorted(set(allowed) - live)
  119. assert not stale, f"allowlist entries that match nothing now (remove them): {stale}"
  120. def test_allowlist_without_a_reason_is_rejected():
  121. for bad in ("a.md:/tmp/x", "a.md:/tmp/x | ", "a.md:/tmp/x | ", "nocolon | reason"):
  122. try:
  123. parse_allowlist(bad)
  124. except ValueError:
  125. continue
  126. raise AssertionError(f"accepted: {bad!r}")
  127. assert parse_allowlist("# c\n\na.md:/tmp/x | it is data, not state\n") == {("a.md", "/tmp/x"): "it is data, not state"}
  128. # ---- the scanner itself: it catches each banned pattern ----------------------------------------
  129. def rules(text, markdown=False):
  130. return {rule for _n, rule, _hit in scan_text(text, markdown)}
  131. def test_scanner_catches_fixed_shared_paths():
  132. for snippet in (
  133. "mkdir -p /tmp/lab",
  134. "echo hi > /tmp/lab.txt",
  135. "pid /tmp/nginx.pid;",
  136. "cd /var/tmp/work",
  137. "touch /dev/shm/state",
  138. 'LAB="$TMPDIR/lab"',
  139. "LAB=${TMPDIR}/lab",
  140. 'p = Path("/tmp") / "state"',
  141. "d = tempfile.gettempdir() + '/lab'",
  142. "$d = Join-Path ([IO.Path]::GetTempPath()) 'cah-lab'",
  143. ):
  144. assert "fixed-shared-path" in rules(snippet), snippet
  145. def test_scanner_catches_kill_by_pattern():
  146. for snippet in ("pkill -f nginx", "pkill nginx", "pgrep -f 'my server'", "killall python3", "kill $(pgrep -f app.py)"):
  147. assert "kill-by-pattern" in rules(snippet), snippet
  148. def test_scanner_catches_kill_of_an_unvalidated_pid_file():
  149. for snippet in (
  150. 'kill "$(cat app.pid)"',
  151. "kill $(cat ~/lab/auth.pid)",
  152. 'kill -9 "$(cat "$WORK/a.pid")" || true',
  153. 'kill "$(<server.pid)"',
  154. "kill `cat app.pid`",
  155. ):
  156. assert "unchecked-pid-file" in rules(snippet), snippet
  157. def test_scanner_catches_inside_a_fenced_block_but_not_in_prose():
  158. page = "Never use /tmp/lab in prose.\n\n```bash\nmkdir /tmp/lab\n```\n\nAfter the block /tmp/other is prose again.\n"
  159. hits = scan_text(page, markdown=True)
  160. assert [(n, rule, hit) for n, rule, hit in hits] == [(4, "fixed-shared-path", "/tmp/lab")]
  161. # ---- the scanner ignores the safe forms --------------------------------------------------------
  162. def test_scanner_ignores_safe_temp_forms():
  163. for snippet in (
  164. 'LAB="$(mktemp -d)"',
  165. "tmp=$(mktemp -d /tmp/cah.XXXXXX)",
  166. 'WORK="${XDG_RUNTIME_DIR:-$HOME/.cache}/cah-lab"',
  167. 'mkdir -m 700 "$HOME/.cache/cah-lab"',
  168. "with tempfile.TemporaryDirectory() as tmp:",
  169. "fd, name = tempfile.mkstemp(prefix='x')",
  170. "home = Path(tempfile.mkdtemp(prefix='x', dir='/tmp'))",
  171. '$d = Join-Path ([IO.Path]::GetTempPath()) ("lab-" + [guid]::NewGuid())',
  172. "ls /tmp",
  173. "cat /etc/tmp.conf",
  174. "cp ./tmp/body lab/tmp/body",
  175. "# pkill -f nginx would match your own shell",
  176. 'pkill -f "$name"',
  177. ):
  178. assert rules(snippet) == set(), snippet
  179. def test_scanner_ignores_kill_of_a_child_pid_and_a_checked_pid_file():
  180. assert rules('python3 -m http.server & pid=$!\nkill "$pid"; wait "$pid"') == set()
  181. checked = (
  182. "pid_ok() {\n"
  183. ' [ -f "$1" ] && [ -O "$1" ] || return 1\n'
  184. ' pid="$(cat "$1")"\n'
  185. ' [[ "$pid" =~ ^[0-9]+$ ]] || return 1\n'
  186. ' [[ "$(ps -o command= -p "$pid")" == *moto.server* ]]\n'
  187. "}\n"
  188. 'pid_ok a.pid && kill "$(cat a.pid)"\n'
  189. )
  190. assert rules(checked) == set()
  191. # Only a digits check, or only an identity check, is not enough.
  192. assert "unchecked-pid-file" in rules('[[ "$p" =~ ^[0-9]+$ ]]\nkill "$(cat a.pid)"')
  193. assert "unchecked-pid-file" in rules('ps -o command= -p 1\nkill "$(cat a.pid)"')
  194. def test_the_checked_pid_pattern_is_per_fenced_block_in_a_page():
  195. good = "```bash\n" + '[[ "$p" =~ ^[0-9]+$ ]]; ps -o command= -p "$p"; kill "$(cat a.pid)"\n' + "```\n"
  196. other = "```bash\n" + 'kill "$(cat a.pid)"\n' + "```\n"
  197. assert rules(good, markdown=True) == set()
  198. assert rules(good + "\n" + other, markdown=True) == {"unchecked-pid-file"}