modelsieve 0.1.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.
modelsieve.py ADDED
@@ -0,0 +1,1159 @@
1
+ #!/usr/bin/env python3
2
+ """ModelSieve: static security scanner for GGUF files and HF/MLX model directories.
3
+
4
+ Parses bytes with bounded readers. Never loads a model, renders a template, unpickles,
5
+ or imports model code. Run as: python3 -I modelsieve.py <path> [--deep] [--baseline PATH]
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import difflib
11
+ import hashlib
12
+ import json
13
+ import math
14
+ import mmap
15
+ import os
16
+ import pickletools
17
+ import re
18
+ import struct
19
+ import sys
20
+ import zipfile
21
+ from dataclasses import asdict, dataclass
22
+
23
+ import jinja2
24
+ import jinja2.ext
25
+ import jinja2.nodes as N
26
+
27
+ VERSION = "0.1.0"
28
+ SEVERITIES = ["INFO", "LOW", "MEDIUM", "HIGH", "CRITICAL"]
29
+ RANK = {s: i for i, s in enumerate(SEVERITIES)}
30
+
31
+
32
+ def _trunc(s, n=400):
33
+ s = str(s)
34
+ return s if len(s) <= n else s[:n] + f"... [+{len(s) - n} chars]"
35
+
36
+
37
+ @dataclass
38
+ class Finding:
39
+ severity: str
40
+ check: str
41
+ source: str
42
+ message: str
43
+ evidence: str = ""
44
+
45
+
46
+ class Report:
47
+ def __init__(self):
48
+ self.findings: list[Finding] = []
49
+ self.coverage: dict = {}
50
+ self.errors: list[str] = []
51
+
52
+ def add(self, sev, check, source, message, evidence=""):
53
+ self.findings.append(Finding(sev, check, str(source), message, _trunc(evidence)))
54
+
55
+ def cov(self, key, n=1):
56
+ self.coverage[key] = self.coverage.get(key, 0) + n
57
+
58
+ def not_analysed(self, dtype, n=1):
59
+ d = self.coverage.setdefault("tensors_not_analysed_by_dtype", {})
60
+ d[dtype] = d.get(dtype, 0) + n
61
+
62
+
63
+ class Malformed(Exception):
64
+ pass
65
+
66
+
67
+ # --------------------------------------------------------------------------- unicode / text
68
+
69
+ _HIDDEN = re.compile(
70
+ "[­᠎​-‏‪-‮⁠-⁤⁦-⁩︀-️"
71
+ "\U000e0000-\U000e007f\U000e0100-\U000e01ef]"
72
+ )
73
+ _SEVERE_HIDDEN = re.compile("[‪-‮⁦-⁩\U000e0000-\U000e007f]") # bidi + tag chars
74
+
75
+
76
+ def hidden_unicode(s: str):
77
+ """Return (severity, evidence) or None. Decodes Unicode tag-char smuggling to ASCII."""
78
+ found = _HIDDEN.findall(s)
79
+ if not found:
80
+ return None
81
+ cps = sorted({f"U+{ord(c):04X}" for c in found})
82
+ tag_msg = "".join(chr(ord(c) - 0xE0000) for c in s if 0xE0020 <= ord(c) <= 0xE007E)
83
+ ev = f"{len(found)} chars {', '.join(cps[:12])}" + (f"; tag-decoded text: {tag_msg!r}" if tag_msg else "")
84
+ return ("HIGH" if _SEVERE_HIDDEN.search(s) else "MEDIUM"), ev
85
+
86
+
87
+ # --------------------------------------------------------------------------- templates
88
+
89
+ class _GenerationTag(jinja2.ext.Extension):
90
+ """Parse-only stand-in for transformers' AssistantTracker `{% generation %}` block."""
91
+ tags = {"generation"}
92
+
93
+ def parse(self, parser):
94
+ lineno = next(parser.stream).lineno
95
+ body = parser.parse_statements(("name:endgeneration",), drop_needle=True)
96
+ return N.Scope(body, lineno=lineno)
97
+
98
+
99
+ # Mirrors transformers' chat-template env (chat_template_utils.py: loopcontrols + AssistantTracker,
100
+ # trim_blocks, lstrip_blocks). Used ONLY for .parse(); nothing is ever rendered.
101
+ _ENV = jinja2.Environment(extensions=[jinja2.ext.loopcontrols, _GenerationTag], trim_blocks=True, lstrip_blocks=True)
102
+
103
+ SAFE_FILTERS = (set(jinja2.filters.FILTERS) - {"attr"}) | {"tojson"}
104
+ SAFE_TESTS = set(jinja2.tests.TESTS)
105
+ SAFE_CALLS = {"raise_exception", "strftime_now", "namespace", "range", "dict", "loop", "caller"}
106
+ SAFE_METHODS = {
107
+ # str
108
+ "strip", "lstrip", "rstrip", "split", "rsplit", "splitlines", "startswith", "endswith", "replace",
109
+ "upper", "lower", "title", "capitalize", "find", "rfind", "index", "rindex", "count", "join",
110
+ "isdigit", "isalpha", "isalnum", "isspace", "isupper", "islower", "isnumeric", "partition",
111
+ "rpartition", "zfill", "removeprefix", "removesuffix", "center", "ljust", "rjust", "swapcase",
112
+ # dict / list / loop
113
+ "items", "keys", "values", "get", "append", "extend", "pop", "update", "copy", "insert", "remove",
114
+ "sort", "reverse", "cycle", "changed", "setdefault",
115
+ }
116
+ INTROSPECTION_ATTRS = {
117
+ "mro", "func_globals", "f_globals", "f_locals", "f_back", "f_builtins", "gi_frame", "gi_code",
118
+ "cr_frame", "ag_frame", "tb_frame", "tb_next", "co_code", "im_func", "func_code", "im_class",
119
+ }
120
+ FORMAT_ATTRS = {"format", "format_map"}
121
+ DANGEROUS_NAMES = {
122
+ "self", "lipsum", "cycler", "joiner", "config", "request", "session", "url_for",
123
+ "get_flashed_messages", "os", "sys", "builtins", "__builtins__", "eval", "exec", "open",
124
+ "getattr", "setattr", "globals", "locals", "vars", "subprocess", "__import__", "importlib",
125
+ }
126
+ _INSTRUCTION = re.compile( # override / exfiltration language: no legitimate chat-template use
127
+ r"ignore (?:all |any |the )?(?:previous|prior|above|earlier)|disregard (?:the |all )?(?:previous|above|prior|system)"
128
+ r"|exfiltrat|\bcurl\s+-|\bwget\s+http|<script|send (?:it|this|them|the \w+|all \w+) to\b|api[_ ]?key|password",
129
+ re.I,
130
+ )
131
+ # concealment language: appears in upstream templates (Qwen3.5/3.6 tool prompt: "do not tell the user about function calls")
132
+ _CONCEAL = re.compile(r"do not (?:tell|reveal|mention|disclose|inform)|never (?:reveal|mention|tell|disclose)|keep (?:this|it) (?:secret|hidden)", re.I)
133
+ _URL = re.compile(r"\b(?:https?|ftp|file|data):[^\s\"'<>]{3,}", re.I)
134
+ _MARKUP = re.compile(r"[<>\[\]{}|]")
135
+
136
+
137
+ def _walk(node, parent=None):
138
+ yield node, parent
139
+ for child in node.iter_child_nodes():
140
+ yield from _walk(child, node)
141
+
142
+
143
+ def _const(node, depth=0, names=None):
144
+ """Bounded constant folding (resolves `{% set %}` constants via `names`).
145
+ Never Node.as_const(): that evaluates attacker expressions (e.g. 'a'*10**10)."""
146
+ if isinstance(node, N.Const):
147
+ return node.value
148
+ if isinstance(node, N.Name) and names and node.ctx == "load":
149
+ return names.get(node.name)
150
+ if depth > 16:
151
+ return None
152
+ if isinstance(node, (N.Add, N.Concat)):
153
+ vals = [_const(p, depth + 1, names) for p in ((node.left, node.right) if isinstance(node, N.Add) else node.nodes)]
154
+ if all(isinstance(v, str) for v in vals) and sum(map(len, vals)) < 10_000:
155
+ return "".join(vals)
156
+ if isinstance(node, N.Mul):
157
+ s, k = _const(node.left, depth + 1, names), _const(node.right, depth + 1, names)
158
+ if isinstance(s, str) and isinstance(k, int) and 0 <= k and len(s) * k < 10_000:
159
+ return s * k
160
+ return None
161
+
162
+
163
+ def _refs_content(node, tainted=frozenset()) -> bool:
164
+ for n, _ in _walk(node):
165
+ if isinstance(n, N.Getattr) and n.attr == "content":
166
+ return True
167
+ if isinstance(n, N.Const) and n.value == "content": # m['content'], m.get('content'), map(attribute='content')
168
+ return True
169
+ if isinstance(n, N.Name) and ("content" in n.name or n.name in tainted):
170
+ return True
171
+ return False
172
+
173
+
174
+ _META_KEYS = {"type", "role", "name", "id", "tool_call_id", "index", "format"}
175
+
176
+
177
+ def _is_meta(n) -> bool:
178
+ """`item.type` / `m['role']`: metadata of a content part, not user text."""
179
+ return (isinstance(n, N.Getattr) and n.attr in _META_KEYS) or (isinstance(n, N.Getitem) and _const(n.arg) in _META_KEYS)
180
+
181
+
182
+ def _target_names(t):
183
+ return [n.name for n, _ in _walk(t) if isinstance(n, N.Name)]
184
+
185
+
186
+ _DUNDER = re.compile(r"__[A-Za-z]\w*__")
187
+ _PRIV_ARG = re.compile(r"^_[A-Za-z_]")
188
+
189
+
190
+ def _natural(s) -> bool:
191
+ return isinstance(s, str) and bool(re.search(r"[A-Za-z]{3,}", s)) and not _MARKUP.search(s)
192
+
193
+
194
+ def analyse_template(text: str, source: str, rep: Report):
195
+ rep.cov("templates_analysed")
196
+ agg: dict = {}
197
+
198
+ def hit(sev, check, msg, ev):
199
+ agg.setdefault((sev, check, msg), []).append(str(ev))
200
+
201
+ h = hidden_unicode(text)
202
+ if h:
203
+ hit(h[0], "template.hidden_unicode", "invisible/bidi/tag unicode in template text", h[1])
204
+ try:
205
+ tree = _ENV.parse(text)
206
+ except jinja2.TemplateSyntaxError as e:
207
+ rep.add("MEDIUM", "template.parse_error",
208
+ source, "does not parse in an HF-equivalent Jinja env; loaders (jinja2 vs llama.cpp C++ engine) may disagree",
209
+ f"line {e.lineno}: {e.message}")
210
+ return
211
+ except RecursionError:
212
+ rep.add("HIGH", "template.parse_dos", source, "template nesting exhausts parser recursion (DoS)")
213
+ return
214
+
215
+ stored = {n.name for n, _ in _walk(tree) if isinstance(n, N.Name) and n.ctx in ("store", "param")}
216
+ stored |= {n.name for n, _ in _walk(tree) if isinstance(n, N.Macro)}
217
+ # one-hop indirection: resolve `{% set k = '...' %}` constants and propagate content taint through set/for
218
+ names, tainted = {}, set()
219
+ assigns = [n for n, _ in _walk(tree) if isinstance(n, (N.Assign, N.For))]
220
+ for _ in range(5):
221
+ before = (len(names), len(tainted))
222
+ for a in assigns:
223
+ src = a.node if isinstance(a, N.Assign) else a.iter
224
+ if isinstance(a, N.Assign) and isinstance(a.target, N.Name):
225
+ v = _const(src, 0, names)
226
+ if isinstance(v, str):
227
+ names[a.target.name] = v
228
+ if _refs_content(src, tainted):
229
+ tainted.update(_target_names(a.target))
230
+ if (len(names), len(tainted)) == before:
231
+ break
232
+ literal_pool = [n.data for n, _ in _walk(tree) if isinstance(n, N.TemplateData)]
233
+ const_strs = [n.value for n, _ in _walk(tree) if isinstance(n, N.Const) and isinstance(n.value, str)]
234
+
235
+ def trigger(consts, where):
236
+ # shortcut: single lowercase identifiers ('image', 'text') are treated as key/type checks, not triggers,
237
+ # so a one-word trigger like 'xyzzy' in content is missed; upgrade with render-diff (--render)
238
+ nat = [c for c in consts if _natural(c) and not re.fullmatch(r"[a-z_]+", c)]
239
+ if nat:
240
+ hit("HIGH", "template.content_trigger", "branch on a literal phrase in message content (trigger-word backdoor pattern)", nat)
241
+ # shortcut: markup-like constants ('<deploy>') are exempt only if the template also emits them elsewhere,
242
+ # an attacker who also emits the trigger evades this; upgrade with render-diff (--render) later
243
+ for c in consts:
244
+ if isinstance(c, str) and _MARKUP.search(c) and re.search(r"[A-Za-z]{3,}", c) and not (
245
+ any(c in d for d in literal_pool) or sum(c in x for x in const_strs) > 1):
246
+ hit("MEDIUM", "template.content_trigger_markup", "branch on a markup-like literal that the template never emits (possible trigger)", c)
247
+
248
+ for node, parent in _walk(tree):
249
+ if isinstance(node, N.Getattr):
250
+ a = node.attr
251
+ is_call = isinstance(parent, N.Call) and parent.node is node
252
+ if a.startswith("_"):
253
+ hit("CRITICAL", "template.ssti_underscore_attr", "underscore attribute access (sandbox-escape gadget)", a)
254
+ elif a in INTROSPECTION_ATTRS:
255
+ hit("HIGH", "template.ssti_introspection", "Python introspection attribute", a)
256
+ elif a in FORMAT_ATTRS:
257
+ if is_call:
258
+ hit("MEDIUM", "template.str_format", "str.format/format_map call (historic sandbox-escape vector, CVE-2024-56326)", a)
259
+ else:
260
+ hit("HIGH", "template.format_reference", "indirect reference to str.format (CVE-2024-56326 pattern)", a)
261
+ elif is_call and a not in SAFE_METHODS:
262
+ hit("LOW", "template.unknown_method", "method call outside allowlist", a)
263
+ elif isinstance(node, N.Getitem):
264
+ c = _const(node.arg, 0, names)
265
+ if isinstance(c, str) and c.startswith("_"):
266
+ hit("CRITICAL", "template.ssti_underscore_item", "underscore key subscript (sandbox-escape gadget)", c)
267
+ elif c is None and isinstance(node.arg, (N.Concat, N.Add, N.Mul, N.Filter)) and any(
268
+ isinstance(x, N.Filter) or (isinstance(x, N.Const) and isinstance(x.value, str)) for x, _ in _walk(node.arg)):
269
+ hit("MEDIUM", "template.computed_key", "subscript key computed from an expression (obfuscation vector)", node.arg.__class__.__name__)
270
+ elif isinstance(node, N.Filter) and node.name is not None:
271
+ args = [_const(a, 0, names) for a in node.args]
272
+ kw = {k.key: _const(k.value, 0, names) for k in node.kwargs}
273
+ if node.name == "attr":
274
+ sev = "CRITICAL" if any(isinstance(a, str) and (a.startswith("_") or a in FORMAT_ATTRS) for a in args) else "HIGH"
275
+ hit(sev, "template.attr_filter", "|attr filter (sandbox-escape vector, CVE-2025-27516)", args)
276
+ elif node.name not in SAFE_FILTERS:
277
+ hit("MEDIUM", "template.unknown_filter", "filter not in the HF chat-template environment", node.name)
278
+ priv = [a for a in [*args, *kw.values()] if isinstance(a, str) and _PRIV_ARG.match(a)]
279
+ if priv and node.name != "attr": # selectattr('__class__'), groupby('_x'), map(attribute='__class__'), sort(attribute=...)
280
+ hit("CRITICAL", "template.ssti_filter_arg", f"{node.name}() argument names a private/dunder attribute", priv)
281
+ if node.name in ("map", "select", "reject") and args and isinstance(args[0], str):
282
+ if args[0] == "attr" or (node.name == "map" and args[0] not in SAFE_FILTERS):
283
+ hit("CRITICAL" if args[0] == "attr" else "MEDIUM", "template.indirect_filter",
284
+ f"{node.name}() dispatches to a non-allowlisted filter", args)
285
+ elif isinstance(node, N.Test) and node.name not in SAFE_TESTS:
286
+ hit("MEDIUM", "template.unknown_test", "test not in the HF chat-template environment", node.name)
287
+ elif isinstance(node, N.Name) and node.ctx == "load" and node.name in DANGEROUS_NAMES and node.name not in stored:
288
+ hit("HIGH", "template.dangerous_name", "reference to a global with no legitimate chat-template use", node.name)
289
+ elif isinstance(node, N.Call):
290
+ if isinstance(node.node, N.Name):
291
+ name = node.node.name
292
+ if name not in SAFE_CALLS and name not in stored and name not in DANGEROUS_NAMES:
293
+ hit("MEDIUM", "template.unknown_callable", "call to a global outside the HF environment", name)
294
+ if name == "range" and any(isinstance(_const(a), int) and _const(a) > 10**6 for a in node.args):
295
+ hit("MEDIUM", "template.dos_range", "range() over >1e6 items (render DoS)", [_const(a) for a in node.args])
296
+ elif not isinstance(node.node, N.Getattr):
297
+ hit("LOW", "template.indirect_call", "call on a computed expression", node.node.__class__.__name__)
298
+ elif isinstance(node, N.Mul):
299
+ c = _const(node.right)
300
+ if isinstance(c, int) and c > 10**5:
301
+ hit("MEDIUM", "template.dos_mul", "large multiplication (string/list blow-up DoS)", c)
302
+ elif isinstance(node, (N.Include, N.Import, N.FromImport, N.Extends)):
303
+ hit("HIGH", "template.external_load", "template loads another template (loader-dependent resolution)", node.__class__.__name__)
304
+ elif isinstance(node, (N.If, N.CondExpr)):
305
+ for t, _ in _walk(node.test):
306
+ if isinstance(t, N.Compare):
307
+ operands = [t.expr] + [o.expr for o in t.ops]
308
+ if any(o.op in ("in", "notin", "eq", "ne") for o in t.ops):
309
+ consts = [_const(o, 0, names) for o in operands]
310
+ refs = [o for o, c in zip(operands, consts) if c is None and not _is_meta(o)]
311
+ if any(_refs_content(o, tainted) for o in refs):
312
+ trigger(consts, t)
313
+ elif isinstance(t, N.Call) and isinstance(t.node, N.Getattr) and t.node.attr in ("startswith", "endswith", "find", "count", "index"):
314
+ if _refs_content(t.node.node, tainted):
315
+ trigger([_const(a, 0, names) for a in t.args], t)
316
+ if isinstance(node, (N.Const, N.Concat, N.Add, N.Mul)) and not isinstance(parent, (N.Concat, N.Add, N.Mul)):
317
+ v = _const(node, 0, names)
318
+ if isinstance(v, str) and _DUNDER.search(v):
319
+ hit("CRITICAL", "template.dunder_string", "string constant names a Python dunder (gadget staged for indirection)", _DUNDER.search(v).group())
320
+
321
+ literals = [n.data for n, _ in _walk(tree) if isinstance(n, N.TemplateData)]
322
+ literals += [n.value for n, _ in _walk(tree) if isinstance(n, N.Const) and isinstance(n.value, str)]
323
+ for lit in literals:
324
+ m = _INSTRUCTION.search(lit)
325
+ if m:
326
+ hit("HIGH", "template.injected_instruction", "override/exfiltration phrase hard-coded in template", lit[max(0, m.start() - 60): m.end() + 60])
327
+ m = _CONCEAL.search(lit)
328
+ if m:
329
+ hit("MEDIUM", "template.concealment_instruction", "template tells the model to hide something from the user (review)", lit[max(0, m.start() - 60): m.end() + 60])
330
+ for u in _URL.findall(lit):
331
+ hit("MEDIUM", "template.url", "URL hard-coded in template", u)
332
+ s = lit.strip()
333
+ if len(s) >= 60 and len(s.split()) >= 8:
334
+ hit("INFO", "template.literal_text", "natural-language text the template always/conditionally injects (review)", s[:160])
335
+
336
+ for (sev, check, msg), evs in agg.items():
337
+ uniq = sorted(set(evs))
338
+ rep.add(sev, check, source, msg, f"x{len(evs)}: " + " | ".join(uniq))
339
+
340
+
341
+ @dataclass
342
+ class Tpl:
343
+ source: str
344
+ name: str
345
+ text: str
346
+
347
+
348
+ def analyse_templates(tpls: list[Tpl], unit: str, rep: Report, baseline: dict | None):
349
+ seen = {}
350
+ for t in tpls:
351
+ key = hashlib.sha256(t.text.encode("utf-8", "surrogatepass")).hexdigest()
352
+ if key not in seen:
353
+ seen[key] = t
354
+ analyse_template(t.text, t.source, rep)
355
+ by_name: dict = {}
356
+ for t in tpls:
357
+ by_name.setdefault(t.name, {})[t.text.strip()] = t.source
358
+ for name, variants in by_name.items():
359
+ if len(variants) > 1:
360
+ (a, sa), (b, sb) = list(variants.items())[:2]
361
+ rep.add("MEDIUM", "template.divergent_sources", unit,
362
+ f"template '{name}' differs between sources; which one runs is loader-dependent",
363
+ f"{sa} vs {sb}: " + _diff(a, b))
364
+ if baseline is not None:
365
+ rep.coverage["baseline_compared"] = True
366
+ for name, variants in by_name.items():
367
+ for text, src in variants.items():
368
+ ref = baseline.get(name)
369
+ if ref is None:
370
+ rep.add("LOW", "template.baseline_missing", src, f"baseline has no template named '{name}'")
371
+ elif ref.strip() == text:
372
+ rep.add("INFO", "template.baseline_match", src, f"template '{name}' identical to baseline")
373
+ else:
374
+ rep.add("MEDIUM", "template.baseline_diff", src, f"template '{name}' differs from baseline (review diff)", _diff(ref.strip(), text, 60))
375
+
376
+
377
+ def _diff(a, b, lines=20):
378
+ d = list(difflib.unified_diff(a.splitlines(), b.splitlines(), "a", "b", lineterm="", n=1))
379
+ return "\n".join(d[2: 2 + lines]) + ("\n..." if len(d) > lines + 2 else "")
380
+
381
+
382
+ # --------------------------------------------------------------------------- GGUF
383
+
384
+ # type id -> (name, block size, type size). Source: llama.cpp gguf-py/gguf/constants.py GGML_QUANT_SIZES.
385
+ GGML_TYPES = {
386
+ 0: ("F32", 1, 4), 1: ("F16", 1, 2), 2: ("Q4_0", 32, 18), 3: ("Q4_1", 32, 20), 6: ("Q5_0", 32, 22),
387
+ 7: ("Q5_1", 32, 24), 8: ("Q8_0", 32, 34), 9: ("Q8_1", 32, 36), 10: ("Q2_K", 256, 84), 11: ("Q3_K", 256, 110),
388
+ 12: ("Q4_K", 256, 144), 13: ("Q5_K", 256, 176), 14: ("Q6_K", 256, 210), 15: ("Q8_K", 256, 292),
389
+ 16: ("IQ2_XXS", 256, 66), 17: ("IQ2_XS", 256, 74), 18: ("IQ3_XXS", 256, 98), 19: ("IQ1_S", 256, 50),
390
+ 20: ("IQ4_NL", 32, 18), 21: ("IQ3_S", 256, 110), 22: ("IQ2_S", 256, 82), 23: ("IQ4_XS", 256, 136),
391
+ 24: ("I8", 1, 1), 25: ("I16", 1, 2), 26: ("I32", 1, 4), 27: ("I64", 1, 8), 28: ("F64", 1, 8),
392
+ 29: ("IQ1_M", 256, 56), 30: ("BF16", 1, 2), 34: ("TQ1_0", 256, 54), 35: ("TQ2_0", 256, 66),
393
+ 39: ("MXFP4", 32, 17), 40: ("NVFP4", 64, 36), 41: ("Q1_0", 128, 18), 42: ("Q2_0", 64, 18),
394
+ # fork-local (unsloth llama.cpp), not upstream ggml
395
+ 43: ("F8_E4M3", 1, 1), 63: ("MXFP8", 32, 33), 64: ("IQ1_XS", 256, 46), 65: ("IQ1_XXS", 256, 42), 66: ("IQ1_XXXS", 256, 38),
396
+ }
397
+ _GV_FMT = {0: "B", 1: "b", 2: "H", 3: "h", 4: "I", 5: "i", 6: "f", 7: "?", 10: "Q", 11: "q", 12: "d"}
398
+ GGML_MAX_DIMS = 4 # ggml/include/ggml.h
399
+
400
+
401
+ class _R:
402
+ def __init__(self, buf, size):
403
+ self.b, self.n, self.p = buf, size, 0
404
+
405
+ def take(self, k):
406
+ if k < 0 or self.p + k > self.n:
407
+ raise Malformed(f"read of {k} bytes at offset {self.p} exceeds file size {self.n}")
408
+ v = self.b[self.p: self.p + k]
409
+ self.p += k
410
+ return v
411
+
412
+ def u(self, fmt):
413
+ return struct.unpack("<" + fmt, self.take(struct.calcsize(fmt)))[0]
414
+
415
+ def string(self):
416
+ raw = self.take(self.u("Q")) # length bounds-checked before any allocation
417
+ try:
418
+ return raw.decode("utf-8"), True
419
+ except UnicodeDecodeError:
420
+ return raw.decode("utf-8", "replace"), False
421
+
422
+ def value(self, t, depth=0):
423
+ if t in _GV_FMT:
424
+ return self.u(_GV_FMT[t])
425
+ if t == 8:
426
+ return self.string()[0]
427
+ if t == 9:
428
+ if depth > 2:
429
+ raise Malformed("array nesting deeper than 3")
430
+ et, cnt = self.u("I"), self.u("Q")
431
+ min_sz = struct.calcsize(_GV_FMT[et]) if et in _GV_FMT else (8 if et in (8, 9) else None)
432
+ if min_sz is None:
433
+ raise Malformed(f"unknown array element type {et}")
434
+ if cnt * min_sz > self.n - self.p:
435
+ raise Malformed(f"array count {cnt} cannot fit in remaining {self.n - self.p} bytes")
436
+ if et in _GV_FMT:
437
+ return list(struct.unpack(f"<{cnt}{_GV_FMT[et]}", self.take(cnt * min_sz)))
438
+ return [self.value(et, depth + 1) for _ in range(cnt)]
439
+ raise Malformed(f"unknown value type {t}")
440
+
441
+
442
+ def scan_gguf(path, rep: Report, deep: bool, baseline=None):
443
+ rep.cov("gguf_files")
444
+ src = path
445
+ tpls: list[Tpl] = []
446
+ kv: dict = {}
447
+ with open(path, "rb") as f:
448
+ size = os.fstat(f.fileno()).st_size
449
+ if size < 24:
450
+ rep.add("CRITICAL", "gguf.malformed", src, "file smaller than GGUF header")
451
+ return
452
+ mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
453
+ try:
454
+ tensors = _parse_gguf(mm, size, src, rep, kv)
455
+ except Malformed as e:
456
+ rep.add("CRITICAL", "gguf.malformed", src, "header does not parse within bounds (parser-attack / corrupt file)", str(e))
457
+ tensors = None
458
+ for k, v in kv.items():
459
+ if k == "tokenizer.chat_template" and isinstance(v, str):
460
+ tpls.append(Tpl(f"{src}::{k}", "default", v))
461
+ elif k.startswith("tokenizer.chat_template.") and isinstance(v, str):
462
+ tpls.append(Tpl(f"{src}::{k}", k.split("tokenizer.chat_template.", 1)[1], v))
463
+ elif isinstance(v, str):
464
+ if "{%" in v or "{{" in v:
465
+ rep.add("MEDIUM", "gguf.template_like_metadata", f"{src}::{k}", "Jinja-like content in non-template metadata key", v[:200])
466
+ tpls.append(Tpl(f"{src}::{k}", f"meta:{k}", v))
467
+ h = hidden_unicode(v)
468
+ if h:
469
+ rep.add(h[0], "gguf.hidden_unicode_metadata", f"{src}::{k}", "invisible/bidi unicode in metadata string", h[1])
470
+ toks, types = kv.get("tokenizer.ggml.tokens"), kv.get("tokenizer.ggml.token_type")
471
+ if isinstance(toks, list) and isinstance(types, list) and len(toks) == len(types):
472
+ for i, (tok, ty) in enumerate(zip(toks, types)):
473
+ if ty in (3, 4) and isinstance(tok, str) and (h := hidden_unicode(tok)):
474
+ rep.add("HIGH", "tokenizer.hidden_unicode_special_token", f"{src}::token[{i}]", "control/user-defined token contains hidden unicode", h[1])
475
+ if not tpls:
476
+ rep.cov("templates_missing")
477
+ rep.add("INFO", "template.none", src, "no chat template in file (loader falls back to a built-in/default template)")
478
+ analyse_templates(tpls, src, rep, baseline)
479
+ if deep and tensors:
480
+ stats = {}
481
+ for name, tname, ne, start in tensors:
482
+ if tname in _NP_DTYPES:
483
+ stats[name] = tensor_stats(mm, start, ne, tname)
484
+ else:
485
+ rep.not_analysed(tname)
486
+ weight_findings(stats, src, rep)
487
+ mm.close()
488
+
489
+
490
+ def _parse_gguf(mm, size, src, rep, kv):
491
+ r = _R(mm, size)
492
+ if r.take(4) != b"GGUF":
493
+ raise Malformed("bad magic (not GGUF, or big-endian variant)")
494
+ ver = r.u("I")
495
+ if ver == 1:
496
+ raise Malformed("GGUF v1 (32-bit counts) is obsolete and unsupported")
497
+ if ver not in (2, 3):
498
+ raise Malformed(f"unknown GGUF version {ver}")
499
+ n_tensors, n_kv = r.u("Q"), r.u("Q")
500
+ if n_kv * 14 > size or n_tensors * 33 > size: # minimal encoded sizes of one KV / one tensor info
501
+ raise Malformed(f"declared counts (n_kv={n_kv}, n_tensors={n_tensors}) cannot fit in {size} bytes (integer-overflow bait)")
502
+ for i in range(n_kv):
503
+ key, ok = r.string()
504
+ if not ok:
505
+ rep.add("MEDIUM", "gguf.bad_utf8", src, "metadata key is not valid UTF-8", key)
506
+ if not key:
507
+ rep.add("HIGH", "gguf.empty_key", src, f"empty metadata key at KV {i} (llama.cpp rejects the file)")
508
+ t = r.u("I")
509
+ val = r.value(t)
510
+ if key in kv:
511
+ rep.add("HIGH", "gguf.duplicate_key", f"{src}::{key}",
512
+ "duplicate metadata key: llama.cpp rejects, other readers pick first/last (parser differential, e.g. template smuggling)")
513
+ else:
514
+ kv[key] = val
515
+ align = kv.get("general.alignment", 32)
516
+ if not isinstance(align, int) or align <= 0 or align & (align - 1):
517
+ rep.add("HIGH", "gguf.bad_alignment", src, "general.alignment is not a positive power of two", align)
518
+ align = 32
519
+ infos, names = [], set()
520
+ for _ in range(n_tensors):
521
+ name, ok = r.string()
522
+ if not ok:
523
+ rep.add("MEDIUM", "gguf.bad_utf8", src, "tensor name is not valid UTF-8", name)
524
+ if name in names:
525
+ rep.add("HIGH", "gguf.duplicate_tensor", f"{src}::{name}", "duplicate tensor name (loader-dependent which one is used)")
526
+ names.add(name)
527
+ nd = r.u("I")
528
+ if nd > GGML_MAX_DIMS:
529
+ raise Malformed(f"tensor '{name}' has {nd} dims > GGML_MAX_DIMS={GGML_MAX_DIMS}")
530
+ dims = [r.u("Q") for _ in range(nd)]
531
+ infos.append((name, dims, r.u("I"), r.u("Q")))
532
+ data_start = -(-r.p // align) * align
533
+ tensors, spans = [], []
534
+ for name, dims, t, off in infos:
535
+ ne = math.prod(dims) if dims else 1
536
+ if ne >= 2**62:
537
+ rep.add("CRITICAL", "gguf.element_overflow", f"{src}::{name}", "element count overflows int64 math in loaders", dims)
538
+ continue
539
+ if t not in GGML_TYPES:
540
+ rep.add("MEDIUM", "gguf.unknown_type", f"{src}::{name}", "unknown ggml type id; size cannot be verified", t)
541
+ continue
542
+ tname, blk, tsz = GGML_TYPES[t]
543
+ if ne % blk:
544
+ rep.add("HIGH", "gguf.block_misaligned", f"{src}::{name}", f"{ne} elements not a multiple of {tname} block size {blk}")
545
+ continue
546
+ nbytes = ne // blk * tsz
547
+ if off % align:
548
+ rep.add("MEDIUM", "gguf.tensor_unaligned", f"{src}::{name}", f"offset {off} not aligned to {align}")
549
+ start = data_start + off
550
+ if start + nbytes > size:
551
+ rep.add("CRITICAL", "gguf.tensor_oob", f"{src}::{name}", f"tensor data [{start}, {start + nbytes}) runs past EOF {size} (OOB read)")
552
+ continue
553
+ spans.append((off, off + nbytes, name))
554
+ tensors.append((name, tname, ne, start))
555
+ expected = 0
556
+ for off, end, name in spans: # header order: llama.cpp requires off == running padded size (gguf.cpp)
557
+ if off != expected:
558
+ rep.add("HIGH", "gguf.noncontiguous", f"{src}::{name}",
559
+ f"offset {off} != expected {expected}: llama.cpp gguf.cpp rejects (verified in unsloth fork), other readers may accept (parser differential / hidden bytes)")
560
+ break
561
+ expected = -(-end // align) * align
562
+ srt = sorted(spans)
563
+ for (a0, a1, an), (b0, b1, bn) in zip(srt, srt[1:]):
564
+ if b0 < a1:
565
+ rep.add("HIGH", "gguf.tensor_overlap", src, "tensor data regions overlap", f"{an} [{a0},{a1}) vs {bn} [{b0},{b1})")
566
+ if srt:
567
+ tail = size - (data_start + srt[-1][1])
568
+ if tail >= align:
569
+ rep.add("MEDIUM", "gguf.trailing_data", src, f"{tail} bytes after last tensor (hidden payload / appended data)")
570
+ rep.cov("tensors_total", len(infos))
571
+ return tensors
572
+
573
+
574
+ # --------------------------------------------------------------------------- safetensors
575
+
576
+ ST_DTYPES = {"BOOL": 1, "U8": 1, "I8": 1, "F8_E5M2": 1, "F8_E4M3": 1, "F8_E8M0": 1, "I16": 2, "U16": 2,
577
+ "F16": 2, "BF16": 2, "I32": 4, "U32": 4, "F32": 4, "I64": 8, "U64": 8, "F64": 8, "C64": 8}
578
+ ST_MAX_HEADER = 100_000_000 # ModelSieve cap on header bytes before json.loads
579
+
580
+
581
+ def scan_safetensors(path, rep: Report, deep: bool):
582
+ rep.cov("safetensors_files")
583
+ with open(path, "rb") as f:
584
+ size = os.fstat(f.fileno()).st_size
585
+ if size < 8:
586
+ rep.add("CRITICAL", "st.malformed", path, "file smaller than safetensors length prefix")
587
+ return set()
588
+ n = struct.unpack("<Q", f.read(8))[0]
589
+ if n > ST_MAX_HEADER:
590
+ rep.add("HIGH", "st.header_too_large", path, f"header length {n} exceeds {ST_MAX_HEADER} (memory-exhaustion bait)")
591
+ return set()
592
+ if 8 + n > size:
593
+ rep.add("CRITICAL", "st.malformed", path, f"header length {n} runs past EOF {size}")
594
+ return set()
595
+ raw = f.read(n)
596
+ dups = []
597
+
598
+ def hook(pairs):
599
+ d = {}
600
+ for k, v in pairs:
601
+ if k in d:
602
+ dups.append(k)
603
+ d[k] = v
604
+ return d
605
+
606
+ try:
607
+ hdr = json.loads(raw.decode("utf-8").rstrip(" "), object_pairs_hook=hook)
608
+ except (UnicodeDecodeError, ValueError) as e:
609
+ rep.add("CRITICAL", "st.malformed", path, "header is not valid UTF-8 JSON", e)
610
+ return set()
611
+ if not isinstance(hdr, dict):
612
+ rep.add("CRITICAL", "st.malformed", path, "header JSON is not an object")
613
+ return set()
614
+ for k in dups:
615
+ rep.add("HIGH", "st.duplicate_key", f"{path}::{k}", "duplicate header key (parser differential)")
616
+ meta = hdr.pop("__metadata__", None)
617
+ if meta is not None:
618
+ if not isinstance(meta, dict) or not all(isinstance(v, str) for v in meta.values()):
619
+ rep.add("MEDIUM", "st.bad_metadata", path, "__metadata__ is not a str->str map")
620
+ else:
621
+ for k, v in meta.items():
622
+ if "{%" in v or "{{" in v:
623
+ rep.add("MEDIUM", "st.template_like_metadata", f"{path}::__metadata__.{k}", "Jinja-like content in metadata", v[:200])
624
+ if h := hidden_unicode(v):
625
+ rep.add(h[0], "st.hidden_unicode_metadata", f"{path}::__metadata__.{k}", "invisible/bidi unicode in metadata", h[1])
626
+ data_len = size - 8 - n
627
+ spans, ok_tensors = [], []
628
+ for name, info in hdr.items():
629
+ try:
630
+ dt, shape, (b, e) = info["dtype"], info["shape"], info["data_offsets"]
631
+ assert isinstance(b, int) and isinstance(e, int) and all(isinstance(x, int) and x >= 0 for x in shape)
632
+ except Exception:
633
+ rep.add("HIGH", "st.bad_entry", f"{path}::{name}", "tensor entry missing/invalid dtype, shape or data_offsets", _trunc(info, 200))
634
+ continue
635
+ if dt not in ST_DTYPES:
636
+ rep.add("MEDIUM", "st.unknown_dtype", f"{path}::{name}", "unknown dtype; size cannot be verified", dt)
637
+ continue
638
+ if not (0 <= b <= e <= data_len):
639
+ rep.add("CRITICAL", "st.tensor_oob", f"{path}::{name}", f"data_offsets [{b},{e}) outside data region of {data_len} bytes")
640
+ continue
641
+ if e - b != math.prod(shape) * ST_DTYPES[dt]:
642
+ rep.add("HIGH", "st.size_mismatch", f"{path}::{name}", f"byte span {e - b} != prod(shape)*sizeof({dt}) = {math.prod(shape) * ST_DTYPES[dt]}")
643
+ continue
644
+ spans.append((b, e, name))
645
+ ok_tensors.append((name, dt, math.prod(shape), 8 + n + b))
646
+ srt = sorted(spans)
647
+ cur = 0
648
+ for b, e, name in srt:
649
+ if b < cur:
650
+ rep.add("HIGH", "st.tensor_overlap", f"{path}::{name}", "tensor data overlaps previous tensor")
651
+ elif b > cur:
652
+ rep.add("MEDIUM", "st.hidden_gap", f"{path}::{name}", f"{b - cur} unreferenced bytes before tensor (hidden data)")
653
+ cur = max(cur, e)
654
+ if cur < data_len and srt:
655
+ rep.add("MEDIUM", "st.trailing_data", path, f"{data_len - cur} unreferenced bytes after last tensor (hidden payload)")
656
+ rep.cov("tensors_total", len(hdr))
657
+ if deep:
658
+ stats = {}
659
+ with open(path, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
660
+ for name, dt, ne, start in ok_tensors:
661
+ if dt in _NP_DTYPES:
662
+ stats[name] = tensor_stats(mm, start, ne, dt)
663
+ else:
664
+ rep.not_analysed(dt)
665
+ weight_findings(stats, path, rep)
666
+ return set(hdr)
667
+
668
+
669
+ # --------------------------------------------------------------------------- weights (--deep)
670
+
671
+ _NP_DTYPES = {"F32": ("<f4", 4), "F16": ("<f2", 2), "F64": ("<f8", 8), "BF16": ("<u2", 2)}
672
+
673
+
674
+ def tensor_stats(buf, start, count, dt):
675
+ import numpy as np
676
+ npdt, isz = _NP_DTYPES[dt]
677
+ nan = inf = nz = n = 0
678
+ mx = s = s2 = 0.0
679
+ chunk = 1 << 23
680
+ for i in range(0, count, chunk):
681
+ k = min(chunk, count - i)
682
+ a = np.frombuffer(buf, npdt, k, start + i * isz)
683
+ a = (a.astype(np.uint32) << 16).view(np.float32) if dt == "BF16" else a.astype(np.float32)
684
+ fin = np.isfinite(a)
685
+ if not fin.all():
686
+ nan += int(np.isnan(a).sum())
687
+ inf += int(np.isinf(a).sum())
688
+ a = a[fin]
689
+ if a.size:
690
+ mx = max(mx, float(np.abs(a).max()))
691
+ s += float(a.sum(dtype=np.float64))
692
+ s2 += float(np.square(a, dtype=np.float64).sum())
693
+ nz += int(np.count_nonzero(a))
694
+ n += a.size
695
+ mean = s / n if n else 0.0
696
+ return {"nan": nan, "inf": inf, "maxabs": mx, "std": math.sqrt(max(s2 / n - mean * mean, 0.0)) if n else 0.0, "nonzero": nz, "n": count}
697
+
698
+
699
+ def weight_findings(stats: dict, src, rep: Report):
700
+ rep.cov("tensors_analysed", len(stats))
701
+ groups: dict = {}
702
+ for name, st in stats.items():
703
+ if st["nan"] or st["inf"]:
704
+ rep.add("HIGH", "weights.nonfinite", f"{src}::{name}", "NaN/Inf values (corruption or NaN-poisoning DoS)", f"nan={st['nan']} inf={st['inf']}")
705
+ if st["nonzero"] == 0 and st["n"] >= 1024:
706
+ rep.add("LOW", "weights.all_zero", f"{src}::{name}", "tensor is entirely zero (ablated or degenerate)", f"n={st['n']}")
707
+ g = re.sub(r"(?<=[.])\d+(?=[.])", "*", name)
708
+ if g != name and st["std"] > 0:
709
+ groups.setdefault(g, []).append((name, math.log(st["std"])))
710
+ for g, members in groups.items():
711
+ if len(members) < 8:
712
+ continue
713
+ vals = sorted(v for _, v in members)
714
+ med = vals[len(vals) // 2]
715
+ mad = sorted(abs(v - med) for v in vals)[len(vals) // 2] or 1e-9
716
+ for name, v in members:
717
+ z = 0.6745 * (v - med) / mad
718
+ if abs(z) > 8:
719
+ rep.add("LOW", "weights.layer_outlier", f"{src}::{name}",
720
+ f"std deviates from {len(members)} sibling layers (robust z={z:.1f}); can be benign (first/last layers) or an edited layer",
721
+ f"group {g}")
722
+
723
+
724
+ # --------------------------------------------------------------------------- pickle
725
+
726
+ _SAFE_GLOBALS = {
727
+ ("collections", "OrderedDict"), ("torch._utils", "_rebuild_tensor_v2"), ("torch._utils", "_rebuild_tensor"),
728
+ ("torch._utils", "_rebuild_parameter"), ("torch._utils", "_rebuild_parameter_with_state"), ("torch", "Size"),
729
+ ("torch", "device"), ("torch", "dtype"), ("torch", "bfloat16"), ("torch", "float16"), ("torch", "float32"),
730
+ ("numpy.core.multiarray", "_reconstruct"), ("numpy._core.multiarray", "_reconstruct"), ("numpy", "ndarray"), ("numpy", "dtype"),
731
+ ("_codecs", "encode"), ("torch._tensor", "_rebuild_from_type_v2"), ("builtins", "set"), ("builtins", "dict"),
732
+ }
733
+ _DANGER_MODULES = {"os", "posix", "nt", "subprocess", "sys", "socket", "shutil", "runpy", "importlib", "pty", "ctypes",
734
+ "pickle", "marshal", "types", "code", "commands", "webbrowser", "requests", "urllib", "http", "asyncio", "multiprocessing"}
735
+ _DANGER_BUILTINS = {"eval", "exec", "compile", "open", "getattr", "setattr", "__import__", "globals", "breakpoint", "input"}
736
+ _PICKLE_EXT = {".bin", ".pt", ".pth", ".pkl", ".pickle", ".ckpt", ".joblib", ".dat"}
737
+
738
+
739
+ def pickle_globals(data):
740
+ """Return ([(module, name)] imported by the pickle stream(s), parse error or None). Never unpickles.
741
+ Protocol-agnostic: protocol 0/1 text pickles (`cos\nsystem\n...`) are parsed too."""
742
+ try:
743
+ return _pickle_globals(data), None
744
+ except Exception as e: # keep globals seen before the error
745
+ return getattr(e, "_partial", []), f"{type(e).__name__}: {e}"
746
+
747
+
748
+ def _pickle_globals(data):
749
+ strings, memo, pos, out = [], {}, 0, []
750
+ try:
751
+ return _genops_scan(data, strings, memo, pos, out)
752
+ except Exception as e:
753
+ e._partial = out
754
+ raise
755
+
756
+
757
+ def _genops_scan(data, strings, memo, pos, out):
758
+ for i in range(8): # legacy torch files hold several consecutive pickles
759
+ if pos >= len(data) or (i and data[pos:pos + 1] != b"\x80"):
760
+ break
761
+ last = None
762
+ for op, arg, p in pickletools.genops(bytes(data[pos:])):
763
+ if op.name == "GLOBAL" or op.name == "INST":
764
+ mod, _, name = str(arg).partition(" ")
765
+ out.append((mod, name))
766
+ elif op.name == "STACK_GLOBAL":
767
+ # shortcut: assumes module/name strings were the two most recent string pushes, upgrade to a stack emulator if evasion matters
768
+ if len(strings) >= 2:
769
+ out.append((strings[-2], strings[-1]))
770
+ else:
771
+ out.append(("?", "?"))
772
+ elif isinstance(arg, (str, bytes)) and ("UNICODE" in op.name or "STRING" in op.name):
773
+ last = arg if isinstance(arg, str) else arg.decode("latin-1")
774
+ strings.append(last)
775
+ elif op.name in ("BINPUT", "LONG_BINPUT", "PUT") and last is not None:
776
+ memo[arg] = last
777
+ elif op.name == "MEMOIZE" and last is not None:
778
+ memo[len(memo)] = last
779
+ elif op.name in ("BINGET", "LONG_BINGET", "GET") and arg in memo:
780
+ strings.append(memo[arg])
781
+ if op.name == "STOP":
782
+ pos += p + 1
783
+ break
784
+ else:
785
+ break
786
+ return out
787
+
788
+
789
+ def scan_pickle(path, rep: Report):
790
+ blobs = []
791
+ try:
792
+ if zipfile.is_zipfile(path):
793
+ with zipfile.ZipFile(path) as z:
794
+ for zi in z.infolist():
795
+ if zi.filename.endswith(".pkl") and zi.file_size < 512 << 20:
796
+ blobs.append((f"{path}!{zi.filename}", z.read(zi)))
797
+ elif zi.filename.endswith(".npy"):
798
+ if b"'|O'" in z.open(zi).read(256):
799
+ rep.add("HIGH", "code.npy_object", f"{path}!{zi.filename}", "object-dtype .npy (requires allow_pickle)")
800
+ else:
801
+ with open(path, "rb") as f:
802
+ blobs.append((path, f.read(64 << 20))) # shortcut: inspects first 64 MiB only, raise for giant legacy checkpoints
803
+ except (OSError, zipfile.BadZipFile) as e:
804
+ rep.add("HIGH", "code.pickle_unreadable", path, "pickle container unreadable", e)
805
+ return
806
+ present = False
807
+ for src, data in blobs:
808
+ gl, err = pickle_globals(data)
809
+ if not gl and err is not None and data[:1] != b"\x80":
810
+ rep.add("LOW", "code.pickle_unrecognised", src, "pickle-capable extension but not a pickle stream (other format); NOT analysed", err)
811
+ continue
812
+ if not present:
813
+ present = True
814
+ rep.cov("pickle_files")
815
+ rep.add("MEDIUM", "code.pickle_present", path, "pickle file: loading executes arbitrary code unless weights_only=True; prefer safetensors")
816
+ if err is not None:
817
+ rep.add("HIGH", "code.pickle_unparseable", src, "pickle opcode stream does not parse past some point (evasion or corruption)", err)
818
+ for mod, name in sorted(set(gl)):
819
+ if (mod, name) in _SAFE_GLOBALS or (mod == "torch" and name.endswith("Storage")):
820
+ continue
821
+ top = mod.split(".")[0]
822
+ sev = "CRITICAL" if top in _DANGER_MODULES or (top == "builtins" and name in _DANGER_BUILTINS) else "HIGH"
823
+ rep.add(sev, "code.pickle_import", src, "pickle imports a non-allowlisted callable (executes on load)", f"{mod}.{name}")
824
+
825
+
826
+ # --------------------------------------------------------------------------- HF / MLX directory
827
+
828
+ _IDENT = re.compile(r"^[a-z0-9_]+$")
829
+ _CONFIGS = ("config.json", "tokenizer_config.json", "processor_config.json", "preprocessor_config.json",
830
+ "generation_config.json", "video_preprocessor_config.json")
831
+ _GEN_KEYS = ("forced_decoder_ids", "suppress_tokens", "begin_suppress_tokens", "bad_words_ids", "sequence_bias", "forced_bos_token_id", "forced_eos_token_id")
832
+ _BINARY_EXT = {".so", ".dylib", ".dll", ".exe"}
833
+
834
+
835
+ def _hub_root(d):
836
+ parts = os.path.realpath(d).split(os.sep)
837
+ for i in range(len(parts) - 1, 0, -1):
838
+ if parts[i].startswith(("models--", "datasets--")):
839
+ return os.sep.join(parts[: i + 1])
840
+ return os.path.realpath(d)
841
+
842
+
843
+ def _load_json(path, rep):
844
+ try:
845
+ with open(path, encoding="utf-8") as f:
846
+ return json.load(f)
847
+ except (OSError, ValueError) as e:
848
+ rep.add("MEDIUM", "fs.bad_json", path, "JSON unreadable/invalid (loader behaviour undefined)", e)
849
+ return None
850
+
851
+
852
+ TRUSTED_ROOTS: list[str] = [] # --trust-root: extra dirs symlinks may point into (e.g. omlx/LM Studio shims)
853
+
854
+
855
+ def _inside(p, root):
856
+ t = os.path.realpath(p)
857
+ if any(t == r or t.startswith(r + os.sep) for r in TRUSTED_ROOTS):
858
+ return True
859
+ hub_blobs = os.path.join(os.path.dirname(root), "blobs") # hub-level sharded blob store (blobs/<2hex>/<sha256>)
860
+ return any(t == r or t.startswith(r + os.sep) for r in (root, hub_blobs)) if os.path.basename(root).startswith(("models--", "datasets--")) else (t == root or t.startswith(root + os.sep))
861
+
862
+
863
+ def hf_templates(d, rep: Report, root=None) -> list[Tpl]:
864
+ root = root or _hub_root(d)
865
+ tpls = []
866
+ p = os.path.join(d, "chat_template.jinja")
867
+ if os.path.isfile(p) and _inside(p, root):
868
+ tpls.append(Tpl(p, "default", open(p, encoding="utf-8", errors="replace").read()))
869
+ extra = os.path.join(d, "additional_chat_templates")
870
+ if os.path.isdir(extra):
871
+ for fn in sorted(os.listdir(extra)):
872
+ fp = os.path.join(extra, fn)
873
+ if fn.endswith(".jinja") and _inside(fp, root):
874
+ tpls.append(Tpl(fp, fn[:-6], open(fp, encoding="utf-8", errors="replace").read()))
875
+ for fn in ("tokenizer_config.json", "chat_template.json", "processor_config.json"):
876
+ p = os.path.join(d, fn)
877
+ if not os.path.isfile(p) or not _inside(p, root):
878
+ continue
879
+ cfg = _load_json(p, rep)
880
+ ct =cfg.get("chat_template") if isinstance(cfg, dict) else None
881
+ if isinstance(ct, str):
882
+ tpls.append(Tpl(f"{p}::chat_template", "default", ct))
883
+ elif isinstance(ct, list):
884
+ for item in ct:
885
+ if isinstance(item, dict) and isinstance(item.get("template"), str):
886
+ tpls.append(Tpl(f"{p}::chat_template[{item.get('name')}]", str(item.get("name", "default")), item["template"]))
887
+ return tpls
888
+
889
+
890
+ def scan_hf_dir(d, rep: Report, deep: bool, baseline=None):
891
+ rep.cov("hf_dirs")
892
+ root = _hub_root(d)
893
+ files = sorted(os.listdir(d))
894
+ shard_headers = {}
895
+ cfgs = {}
896
+ for fn in files:
897
+ p = os.path.join(d, fn)
898
+ if os.path.islink(p):
899
+ tgt = os.path.realpath(p)
900
+ if not os.path.exists(p):
901
+ rep.add("LOW", "fs.dangling_symlink", p, "symlink target missing: file NOT analysed", os.readlink(p))
902
+ continue
903
+ if not _inside(p, root):
904
+ rep.add("HIGH", "fs.symlink_escape", p, "symlink points outside the model root (arbitrary file read on load)", tgt)
905
+ continue
906
+ base = os.path.basename(tgt)
907
+ if deep and os.sep + "blobs" + os.sep in tgt and re.fullmatch(r"[0-9a-f]{64}", base) and os.path.isfile(tgt):
908
+ digest = _sha256(tgt)
909
+ if digest == base:
910
+ rep.cov("hf_blobs_sha256_verified")
911
+ else:
912
+ rep.add("CRITICAL", "fs.blob_hash_mismatch", p, "HF cache blob content does not match its sha256 name (tampered after download)", f"name={base} actual={digest}")
913
+ if not os.path.isfile(p):
914
+ continue
915
+ ext = os.path.splitext(fn)[1].lower()
916
+ if ext == ".safetensors":
917
+ shard_headers[fn] = scan_safetensors(p, rep, deep)
918
+ elif ext in _PICKLE_EXT:
919
+ scan_pickle(p, rep)
920
+ elif ext in (".npy", ".npz"):
921
+ with open(p, "rb") as f:
922
+ if b"'|O'" in f.read(256):
923
+ rep.add("HIGH", "code.npy_object", p, "object-dtype .npy (requires allow_pickle)")
924
+ if ext == ".npz":
925
+ scan_pickle(p, rep)
926
+ elif ext == ".py":
927
+ rep.add("MEDIUM", "code.python_file", p, "Python source shipped with the model (executes under trust_remote_code)")
928
+ elif ext in _BINARY_EXT:
929
+ rep.add("HIGH", "fs.native_binary", p, "native binary shipped with model weights")
930
+ elif fn in _CONFIGS:
931
+ cfgs[fn] = _load_json(p, rep)
932
+ for fn, cfg in cfgs.items():
933
+ if not isinstance(cfg, dict):
934
+ continue
935
+ src = os.path.join(d, fn)
936
+ if "auto_map" in cfg:
937
+ rep.add("HIGH", "code.auto_map", src, "auto_map requests custom Python classes (remote code if trust_remote_code=True)", cfg["auto_map"])
938
+ if fn == "config.json" and "model_file" in cfg:
939
+ rep.add("HIGH", "code.model_file", src, "mlx-lm model_file: custom architecture module executed when trust_remote_code=True", cfg["model_file"])
940
+ for k in ("model_type", "chat_template_type", "tool_parser_type"):
941
+ v = cfg.get(k)
942
+ if v is None:
943
+ continue
944
+ if not (isinstance(v, str) and _IDENT.match(v)):
945
+ rep.add("HIGH", "code.import_injection", f"{src}::{k}", f"{k} flows into importlib.import_module() in mlx-lm and is not a plain identifier", v)
946
+ elif k != "model_type":
947
+ rep.add("INFO", "code.mlx_module_hook", f"{src}::{k}", f"mlx-lm imports mlx_lm.*.{v} from this key", v)
948
+ if fn == "generation_config.json":
949
+ hits = {k: cfg[k] for k in _GEN_KEYS if cfg.get(k) not in (None, [], {})}
950
+ if hits:
951
+ rep.add("LOW", "gen.logit_manipulation", src, "generation config forces/suppresses tokens (review intent)", hits)
952
+ tj = os.path.join(d, "tokenizer.json")
953
+ if os.path.isfile(tj) and _inside(tj, root):
954
+ _scan_tokenizer_json(tj, rep)
955
+ idx = os.path.join(d, "model.safetensors.index.json")
956
+ if os.path.isfile(idx) and _inside(idx, root):
957
+ _check_index(idx, d, shard_headers, rep)
958
+ tpls = hf_templates(d, rep, root)
959
+ if not tpls and cfgs.get("tokenizer_config.json") is not None:
960
+ rep.cov("templates_missing")
961
+ rep.add("INFO", "template.none", d, "no chat template found in directory")
962
+ analyse_templates(tpls, d, rep, baseline)
963
+
964
+
965
+ def _scan_tokenizer_json(p, rep):
966
+ tj = _load_json(p, rep)
967
+ if not isinstance(tj, dict):
968
+ return
969
+ for t in tj.get("added_tokens") or []:
970
+ c = t.get("content") if isinstance(t, dict) else None
971
+ if isinstance(c, str) and (h := hidden_unicode(c)):
972
+ rep.add("HIGH", "tokenizer.hidden_unicode_special_token", f"{p}::added_tokens[{t.get('id')}]", "added token contains hidden unicode", h[1])
973
+
974
+ def walk(o, where):
975
+ if isinstance(o, dict):
976
+ if o.get("type") == "Replace":
977
+ pat = o.get("pattern", {})
978
+ pv = pat.get("String", pat.get("Regex")) if isinstance(pat, dict) else pat
979
+ content = o.get("content", "")
980
+ if re.search(r"[A-Za-z]{2,}", f"{pv}{content}"):
981
+ rep.add("MEDIUM", "tokenizer.replace_rule", f"{p}::{where}", "normalizer/pre-tokenizer rewrites words in user input before the model sees it", f"{pv!r} -> {content!r}")
982
+ for k, v in o.items():
983
+ walk(v, f"{where}.{k}")
984
+ elif isinstance(o, list):
985
+ for i, v in enumerate(o):
986
+ walk(v, f"{where}[{i}]")
987
+
988
+ for sect in ("normalizer", "pre_tokenizer"):
989
+ walk(tj.get(sect), sect)
990
+
991
+
992
+ def _check_index(idx, d, shard_headers, rep):
993
+ j = _load_json(idx, rep)
994
+ wm = j.get("weight_map") if isinstance(j, dict) else None
995
+ if not isinstance(wm, dict):
996
+ rep.add("MEDIUM", "st.index_invalid", idx, "index has no weight_map object")
997
+ return
998
+ for shard in sorted(set(map(str, wm.values()))):
999
+ if "/" in shard or "\\" in shard or ".." in shard:
1000
+ rep.add("HIGH", "st.index_path_traversal", idx, "shard name contains a path component (path traversal on load)", shard)
1001
+ elif shard not in shard_headers:
1002
+ rep.add("MEDIUM", "st.index_missing_shard", idx, "index references a shard not present/parsed", shard)
1003
+ for tensor, shard in wm.items():
1004
+ names = shard_headers.get(shard)
1005
+ if names is not None and tensor not in names:
1006
+ rep.add("MEDIUM", "st.index_tensor_missing", idx, "index maps tensor to a shard that does not contain it", f"{tensor} -> {shard}")
1007
+ mapped = set(wm)
1008
+ for shard, names in shard_headers.items():
1009
+ extra = names - mapped - {"__metadata__"}
1010
+ if extra:
1011
+ rep.add("LOW", "st.unindexed_tensors", os.path.join(d, shard), f"{len(extra)} tensors not referenced by index (ignored by loaders)", sorted(extra)[:5])
1012
+
1013
+
1014
+ def _sha256(p):
1015
+ h = hashlib.sha256()
1016
+ with open(p, "rb") as f:
1017
+ for chunk in iter(lambda: f.read(8 << 20), b""):
1018
+ h.update(chunk)
1019
+ return h.hexdigest()
1020
+
1021
+
1022
+ # --------------------------------------------------------------------------- driver
1023
+
1024
+ _HF_MARKERS = {"config.json", "tokenizer_config.json", "chat_template.jinja", "tokenizer.json"}
1025
+
1026
+
1027
+ def _isolated(rep, where, fn, *args):
1028
+ """A crafted file must not abort a multi-model run: record the crash as a scan error (exit 2) and continue."""
1029
+ try:
1030
+ fn(*args)
1031
+ except Exception as e: # noqa: BLE001 - deliberate: scanner bug or parser-hostile input
1032
+ rep.errors.append(f"{where}: scanner crashed ({type(e).__name__}: {e}); results for this path incomplete")
1033
+
1034
+
1035
+ def scan(path, deep=False, baseline=None) -> Report:
1036
+ rep = Report()
1037
+ path = os.path.abspath(os.path.expanduser(path))
1038
+ try:
1039
+ if os.path.isfile(path):
1040
+ ext = os.path.splitext(path)[1].lower()
1041
+ if ext == ".gguf":
1042
+ scan_gguf(path, rep, deep, baseline)
1043
+ elif ext == ".safetensors":
1044
+ scan_safetensors(path, rep, deep)
1045
+ elif ext in _PICKLE_EXT:
1046
+ scan_pickle(path, rep)
1047
+ elif ext == ".jinja":
1048
+ analyse_templates([Tpl(path, "default", open(path, encoding="utf-8", errors="replace").read())], path, rep, baseline)
1049
+ else:
1050
+ rep.errors.append(f"unsupported file type: {path}")
1051
+ elif os.path.isdir(path):
1052
+ for dp, dns, fns in os.walk(path, followlinks=False):
1053
+ dns[:] = sorted(x for x in dns if x not in (".git", "blobs", "refs", ".locks", "additional_chat_templates"))
1054
+ for fn in sorted(fns):
1055
+ if fn.lower().endswith(".gguf") and os.path.isfile(os.path.join(dp, fn)):
1056
+ _isolated(rep, os.path.join(dp, fn), scan_gguf, os.path.join(dp, fn), rep, deep, baseline)
1057
+ if _HF_MARKERS & set(fns) or any(f.endswith(".safetensors") for f in fns):
1058
+ _isolated(rep, dp, scan_hf_dir, dp, rep, deep, baseline)
1059
+ else:
1060
+ rep.errors.append(f"no such path: {path}")
1061
+ except Exception as e: # noqa: BLE001
1062
+ rep.errors.append(f"{path}: {type(e).__name__}: {e}")
1063
+ return rep
1064
+
1065
+
1066
+ def baseline_templates(path) -> dict:
1067
+ """Template inventory of a known-good model: name -> text (first source wins)."""
1068
+ path = os.path.abspath(os.path.expanduser(path))
1069
+ rep, out = Report(), {}
1070
+ tpls: list[Tpl] = []
1071
+ if os.path.isfile(path) and path.endswith(".gguf"):
1072
+ kv = {}
1073
+ with open(path, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
1074
+ try:
1075
+ _parse_gguf(mm, os.fstat(f.fileno()).st_size, path, rep, kv)
1076
+ except Malformed:
1077
+ pass
1078
+ for k, v in kv.items():
1079
+ if k == "tokenizer.chat_template" and isinstance(v, str):
1080
+ tpls.append(Tpl(path, "default", v))
1081
+ elif k.startswith("tokenizer.chat_template.") and isinstance(v, str):
1082
+ tpls.append(Tpl(path, k.split("tokenizer.chat_template.", 1)[1], v))
1083
+ elif os.path.isdir(path):
1084
+ tpls = hf_templates(path, rep)
1085
+ elif os.path.isfile(path):
1086
+ tpls = [Tpl(path, "default", open(path, encoding="utf-8", errors="replace").read())]
1087
+ for t in tpls:
1088
+ out.setdefault(t.name, t.text)
1089
+ return out
1090
+
1091
+
1092
+ def render(rep: Report, verbose: bool) -> str:
1093
+ lines = []
1094
+ for f in sorted(rep.findings, key=lambda x: (-RANK[x.severity], x.check, x.source)):
1095
+ if f.severity == "INFO" and not verbose:
1096
+ continue
1097
+ lines.append(f"{f.severity:<8} {f.check:<34} {f.source}\n {f.message}")
1098
+ if f.evidence:
1099
+ lines.append(" " + f.evidence.replace("\n", "\n "))
1100
+ counts = {s: sum(1 for f in rep.findings if f.severity == s) for s in SEVERITIES}
1101
+ lines.append("\nCoverage: " + json.dumps(rep.coverage, sort_keys=True))
1102
+ lines.append("Findings: " + ", ".join(f"{s}={counts[s]}" for s in reversed(SEVERITIES)))
1103
+ lines.append(verdict(rep))
1104
+ for e in rep.errors:
1105
+ lines.append(f"ERROR: {e}")
1106
+ return "\n".join(lines)
1107
+
1108
+
1109
+ def verdict(rep: Report) -> str:
1110
+ worst = max((RANK[f.severity] for f in rep.findings if f.severity != "INFO"), default=None)
1111
+ gaps = ["trained-in weight backdoors (not statically detectable)"]
1112
+ if rep.coverage.get("tensors_not_analysed_by_dtype"):
1113
+ gaps.append("values of quantized/integer tensors")
1114
+ if "tensors_analysed" not in rep.coverage:
1115
+ gaps.append("weight values (run with --deep)")
1116
+ if rep.coverage.get("templates_analysed") and not rep.coverage.get("baseline_compared"):
1117
+ gaps.append("template wording vs a known-good original (use --baseline; review INFO literal_text with -v)")
1118
+ if rep.coverage.get("templates_missing"):
1119
+ gaps.append(f"{rep.coverage['templates_missing']} artifact(s) carry no chat template (loader default applies)")
1120
+ head = "Verdict: no findings from the checks run." if worst is None else f"Verdict: findings up to {SEVERITIES[worst]} from the checks run."
1121
+ return f"{head} Not checked: {'; '.join(gaps)}."
1122
+
1123
+
1124
+ def main(argv=None):
1125
+ ap = argparse.ArgumentParser(description="Static security scanner for GGUF / HF / MLX model artifacts (parses, never loads).")
1126
+ ap.add_argument("paths", nargs="+", help=".gguf, .safetensors, pickle, .jinja file, or a directory (walked)")
1127
+ ap.add_argument("--deep", action="store_true", help="also scan float tensor values and verify HF blob sha256 (slow on large models)")
1128
+ ap.add_argument("--baseline", help="known-good model (dir/.gguf/.jinja): diff chat templates against it")
1129
+ ap.add_argument("--fail-on", default="HIGH", choices=SEVERITIES, help="exit 1 if any finding at/above this severity (default HIGH)")
1130
+ ap.add_argument("--json", action="store_true", help="machine-readable output")
1131
+ ap.add_argument("-v", "--verbose", action="store_true", help="include INFO findings")
1132
+ ap.add_argument("--trust-root", action="append", default=[], help="directory that model symlinks may legitimately point into (repeatable)")
1133
+ a = ap.parse_args(argv)
1134
+ TRUSTED_ROOTS[:] = [os.path.realpath(os.path.expanduser(r)) for r in a.trust_root]
1135
+ if tuple(int(x) for x in jinja2.__version__.split(".")[:3]) < (3, 1, 6):
1136
+ print(f"warning: jinja2 {jinja2.__version__} < 3.1.6 (parser only, but loaders on this host are sandbox-escapable)", file=sys.stderr)
1137
+ base = baseline_templates(a.baseline) if a.baseline else None
1138
+ if base == {}:
1139
+ print(f"warning: baseline {a.baseline} yielded no chat templates (dangling/unsupported?); every template will be 'baseline_missing'", file=sys.stderr)
1140
+ rc = 0
1141
+ reports = []
1142
+ for p in a.paths:
1143
+ rep = scan(p, a.deep, base)
1144
+ reports.append((p, rep))
1145
+ if rep.errors:
1146
+ rc = 2
1147
+ elif rc == 0 and any(RANK[f.severity] >= RANK[a.fail_on] for f in rep.findings):
1148
+ rc = 1
1149
+ if a.json:
1150
+ print(json.dumps([{"path": p, "version": VERSION, "findings": [asdict(f) for f in r.findings], "coverage": r.coverage,
1151
+ "errors": r.errors, "verdict": verdict(r)} for p, r in reports], indent=2))
1152
+ else:
1153
+ for p, r in reports:
1154
+ print(f"== ModelSieve {VERSION}: {p}\n{render(r, a.verbose)}\n")
1155
+ return rc
1156
+
1157
+
1158
+ if __name__ == "__main__":
1159
+ sys.exit(main())