#!/usr/bin/env python3 """vet_gguf.py: inspect a GGUF file before you run it. Reads metadata only. What it does: * Parses the GGUF header (key/values and tensor descriptors) by reading the file sequentially. It never memory-maps or loads tensor data, and never renders or executes the chat template. * Prints every chat template in the file (tokenizer.chat_template and any named tokenizer.chat_template.) and flags suspicious patterns: URLs, shell or download commands, injected "directive" text, and conditionals on what the user typed. * Computes where tensor data should end and reports any bytes after it. A remote-access payload was hidden there in the Nov 2026 Hugging Face "Mir2k" case. * Prints the file's sha256 (skip with --no-hash) and compares it with --compare-hash. It can also scan a bare template with --template-file (a .jinja file, a tokenizer_config.json, or "-" for stdin). Exit codes: 0 = nothing flagged, 1 = something flagged (template pattern, trailing data, or hash mismatch), 2 = could not parse. This is a tripwire, not a verdict. A clean result does not make a model safe: it cannot see backdoors trained into the weights, and a careful attacker can phrase a template around any word list. Read the template yourself. Requires: pip install gguf (used only for its constants: value types and quant block sizes). """ import argparse import hashlib import json import os import re import struct import sys from gguf.constants import GGML_QUANT_SIZES, GGMLQuantizationType, GGUFValueType GGUF_MAGIC = b"GGUF" DEFAULT_ALIGNMENT = 32 MAX_STRING = 64 * 1024 * 1024 # refuse absurd lengths in a hostile header # (severity, label, regex). HIGH patterns have no business in a chat template. PATTERNS = [ ("HIGH", "URL", r"(?:https?|hxxps?|ftp)://|www\.[a-z0-9-]+\.[a-z]"), ("HIGH", "PowerShell", r"powershell|pwsh|invoke-webrequest|invoke-expression|\biex\b|start-process|-encodedcommand|downloadstring|net\.webclient"), ("HIGH", "download/shell command", r"\bcurl\s|\bwget\s|certutil|bitsadmin|mshta|rundll32|cmd(?:\.exe)?\s*/c|/bin/(?:ba)?sh|bash\s+-c|chmod\s+\+x|\|\s*(?:ba)?sh\b"), ("HIGH", "injected directive", r"system\s+directive|\bmust\s+(?:call|run|execute|use)\b|ignore\s+(?:all\s+)?(?:previous|prior)\s+instructions"), ("HIGH", "Windows executable or temp path", r"\bseek\b|readallbytes|\.exe\b|%temp%|\$env:temp|\\windows\\temp"), ("WARN", "base64-like blob", r"[A-Za-z0-9+/]{120,}={0,2}"), ] # Conditionals that test what a message's text says (not which keys a message has, # like 'tool_calls' in message). Real templates do this for # reasoning and tool markup, so those literals are allowed. CONTENT_TEST = re.compile( r"""\{%-?\s*(?:el)?if\b[^%]*?(?:(['"])(?P[^'"]{1,200})\1\s+(?:not\s+)?in\s+[^%]*?(?:\bcontent\b|\bprompt\b|\bquery\b|\[\s*['"]content['"]\s*\])""" r"""|(?:\bcontent\b|\bprompt\b|\bquery\b|\[\s*['"]content['"]\s*\])[^%]*?\.(?:startswith|endswith|find|count)\s*\(\s*(['"])(?P[^'"]{1,200})\3)""", re.IGNORECASE, ) BENIGN_LITERALS = { "", "", "", "", "", "", "<|im_start|>", "<|im_end|>", "\n", "", "", "[TOOL_CALLS]", "<|channel|>", "<|message|>", "<|end|>", "<|start|>", "<|call|>", "<|return|>", } class Reader: """Sequential little-endian reader that tracks how many bytes it has consumed.""" def __init__(self, f): self.f = f self.pos = 0 def take(self, n): b = self.f.read(n) if len(b) != n: raise ValueError(f"file ends at byte {self.pos + len(b):,} inside the header (wanted {n} more bytes)") self.pos += n return b def u32(self): return struct.unpack(" MAX_STRING: raise ValueError(f"string length {n:,} at byte {self.pos:,} is implausible") return self.take(n).decode("utf-8", "replace") SCALARS = { GGUFValueType.UINT8: "" items = [self.value(itype) for _ in range(count)] return items if keep_arrays else f"" fmt = self.SCALARS[vtype] return struct.unpack(fmt, self.take(struct.calcsize(fmt)))[0] def parse_header(path): with open(path, "rb") as f: r = Reader(f) if r.take(4) != GGUF_MAGIC: raise ValueError("not a GGUF file (bad magic)") version = r.u32() if version not in (2, 3): raise ValueError(f"unsupported GGUF version {version}") n_tensors, n_kv = r.u64(), r.u64() kv = {} for _ in range(n_kv): key = r.string() kv[key] = r.value(r.u32()) tensors = [] for _ in range(n_tensors): name = r.string() n_dims = r.u32() dims = [r.u64() for _ in range(n_dims)] ttype = r.u32() offset = r.u64() tensors.append((name, dims, ttype, offset)) header_end = r.pos return version, kv, tensors, header_end def tensor_nbytes(dims, ttype): n = 1 for d in dims: n *= d block, size = GGML_QUANT_SIZES[GGMLQuantizationType(ttype)] if n % block: raise ValueError(f"tensor with {n} elements is not a multiple of block size {block}") return n // block * size def scan_template(text): """Return a list of (severity, label, excerpt) findings for one template.""" findings = [] for sev, label, rx in PATTERNS: for m in re.finditer(rx, text, re.IGNORECASE): a, b = max(0, m.start() - 40), min(len(text), m.end() + 40) findings.append((sev, label, text[a:b].replace("\n", "\\n"))) break # one excerpt per pattern is enough for m in CONTENT_TEST.finditer(text): lit = m.group("lit") if m.group("lit") is not None else m.group("lit2") if lit in BENIGN_LITERALS: continue findings.append(("HIGH", "conditional on user text", f"tests for {lit!r}: {m.group(0)[:160]!s}".replace("\n", "\\n"))) return findings def defang(s): return re.sub(r"https?://", lambda m: m.group(0).replace("http", "hxxp"), s).replace(".com", "[.]com") def report_templates(templates, show): flagged = False for name, text in templates: print(f"\n== template {name}: {len(text):,} chars, sha256 {hashlib.sha256(text.encode()).hexdigest()}") findings = scan_template(text) if not findings: print(" no patterns flagged") for sev, label, excerpt in findings: flagged = True print(f" [{sev}] {label}: ...{defang(excerpt)}...") if show: print(" ---- template (URLs defanged) ----") print(defang(text)) print(" ---- end template ----") return flagged def sha256_file(path): h = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(8 * 1024 * 1024), b""): h.update(chunk) return h.hexdigest() def load_template_file(path): data = sys.stdin.read() if path == "-" else open(path, encoding="utf-8", errors="replace").read() if path.endswith(".json"): cfg = json.loads(data) tmpl = cfg.get("chat_template") if isinstance(tmpl, list): # [{"name": ..., "template": ...}, ...] return [(f"chat_template[{t.get('name', i)}]", t.get("template", "")) for i, t in enumerate(tmpl)] return [("chat_template", tmpl or "")] return [(os.path.basename(path) if path != "-" else "stdin", data)] def main(): ap = argparse.ArgumentParser(description="Inspect a GGUF's metadata, chat template and trailing bytes without loading it.") ap.add_argument("gguf", nargs="?", help="path to a .gguf file") ap.add_argument("--template-file", help="scan a bare template instead (.jinja, tokenizer_config.json, or - for stdin)") ap.add_argument("--compare-hash", metavar="SHA256", help="expected sha256 from the publisher's file page") ap.add_argument("--no-hash", action="store_true", help="skip hashing the whole file") ap.add_argument("--no-template", action="store_true", help="don't print template text, only findings") args = ap.parse_args() if args.template_file: try: templates = load_template_file(args.template_file) except (OSError, ValueError) as e: print(f"error: {e}", file=sys.stderr) return 2 return 1 if report_templates(templates, not args.no_template) else 0 if not args.gguf: ap.error("give a .gguf path or --template-file") try: version, kv, tensors, header_end = parse_header(args.gguf) except (OSError, ValueError, KeyError) as e: print(f"error: could not parse {args.gguf}: {e}", file=sys.stderr) return 2 flagged = False size = os.path.getsize(args.gguf) print(f"{args.gguf}\n GGUF v{version}, {len(kv)} keys, {len(tensors)} tensors, file {size:,} bytes") for k in ("general.name", "general.architecture", "general.size_label", "general.quantized_by", "general.url", "general.source.url", "general.repo_url"): if k in kv: print(f" {k} = {defang(str(kv[k]))}") alignment = int(kv.get("general.alignment", DEFAULT_ALIGNMENT)) data_start = (header_end + alignment - 1) // alignment * alignment try: data_end = data_start + max((off + tensor_nbytes(d, t) for _, d, t, off in tensors), default=0) except (KeyError, ValueError) as e: print(f" tensor size check skipped: {e}") data_end = None if data_end is not None: extra = size - data_end print(f" tensor data: starts at {data_start:,}, should end at {data_end:,}") if extra < 0: print(f" [HIGH] file is {-extra:,} bytes SHORTER than its tensors need (truncated or corrupt)") flagged = True elif extra == 0: print(" trailing bytes after the last tensor: 0") else: with open(args.gguf, "rb") as f: f.seek(data_end) tail = f.read(min(extra, 64)) if extra < alignment and not tail.strip(b"\x00"): print(f" trailing bytes after the last tensor: {extra:,} zero bytes (alignment padding, normal)") else: preview = "".join(chr(c) if 32 <= c < 127 else "." for c in tail[:32]) print(f" [HIGH] trailing bytes after the last tensor: {extra:,}. Nothing in a normal GGUF lives there." f" First bytes: {preview!r}") flagged = True templates = [(k, v) for k, v in kv.items() if k.startswith("tokenizer.chat_template") and isinstance(v, str)] if not templates: print(" no chat template in the file (your runtime will use its own or a Modelfile's)") flagged |= report_templates(templates, not args.no_template) if not args.no_hash: digest = sha256_file(args.gguf) print(f"\n sha256 {digest}") if args.compare_hash: if digest.lower() == args.compare_hash.strip().lower(): print(" hash matches the expected value") else: print(f" [HIGH] hash does NOT match the expected {args.compare_hash.strip()}") flagged = True elif args.compare_hash: print(" --compare-hash ignored because --no-hash was given") print("\nRESULT:", "FLAGGED, read the findings above before running this file" if flagged else "nothing flagged (not a guarantee; see --help)") return 1 if flagged else 0 if __name__ == "__main__": sys.exit(main())