hearthwatch 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ """Hearthwatch: helps you look after a single Linux server."""
2
+ __version__ = "0.3.0"
@@ -0,0 +1,596 @@
1
+ #!/usr/bin/env python3
2
+ """Hearthwatch: CHECK BEFORE INSTALL. check_repo.py <git-https-url | local folder>
3
+
4
+ Reads a repository WITHOUT running it and reports known tricks: hidden instructions aimed at AI agents
5
+ (prompt injection, invisible unicode), download-and-execute patterns, install hooks, read-a-secret-then-send,
6
+ MCP tool poisoning, hidden programs. Exit 0 GREEN, 1 YELLOW, 2 RED, 3 error, 4 INCOMPLETE (something could
7
+ not be read: never treated as GREEN).
8
+
9
+ Rules adapted from RepoBeagle (https://github.com/javierbits/repobeagle), Apache License 2.0,
10
+ Copyright 2026 javierbits; pinned to commit 581e01e976 (v1.201.1). Changes: a stdlib-only subset; see NOTICE.
11
+ No RepoBeagle code is run.
12
+
13
+ Safety: it NEVER runs anything from the repo. A URL is cloned with --no-checkout, depth 1, no tags, no
14
+ submodules, hooks off, LFS smudge off, an empty git config, no credentials, https only (port 443), from a
15
+ host allowlist; then every file is read straight out of git (git cat-file). Nothing from the repo is
16
+ written to disk as a file, so a symlink or a hook can't do anything. Size, memory, CPU and time are capped.
17
+ Run it as an unprivileged user; the residual risk is a bug in git or libcurl itself.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ import re
23
+ import shutil
24
+ import subprocess
25
+ import sys
26
+ import tempfile
27
+ from urllib.parse import urlparse
28
+
29
+ from hearthwatch import config
30
+
31
+ ALLOWED_HOSTS = set(config.get("check_repo", "allowed_hosts",
32
+ ["github.com", "gitlab.com", "codeberg.org", "bitbucket.org"]))
33
+ MAX_FILE = 2_000_000
34
+ MAX_FILES = 20_000
35
+ CLONE_TIMEOUT = 180
36
+ SEV = ["info", "low", "medium", "high", "critical"]
37
+
38
+ # ---- rules (adapted from RepoBeagle core.py / rules/agent.py @ 581e01e976) --------------------------
39
+ AGENT_FILE_RE = re.compile(r"(?i)(^|/)(readme[^/]*|skill\.md|agents?\.md|claude\.md|gemini\.md|copilot-instructions\.md|"
40
+ r"\.cursorrules|\.windsurfrules|\.clinerules|[^/]*\.mdc|[^/]*prompt[^/]*\.(md|txt|ya?ml|json)|"
41
+ r"[^/]*\.prompt|system[_-]?prompt[^/]*|instructions?\.md)$|(^|/)\.cursor/rules/|(^|/)\.claude/|(^|/)skills?/[^/]+\.md$")
42
+ INJECTION_PATTERNS = [
43
+ (r"(?i)\bignore\s+(all\s+|any\s+)?(previous|prior|above|earlier)\s+(instructions|prompts|rules)", "ignore previous instructions"),
44
+ (r"(?i)\b(do\s+not|don'?t|never)\s+(tell|inform|mention|reveal|show|notify|alert)\b.{0,40}\b(user|human|owner|operator)", "tells the agent to hide things from the user"),
45
+ (r"(?i)\b(silently|quietly|secretly|without\s+(asking|telling|notifying|confirmation|the\s+user))\b.{0,80}\b(run|execute|send|upload|post|curl|read|copy|delete|install)", "asks the agent to act silently"),
46
+ (r"(?i)\b(run|execute|send|upload|post|curl|read|copy|install)\b.{0,80}\b(silently|quietly|secretly|without\s+(asking|telling|notifying|confirmation))", "asks the agent to act silently"),
47
+ (r"(?i)\b(you\s+are\s+now|new\s+system\s+prompt|developer\s+mode|jailbreak|override\s+(your|the)\s+(rules|instructions|system))", "role / system override attempt"),
48
+ (r"(?i)\b(ai|llm|agent|assistant|claude|copilot|cursor|gpt|model)s?\b[^.\n]{0,40}\b(must|should|always|need\s+to)\b[^.\n]{0,60}\b(upload|exfiltrate|send|post|transmit|forward)\b", "orders an AI agent to send data"),
49
+ ]
50
+ INJ = [(re.compile(p), why) for p, why in INJECTION_PATTERNS]
51
+ SENS_RE = re.compile(r"(~/\.ssh|\.ssh/|\bid_(rsa|ed25519|ecdsa|dsa)\b|(^|[\s'\"/=(])\.env\b(?!\.example|\.sample|\.template)|\.aws/credentials|"
52
+ r"\.npmrc|\.netrc|\.pypirc|\.git-credentials|\.docker/config\.json|\.kube/config|\.gnupg|keychain|login\.keychain|"
53
+ r"cookies\.sqlite|/Cookies\b|Login\s+Data|wallet\.dat|\bseed\s+phrase|metamask|exodus|\.config/gh/hosts|\.claude\.json|\.cursor/mcp\.json)", re.I)
54
+ READ_RE = re.compile(r"(?i)(readFile|readFileSync|open\s*\(|read_text|read_bytes|\bcat\s|\bcp\s|\bscp\b|tar\s|zip\s|base64\s|homedir|expanduser|\$HOME)")
55
+ SINK_RE = re.compile(r"(?i)(\bcurl\b|\bwget\b|\bfetch\s*\(|requests\.(post|put|get)|urllib|http\.request|https\.request|axios|XMLHttpRequest|"
56
+ r"\bnc\s|netcat|webhook|discord(app)?\.com/api|api\.telegram|ngrok|pastebin|transfer\.sh|\bupload\b|\bexfil|https?://)")
57
+ PIPE_SHELL = re.compile(r"(?i)(curl|wget)\b[^|\n]{0,300}\|\s*(sudo\s+)?(ba|z|da)?sh\b|base64\s+(-d|--decode)[^|\n]{0,100}\|\s*(ba)?sh|"
58
+ r"\bpowershell\b.{0,40}-e(nc(odedcommand)?)?\s|iex\s*\(\s*(new-object|iwr|invoke-webrequest)|"
59
+ r"python[0-9.]*\s+-c\s+[\"'].{0,80}(urlopen|requests\.get)")
60
+ DECODE_EXEC = re.compile(r"(?i)(eval|exec|Function)\s*\(\s*(atob|base64\.b64decode|Buffer\.from\([^)]*base64|zlib\.decompress|codecs\.decode|bytes\.fromhex)")
61
+ MCP_CODE_RE = re.compile(r"(@mcp\.tool|FastMCP|McpServer|server\.tool\(|registerTool|mcp\.server|ListToolsRequest|@modelcontextprotocol)")
62
+ POISON_RE = re.compile(r"(?i)(<\s*important\s*>|otherwise the tool will not work|(do\s+not|don'?t|never)\s+(mention|tell|reveal|disclose)|"
63
+ r"pass (its|the) content|before using this tool|instead of the (real|actual|requested)|send (all|every) (messages?|emails?) to|concealment)")
64
+ MCP_NAME_RE = re.compile(r"(?i)(^|/)(\.?mcp(_servers)?\.json|[^/]*\.mcp\.json|plugin\.json|[^/]*\.plugin\.json|marketplace\.json|claude_desktop_config\.json|"
65
+ r"\.claude/settings[^/]*\.json|\.cursor/mcp\.json|\.vscode/mcp\.json|\.codex/config\.toml|\.gemini/settings\.json|\.windsurf/mcp[^/]*\.json|hooks\.json)$")
66
+ BIDI = set(map(chr, list(range(0x202A, 0x202F)) + list(range(0x2066, 0x206A))))
67
+ ZW_SPLICE = re.compile(r"\w[​-‏⁠-⁤­]+\w")
68
+ # --------------------------------------------------------------------------------------------------------
69
+
70
+ CODE_EXT = {".py", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".sh", ".bash", ".zsh", ".ps1", ".rb", ".go", ".rs",
71
+ ".php", ".pl", ".lua", ".java", ".kt", ".c", ".h", ".cpp", ".cs", ".swift", ".toml", ".cfg", ".ini"}
72
+ DOC_EXT = {".md", ".txt", ".rst", ".adoc", ".html"}
73
+ BINARY_EXT = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".pdf", ".zip", ".gz", ".tgz", ".xz", ".bz2", ".7z", ".woff",
74
+ ".woff2", ".ttf", ".otf", ".eot", ".mp3", ".mp4", ".wav", ".ogg", ".so", ".dll", ".dylib", ".exe", ".bin",
75
+ ".wasm", ".jar", ".class", ".pyc", ".node", ".a", ".o", ".lib", ".gguf", ".safetensors", ".onnx", ".pt", ".npy"}
76
+ MAGIC = [(b"\x7fELF", "ELF program"), (b"MZ", "Windows program"), (b"\xcf\xfa\xed\xfe", "macOS program"),
77
+ (b"\xfe\xed\xfa", "macOS program"), (b"\xca\xfe\xba\xbe", "macOS/Java program")]
78
+ ALLOW_FILE = (os.environ.get("HEARTHWATCH_REPO_ALLOW")
79
+ or config.get_or("check_repo", "allowlist", lambda: os.path.join(config.settings_dir(), "repo-allow.json")))
80
+
81
+
82
+ def load_allow(path: str = None) -> list:
83
+ """Known-okay findings for your own repos: (file, rule) pairs, each with a reason and a review date,
84
+ bound to the reviewed content. Entry: {"file", "rule", "sha256" (of the file), "reason", "review"}.
85
+ If the file changes, its sha256 no longer matches and the finding counts again."""
86
+ import json
87
+ try:
88
+ with open(path or ALLOW_FILE, encoding="utf-8") as fh:
89
+ return json.load(fh)
90
+ except FileNotFoundError:
91
+ return []
92
+ except (OSError, ValueError) as exc: # unreadable list = no list: more findings shown, never fewer
93
+ print(f"WARNING allowlist not used: {type(exc).__name__}", file=sys.stderr)
94
+ return []
95
+
96
+
97
+ def apply_allow(findings: list, hashes: dict, allow: list, today: str) -> list:
98
+ keep = []
99
+ for f in findings:
100
+ raw = f.get("path", f["file"]) # the exact path: two files can LOOK the same once escaped
101
+ ok = any(a["file"] == raw and a["rule"] == f["rule"] and a.get("sha256") == hashes.get(raw)
102
+ and a.get("review", "") >= today for a in allow)
103
+ if ok:
104
+ f = dict(f, allowed=True)
105
+ keep.append(f)
106
+ return keep
107
+
108
+
109
+
110
+
111
+ def _ext(path: str) -> str:
112
+ return os.path.splitext(path)[1].lower()
113
+
114
+
115
+ def finding(out, sev, rule, path, line, why, text=""):
116
+ out.append({"sev": sev, "rule": rule, "file": safe(path), "path": path, "line": line, "why": safe(why),
117
+ "text": safe(text.strip())[:140]})
118
+
119
+
120
+ def safe(s: str) -> str:
121
+ """Untrusted text from the repo never reaches a terminal or log raw (no control or direction characters)."""
122
+ return "".join(c if c.isprintable() and c not in BIDI and not (0xE0000 <= ord(c) <= 0xE007F)
123
+ and not ("\u200b" <= c <= "\u200f") else f"<U+{ord(c):04X}>" for c in s)
124
+
125
+
126
+ def check_file(path: str, data: bytes, out: list) -> None:
127
+ ext = _ext(path)
128
+ for magic, what in MAGIC:
129
+ if data.startswith(magic) and ext not in BINARY_EXT and ext not in (".exe", ".dll"):
130
+ finding(out, "high", "magic-mismatch", path, 1, f"a {what} hiding behind a '{ext or 'no'}' extension")
131
+ return
132
+ if ext in BINARY_EXT or b"\x00" in data[:8192]:
133
+ return
134
+ text = data.decode("utf-8", errors="replace")
135
+ lines = text.splitlines()
136
+ base = path.rsplit("/", 1)[-1]
137
+ is_agent = bool(AGENT_FILE_RE.search(path))
138
+ is_doc = ext in DOC_EXT
139
+ # install / build hooks
140
+ if base == "package.json":
141
+ for m in re.finditer(r'"(preinstall|install|postinstall|prepublish|preuninstall|postuninstall|prepare)"\s*:\s*"([^"]*)"', text):
142
+ hook, cmd = m.group(1), m.group(2)
143
+ sev = "medium" # a plain hook is common; downloads/decoding make it critical below
144
+ if hook == "prepare" and re.search(r"husky|tsc|build", cmd):
145
+ sev = "low"
146
+ if re.search(r"curl|wget|node\s+-e|python[0-9.]*\s+-c|base64|eval|\bnc\b", cmd) or SENS_RE.search(cmd):
147
+ sev = "critical"
148
+ finding(out, sev, "install-hook", path, text[:m.start()].count("\n") + 1, f"npm '{hook}' runs on install", m.group(0))
149
+ if base == "setup.py":
150
+ if "cmdclass" in text:
151
+ finding(out, "medium", "install-hook", path, 1, "setup.py replaces install steps (cmdclass)")
152
+ for i, ln in enumerate(lines, 1):
153
+ if re.search(r"os\.system|subprocess\.|urllib|requests\.|\bsocket\.|\bexec\(|\beval\(", ln):
154
+ finding(out, "high", "install-time-code", path, i, "setup.py runs code or reaches the network at install", ln)
155
+ break
156
+ if base == "devcontainer.json":
157
+ for m in re.finditer(r'"(initializeCommand|onCreateCommand|postCreateCommand|postStartCommand|postAttachCommand)"', text):
158
+ finding(out, "high" if m.group(1) == "initializeCommand" else "medium", "devcontainer-command", path,
159
+ text[:m.start()].count("\n") + 1, f"{m.group(1)} runs automatically" + (" ON THE HOST" if m.group(1) == "initializeCommand" else ""))
160
+ if path.endswith(".vscode/tasks.json") and re.search(r'"runOn"\s*:\s*"folderOpen"', text):
161
+ finding(out, "high", "vscode-autorun", path, 1, "a VS Code task runs when the folder is opened")
162
+ # GitHub workflows
163
+ if re.search(r"(^|/)\.github/workflows/[^/]+\.ya?ml$", path):
164
+ if re.search(r"pull_request_target|workflow_run", text):
165
+ pwn = re.search(r"github\.event\.pull_request\.head\.(sha|ref)|refs/pull/", text)
166
+ finding(out, "high" if pwn else "medium", "gha-privileged-trigger", path, 1,
167
+ "privileged trigger" + (" that checks out the PR's code" if pwn else ""))
168
+ for i, ln in enumerate(lines, 1):
169
+ if re.search(r"(echo|printf|cat)\b.*\$\{\{\s*secrets\.", ln):
170
+ finding(out, "high", "gha-secret-echo", path, i, "prints a secret into the log", ln)
171
+ # MCP / agent tool manifests
172
+ if MCP_NAME_RE.search(path):
173
+ for i, ln in enumerate(lines, 1):
174
+ if re.search(r"(?i)(dangerously|bypass[_-]?permissions|yolo)\w*\"?\s*[:=]\s*true|\"Bash\(\*\)\"|\"allow\"\s*:\s*\[\s*\"\*\"", ln):
175
+ finding(out, "high", "mcp-broad-permission", path, i, "gives an agent unlimited permissions", ln)
176
+ elif re.search(r"(curl|wget)[^\n]*\|\s*(ba|z)?sh", ln):
177
+ finding(out, "high", "mcp-shell-command", path, i, "tool command pipes a download into a shell", ln)
178
+ elif re.search(r"\bnpx\s+-y\b|\buvx\b|pipx\s+run", ln):
179
+ finding(out, "medium", "mcp-auto-install", path, i, "tool installs and runs a package on first use", ln)
180
+ has_mcp = bool(MCP_CODE_RE.search(text))
181
+ for i, ln in enumerate(lines, 1):
182
+ # hidden unicode
183
+ tags = [c for c in ln if 0xE0000 <= ord(c) <= 0xE007F]
184
+ if tags:
185
+ hidden = "".join(chr(ord(c) - 0xE0000) for c in tags if 0xE0020 <= ord(c) <= 0xE007E)
186
+ finding(out, "critical", "hidden-tag-text", path, i, "invisible tag characters spell a hidden message",
187
+ hidden[:140])
188
+ if any(c in BIDI for c in ln):
189
+ finding(out, "high" if ext in CODE_EXT else "medium", "bidi-control", path, i, "text-direction trick characters", ln)
190
+ if ZW_SPLICE.search(ln) and (is_agent or len(ZW_SPLICE.findall(ln)) >= 3):
191
+ finding(out, "high", "zero-width-splice", path, i, "invisible characters spliced inside words", ln)
192
+ # download-and-run / decode-and-run
193
+ if PIPE_SHELL.search(ln):
194
+ finding(out, "low" if is_doc else "medium" if base.lower() in ("makefile", "justfile") else "high",
195
+ "download-and-run", path, i, "downloads something and runs it", ln)
196
+ if DECODE_EXEC.search(ln):
197
+ finding(out, "high", "decode-and-run", path, i, "decodes hidden code and runs it", ln)
198
+ # prompt injection in agent-facing files
199
+ if is_agent:
200
+ for rx, why in INJ:
201
+ if rx.search(ln):
202
+ near = "\n".join(lines[max(0, i - 1 - WINDOW):i + WINDOW]) # instructions split over lines
203
+ sev = "critical" if (SENS_RE.search(near) or SINK_RE.search(near)) else "high"
204
+ finding(out, sev, "agent-injection", path, i, why, ln)
205
+ break
206
+ if has_mcp and POISON_RE.search(ln):
207
+ finding(out, "high", "tool-poisoning", path, i, "hidden instructions in a tool description", ln)
208
+ # read a secret, then send it (within 4 lines), in code
209
+ if ext in CODE_EXT or base.lower() in ("makefile", "justfile"):
210
+ for i, ln in enumerate(lines, 1):
211
+ m = SENS_RE.search(ln)
212
+ if m and READ_RE.search(ln) and not ln.lstrip().startswith(("#", "//")):
213
+ near = "\n".join(lines[max(0, i - 5):i + 4])
214
+ if SINK_RE.search(near):
215
+ only_env = bool(re.fullmatch(r"(?i).*(^|[\s'\"/=(])\.env\b.*", m.group(0))) and ".env" in m.group(0)
216
+ finding(out, "medium" if only_env else "critical", "read-secret-then-send", path, i,
217
+ "reads a secret file near a network call", ln)
218
+
219
+
220
+ WINDOW = 4
221
+
222
+
223
+ def verdict(findings: list) -> str:
224
+ worst = max((SEV.index(f["sev"]) for f in findings if not f.get("allowed")), default=0)
225
+ return "RED" if worst >= SEV.index("high") else "YELLOW" if worst >= SEV.index("medium") else "GREEN"
226
+
227
+
228
+ # ---------------------------------------------------------------- reading a repo (never executing it)
229
+
230
+ def _safe_path_dirs() -> list[str]:
231
+ """PATH entries minus empty ones, "." and the current folder. On Windows, starting "git" by bare name
232
+ searches the CURRENT folder first, so a planted git.exe in the repo being checked would run (Neon review)."""
233
+ here = os.path.normcase(os.path.realpath(os.getcwd()))
234
+ fixed = ["/usr/bin", "/bin", "/usr/local/bin"] if os.name == "posix" else []
235
+ out = []
236
+ for d in fixed + os.environ.get("PATH", "").split(os.pathsep):
237
+ if not d or not os.path.isabs(d): # "", ".", "bin", "node_modules/.bin": relative = inside cwd
238
+ continue
239
+ real = os.path.normcase(os.path.realpath(d))
240
+ if real == here or real.startswith(here + os.sep) or d in out:
241
+ continue # the current folder, or anything below it
242
+ out.append(d)
243
+ return out
244
+
245
+
246
+ def git_exe() -> str:
247
+ """Absolute path to git, never found in the current folder. Not found = an error, never a guess."""
248
+ # Own search, not shutil.which: on Windows, Python 3.10/3.11 which() also looks in the current folder.
249
+ names = ["git"]
250
+ if os.name == "nt":
251
+ names = ["git" + e.lower() for e in os.environ.get("PATHEXT", ".EXE").split(";") if e.upper() in (".EXE", ".COM")]
252
+ for d in _safe_path_dirs():
253
+ for n in names:
254
+ cand = os.path.join(d, n)
255
+ if os.path.isfile(cand) and os.access(cand, os.X_OK):
256
+ return os.path.realpath(cand)
257
+ raise RuntimeError("git not found on PATH (outside the current folder)")
258
+
259
+
260
+ def clone_cmd(url: str, dest: str) -> list[str]:
261
+ return [git_exe(), "-c", f"core.hooksPath={os.devnull}", "-c", "core.symlinks=false", "-c", "protocol.allow=never",
262
+ "-c", "protocol.https.allow=always", "-c", "protocol.file.allow=never", "-c", "protocol.ext.allow=never",
263
+ "-c", "filter.lfs.smudge=", "-c", "filter.lfs.process=", "-c", "filter.lfs.required=false",
264
+ "-c", "credential.helper=", "-c", "http.followRedirects=false", "-c", "transfer.fsckObjects=true",
265
+ "-c", "fetch.fsckObjects=true", "clone", "--template=", "--no-checkout", "--depth", "1", "--no-tags",
266
+ "--single-branch", "--no-recurse-submodules", "--", url, dest]
267
+
268
+
269
+ def check_url(url: str) -> str | None:
270
+ if any(ord(c) < 0x21 or ord(c) == 0x7f for c in url) or "\\" in url:
271
+ return "no spaces, control characters or backslashes in the URL"
272
+ u = urlparse(url)
273
+ if u.query or u.fragment or u.params:
274
+ return "no ?query, #fragment or ;params in the URL"
275
+ try:
276
+ port = u.port
277
+ except ValueError:
278
+ return "bad port"
279
+ if port not in (None, 443):
280
+ return "only port 443"
281
+ if u.scheme != "https":
282
+ return "only https:// URLs are allowed"
283
+ if (u.hostname or "").lower() not in ALLOWED_HOSTS:
284
+ return f"host not on the allowlist ({', '.join(sorted(ALLOWED_HOSTS))})"
285
+ if u.username or u.password:
286
+ return "no credentials in the URL"
287
+ return None
288
+
289
+
290
+ JOB_SECONDS = 600
291
+ MAX_MEM = 1_500_000_000
292
+ MAX_WRITE = 600_000_000 # biggest file git may write (the pack) = the download cap
293
+
294
+
295
+ def _limits():
296
+ """preexec for git: hard caps so a hostile repo can't drown the server."""
297
+ import resource
298
+ resource.setrlimit(resource.RLIMIT_AS, (MAX_MEM, MAX_MEM))
299
+ resource.setrlimit(resource.RLIMIT_FSIZE, (MAX_WRITE, MAX_WRITE))
300
+ resource.setrlimit(resource.RLIMIT_CPU, (300, 300))
301
+ resource.setrlimit(resource.RLIMIT_NPROC, (64, 64))
302
+ os.nice(10)
303
+
304
+
305
+ def _clean_env(home: str) -> dict:
306
+ env = {"PATH": "/usr/bin:/bin", "HOME": home, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull,
307
+ "GIT_TERMINAL_PROMPT": "0", "GIT_ASKPASS": "/bin/false", "SSH_ASKPASS": "/bin/false",
308
+ "GIT_LFS_SKIP_SMUDGE": "1", "GIT_OPTIONAL_LOCKS": "0", "LC_ALL": "C"}
309
+ if os.name == "nt":
310
+ # Windows networking fails without SYSTEMROOT ("getaddrinfo() thread failed to start"), and git for
311
+ # Windows is found through the normal PATH. No credential or git setting is carried over.
312
+ for k in ("SYSTEMROOT", "WINDIR", "TEMP", "TMP", "PATHEXT", "COMSPEC"):
313
+ if k in os.environ:
314
+ env[k] = os.environ[k]
315
+ env["PATH"] = os.pathsep.join(_safe_path_dirs())
316
+ env["USERPROFILE"] = home
317
+ # Empty = git runs no askpass helper at all and, with GIT_TERMINAL_PROMPT=0, fails instead of asking.
318
+ env["GIT_ASKPASS"] = env["SSH_ASKPASS"] = ""
319
+ env["GCM_INTERACTIVE"] = "never"
320
+ return env
321
+
322
+
323
+ def files_from_git(gitdir: str, env: dict):
324
+ lim = _limits if os.name == "posix" else None
325
+ ls = subprocess.run([git_exe(), "--git-dir", gitdir, "ls-tree", "-r", "-z", "--full-tree", "HEAD"],
326
+ capture_output=True, env=env, timeout=120, check=True, preexec_fn=lim, cwd=env.get("HOME")).stdout
327
+ entries = [e for e in ls.split(b"\x00") if e]
328
+ if len(entries) > MAX_FILES:
329
+ raise RuntimeError(f"too many files ({len(entries)})")
330
+ parsed = []
331
+ for e in entries:
332
+ meta, path = e.split(b"\t", 1)
333
+ mode, typ, sha = meta.split(b" ")
334
+ parsed.append((mode, typ, sha, path))
335
+ blobs = list(dict.fromkeys(sha for mode, typ, sha, _ in parsed if typ == b"blob" and mode != b"120000"))
336
+ sizes = {}
337
+ if blobs:
338
+ chk = subprocess.run([git_exe(), "--git-dir", gitdir, "cat-file", "--batch-check"], input=b"\n".join(blobs) + b"\n",
339
+ capture_output=True, env=env, timeout=300, check=True, preexec_fn=lim,
340
+ cwd=env.get("HOME")).stdout
341
+ for line in chk.splitlines():
342
+ parts = line.split(b" ")
343
+ if len(parts) == 3:
344
+ sizes[parts[0]] = int(parts[2])
345
+ # read contents in bundles of at most CHUNK_BYTES, hand them over, then forget them: memory stays flat
346
+ pending, need, total = [], [], 0
347
+ for item in parsed + [None]:
348
+ if item is not None:
349
+ mode, typ, sha, _ = item
350
+ if typ == b"blob" and mode != b"120000" and sizes.get(sha, MAX_FILE + 1) <= MAX_FILE and sha not in need:
351
+ need.append(sha)
352
+ total += sizes[sha]
353
+ pending.append(item)
354
+ if total < CHUNK_BYTES and len(need) < CHUNK_FILES:
355
+ continue
356
+ contents = _cat_batch(gitdir, env, lim, need) if need else {}
357
+ for mode, typ, sha, path in pending:
358
+ p = path.decode("utf-8", errors="surrogateescape") # lossless: two byte-different names stay different
359
+ if typ != b"blob":
360
+ yield p, None, "submodule (not followed, not read)" if typ == b"commit" else f"skipped: {typ.decode()}"
361
+ elif mode == b"120000":
362
+ yield p, None, "symlink (not followed)"
363
+ elif sha not in sizes:
364
+ yield p, None, "skipped: could not read its size"
365
+ elif sizes[sha] > MAX_FILE:
366
+ yield p, None, f"skipped: {sizes[sha]} bytes"
367
+ elif sha not in contents:
368
+ yield p, None, "skipped: content not returned"
369
+ else:
370
+ yield p, contents[sha], None
371
+ pending, need, total, contents = [], [], 0, None
372
+
373
+
374
+ CHUNK_BYTES = 16 * 1024 * 1024
375
+ CHUNK_FILES = 2000
376
+
377
+
378
+ def _cat_batch(gitdir: str, env: dict, lim, shas: list) -> dict:
379
+ """Contents of up to CHUNK_BYTES worth of blobs, from one `git cat-file --batch` run."""
380
+ cat = subprocess.Popen([git_exe(), "--git-dir", gitdir, "cat-file", "--batch"], stdin=subprocess.PIPE,
381
+ stdout=subprocess.PIPE, env=env, preexec_fn=lim, cwd=env.get("HOME"))
382
+ try:
383
+ out, _ = cat.communicate(b"\n".join(shas) + b"\n", timeout=300)
384
+ finally:
385
+ if cat.poll() is None:
386
+ cat.kill()
387
+ if cat.returncode != 0:
388
+ raise RuntimeError(f"git cat-file exited {cat.returncode}")
389
+ contents, pos = {}, 0
390
+ while pos < len(out):
391
+ nl = out.index(b"\n", pos)
392
+ head = out[pos:nl].split(b" ")
393
+ if len(head) != 3:
394
+ raise RuntimeError("git cat-file gave an unexpected answer")
395
+ n = int(head[2])
396
+ contents[head[0]] = out[nl + 1:nl + 1 + n]
397
+ pos = nl + 1 + n + 1
398
+ return contents
399
+
400
+
401
+ def files_from_folder(root: str):
402
+ if os.path.islink(root):
403
+ raise RuntimeError("the folder itself is a symlink")
404
+ if hasattr(os, "fwalk") and os.open in os.supports_dir_fd:
405
+ yield from _files_from_folder_fd(root)
406
+ return
407
+ yield from _files_from_folder_paths(root)
408
+
409
+
410
+ SKIP_DIRS = (".git", "node_modules", "__pycache__")
411
+
412
+
413
+ def _files_from_folder_fd(root: str):
414
+ """Every open is relative to an already-open directory and refuses symlinks: a folder swapped for a link while
415
+ we read can't send us outside `root`."""
416
+ import stat
417
+ errors = []
418
+ count, expected, visited = 0, set(), set()
419
+ for dp, dns, fns, dfd in os.fwalk(root, follow_symlinks=False, onerror=lambda e: errors.append(e)):
420
+ visited.add(os.path.normpath(dp))
421
+ dns[:] = [d for d in dns if d not in SKIP_DIRS]
422
+ for d in list(dns): # a linked folder is named, never silently left out
423
+ try:
424
+ if stat.S_ISLNK(os.stat(d, dir_fd=dfd, follow_symlinks=False).st_mode):
425
+ yield os.path.relpath(os.path.join(dp, d), root).replace(os.sep, "/"), None, "symlink (not followed)"
426
+ dns.remove(d)
427
+ except OSError:
428
+ yield os.path.relpath(os.path.join(dp, d), root).replace(os.sep, "/"), None, "skipped: folder could not be read"
429
+ dns.remove(d)
430
+ expected.update(os.path.normpath(os.path.join(dp, d)) for d in dns)
431
+ count += len(fns)
432
+ if count > MAX_FILES:
433
+ raise RuntimeError(f"too many files (over {MAX_FILES})")
434
+ for fn in fns:
435
+ rel = os.path.relpath(os.path.join(dp, fn), root).replace(os.sep, "/")
436
+ try:
437
+ fd = os.open(fn, os.O_RDONLY | os.O_NOFOLLOW | getattr(os, "O_NONBLOCK", 0), dir_fd=dfd)
438
+ except OSError:
439
+ try:
440
+ is_link = stat.S_ISLNK(os.stat(fn, dir_fd=dfd, follow_symlinks=False).st_mode)
441
+ except OSError:
442
+ is_link = False
443
+ yield rel, None, "symlink (not followed)" if is_link else "skipped: cannot open"
444
+ continue
445
+ try:
446
+ st = os.fstat(fd)
447
+ if not stat.S_ISREG(st.st_mode):
448
+ yield rel, None, "skipped: not a regular file"
449
+ continue
450
+ if st.st_size > MAX_FILE:
451
+ yield rel, None, "skipped: too big"
452
+ continue
453
+ with os.fdopen(fd, "rb", closefd=False) as fh:
454
+ blob = fh.read(MAX_FILE + 1)
455
+ if len(blob) > MAX_FILE:
456
+ yield rel, None, "skipped: grew too big while being read"
457
+ else:
458
+ yield rel, blob, None
459
+ finally:
460
+ os.close(fd)
461
+ for e in errors:
462
+ yield str(getattr(e, "filename", "?")), None, "skipped: folder could not be read"
463
+ for missed in sorted(expected - visited): # e.g. swapped while we read: never visited = never GREEN
464
+ yield os.path.relpath(missed, root).replace(os.sep, "/"), None, "skipped: folder changed or was never visited"
465
+
466
+
467
+ def _files_from_folder_paths(root: str):
468
+ import stat
469
+ errors = []
470
+ expected, visited = set(), set()
471
+ for dp, dns, fns in os.walk(root, followlinks=False, onerror=lambda e: errors.append(e)):
472
+ visited.add(os.path.normpath(dp))
473
+ dns[:] = [d for d in dns if d not in SKIP_DIRS]
474
+ for d in list(dns):
475
+ if os.path.islink(os.path.join(dp, d)):
476
+ yield os.path.relpath(os.path.join(dp, d), root).replace(os.sep, "/"), None, "symlink (not followed)"
477
+ dns.remove(d)
478
+ expected.update(os.path.normpath(os.path.join(dp, d)) for d in dns)
479
+ for fn in fns:
480
+ full = os.path.join(dp, fn)
481
+ rel = os.path.relpath(full, root).replace(os.sep, "/")
482
+ try:
483
+ fd = os.open(full, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
484
+ except OSError:
485
+ yield rel, None, "symlink (not followed)" if os.path.islink(full) else "skipped: cannot open"
486
+ continue
487
+ try:
488
+ st = os.fstat(fd)
489
+ if not stat.S_ISREG(st.st_mode):
490
+ yield rel, None, "skipped: not a regular file"
491
+ continue
492
+ if st.st_size > MAX_FILE:
493
+ yield rel, None, "skipped: too big"
494
+ continue
495
+ with os.fdopen(fd, "rb", closefd=False) as fh:
496
+ blob = fh.read(MAX_FILE + 1)
497
+ if len(blob) > MAX_FILE:
498
+ yield rel, None, "skipped: grew too big while being read"
499
+ else:
500
+ yield rel, blob, None
501
+ finally:
502
+ os.close(fd)
503
+ for e in errors:
504
+ yield str(getattr(e, "filename", "?")), None, "skipped: folder could not be read"
505
+ for missed in sorted(expected - visited):
506
+ yield os.path.relpath(missed, root).replace(os.sep, "/"), None, "skipped: folder changed or was never visited"
507
+
508
+
509
+ LFS_POINTER = b"version https://git-lfs.github.com/spec/"
510
+ MAX_FINDINGS = 5000
511
+
512
+
513
+ def scan(source, allow: list | None = None, today: str | None = None) -> dict:
514
+ import hashlib
515
+ from datetime import date
516
+ findings, skipped, n, read, hashes, gaps = [], [], 0, 0, {}, 0
517
+ for path, data, note in source:
518
+ n += 1
519
+ if note:
520
+ skipped.append(f"{safe(path)}: {note}")
521
+ if not note.startswith("symlink"): # decided by OUR note, never by the (attacker-chosen) file name
522
+ gaps += 1
523
+ continue
524
+ if data.startswith(LFS_POINTER): # a pointer, not the file: its real content was never seen
525
+ skipped.append(f"{safe(path)}: git-lfs pointer (real content not fetched, not read)")
526
+ gaps += 1
527
+ continue
528
+ read += 1
529
+ hashes[path] = hashlib.sha256(data).hexdigest()
530
+ check_file(path, data, findings)
531
+ if len(findings) > MAX_FINDINGS:
532
+ skipped.append(f"stopped after {MAX_FINDINGS} findings: the rest was not checked")
533
+ gaps += 1
534
+ break
535
+ findings = apply_allow(findings, hashes, allow if allow is not None else load_allow(), today or date.today().isoformat())
536
+ v = verdict(findings)
537
+ if v != "RED" and (read == 0 or gaps): # an unread file is never GREEN
538
+ v = "INCOMPLETE"
539
+ return {"files": n, "read": read, "skipped": skipped, "findings": findings, "verdict": v}
540
+
541
+
542
+ def main(argv: list[str]) -> int:
543
+ show_text = "--show-text" in argv # repo text is untrusted: off by default (agents read this output)
544
+ argv = [a for a in argv if a != "--show-text"]
545
+ if len(argv) != 1:
546
+ print(__doc__)
547
+ return 3
548
+ target = argv[0]
549
+ tmp = None
550
+ if os.name == "posix":
551
+ import signal
552
+ signal.signal(signal.SIGALRM, lambda *a: (_ for _ in ()).throw(TimeoutError("whole job over time")))
553
+ signal.alarm(JOB_SECONDS)
554
+ try:
555
+ if os.path.isdir(target):
556
+ res = scan(files_from_folder(target))
557
+ label = target
558
+ else:
559
+ bad = check_url(target)
560
+ if bad:
561
+ print(f"REFUSED: {bad}")
562
+ return 3
563
+ tmp = tempfile.mkdtemp(prefix="hg-check-")
564
+ env = _clean_env(tmp)
565
+ dest = os.path.join(tmp, "repo.git")
566
+ subprocess.run(clone_cmd(target, dest), env=env, timeout=CLONE_TIMEOUT, check=True, cwd=tmp,
567
+ capture_output=True, preexec_fn=_limits if os.name == "posix" else None)
568
+ res = scan(files_from_git(os.path.join(dest, ".git"), env))
569
+ label = target
570
+ except Exception as exc:
571
+ print(f"ERROR: could not check {safe(target)[:200]}: {type(exc).__name__}")
572
+ return 3
573
+ finally:
574
+ if tmp:
575
+ shutil.rmtree(tmp, ignore_errors=True)
576
+ order = {s: i for i, s in enumerate(reversed(SEV))}
577
+ print(f"{res['verdict']}: {safe(label)} ({res['read']} of {res['files']} files read, nothing run; binary files are checked by type, not content)")
578
+ shown = [f for f in res["findings"] if not f.get("allowed")]
579
+ known = len(res["findings"]) - len(shown)
580
+ for f in sorted(shown, key=lambda f: (order[f["sev"]], f["file"], f["line"]))[:60]:
581
+ line = f" {f['sev'].upper():8} {f['rule']:22} {f['file'][:120]}:{f['line']} {f['why']}"
582
+ print(line + (f" | {f['text']}" if show_text and f["text"] else ""))
583
+ if not show_text and any(f["text"] for f in shown):
584
+ print(" (repo text hidden: it is untrusted and may be aimed at an AI. A person can add --show-text.)")
585
+ if known:
586
+ print(f" known-okay (allowlisted, content unchanged): {known}")
587
+ if len(shown) > 60:
588
+ print(f" ... {len(shown) - 60} more")
589
+ if res["skipped"]:
590
+ print(f" not read: {len(res['skipped'])} ({'; '.join(res['skipped'][:5])}{' ...' if len(res['skipped']) > 5 else ''})")
591
+ print(" GREEN means no KNOWN trick was found, never a promise. RED = stop and have a person look.")
592
+ return {"GREEN": 0, "YELLOW": 1, "RED": 2, "INCOMPLETE": 4}[res["verdict"]]
593
+
594
+
595
+ if __name__ == "__main__":
596
+ sys.exit(main(sys.argv[1:]))
hearthwatch/cli.py ADDED
@@ -0,0 +1,27 @@
1
+ """Command-line entry points created by `pip install hearthwatch`:
2
+
3
+ hearthwatch-check <https link or folder> check before you install (check_repo)
4
+ hearthwatch-keys did a live key leak into git history (keys)
5
+ hearthwatch-scan scan | hit <name> [version] Linux server package watch (scan)
6
+
7
+ Run these from OUTSIDE the folder you are checking. An installed command does not run Python in isolated
8
+ mode: a PYTHONPATH that holds "." or an empty entry puts the current folder on the import path, and on
9
+ Windows Command Prompt a program in the current folder with the same name starts before the real one.
10
+ To check a folder while standing in it, use `python3 -I hw_check.py` from a Hearthwatch checkout.
11
+ """
12
+ import sys
13
+
14
+
15
+ def check() -> None:
16
+ from hearthwatch.check_repo import main
17
+ sys.exit(main(sys.argv[1:]))
18
+
19
+
20
+ def keys() -> None:
21
+ from hearthwatch.keys import main
22
+ sys.exit(main())
23
+
24
+
25
+ def scan() -> None:
26
+ from hearthwatch.scan import main
27
+ sys.exit(main(sys.argv[1:]))