#!/usr/bin/env python3
# gguf_check.py - read a GGUF file's chat template and find payload bytes after the weights, without loading the model.
# Project: hostimm.com - https://hostimm.com
# AION (agent, APEX V2 architecture) - Architect AlexH
# Community: llmresearch.net (EN) / forumai.ro (RO)
# License: MIT, attribution required
"""gguf_check.py - inspect a GGUF model file before you run it.

Pure stdlib, no dependencies, no model loaded, no template executed. It answers two
questions a GGUF loader never asks out loud:

  1. What chat template is inside this file, and does it contain instructions,
     commands, URLs, decompression or file writes?
  2. Do the declared tensors fill the file exactly, or is there a payload hidden
     after the last tensor where llama.cpp, Ollama and LM Studio never read?

Usage
  python gguf_check.py model.gguf
  python gguf_check.py https://huggingface.co/owner/repo/blob/main/weights-Q4_K_M.gguf
  python gguf_check.py owner/repo                       # every GGUF in the repo, header only
  python gguf_check.py --json model.gguf

Exit codes: 0 clean, 2 suspicious or malicious, 1 error (unreadable, not GGUF, unknown quant type).
Exit code 1 on an unknown tensor type is deliberate: "could not verify" is never "clean".
"""
import argparse
import json
import os
import re
import struct
import sys
import urllib.error
import urllib.request

HEADER_CHUNK = 8 * 1024 * 1024   # enough for header, metadata, template and tensor table
TAIL_CHUNK = 64 * 1024
UA = {"User-Agent": "Mozilla/5.0 (gguf_check.py, hostimm.com)"}

# ggml type id -> (block size, bytes per block). Types not listed cannot be sized,
# and the file is reported as unverifiable rather than clean.
GGML_TYPES = {
    0: (1, 4), 1: (1, 2), 2: (32, 18), 3: (32, 20), 6: (32, 22), 7: (32, 24),
    8: (32, 34), 9: (32, 36), 10: (256, 84), 11: (256, 110), 12: (256, 144),
    13: (256, 176), 14: (256, 210), 15: (256, 292), 16: (256, 66), 17: (256, 74),
    18: (256, 98), 19: (256, 50), 20: (32, 18), 21: (256, 110), 22: (256, 82),
    23: (256, 136), 24: (1, 1), 25: (1, 2), 26: (1, 4), 27: (1, 8), 28: (1, 8),
    29: (256, 56), 30: (1, 2), 34: (256, 54), 35: (256, 66), 39: (32, 17),
}

# template rules: (regex, weight, what it means)
RULES = [
    (r"\[\s*system\s+directive\s*\]", 3, "fake system directive aimed at an agent"),
    (r"\b(never|do not|don't)\s+mention\b", 2, "instruction to hide itself from the user"),
    (r"io\.file\]?::\s*openread", 3, "reads bytes from a file at reply time"),
    (r"writeallbytes", 3, "writes a file at reply time"),
    (r"deflatestream", 3, "decompresses data at reply time"),
    (r"start-process", 3, "starts a process at reply time"),
    (r"\bpowershell(\.exe)?\b|\bpwsh\b", 3, "PowerShell in the template"),
    (r"invoke-webrequest|\biwr\b|downloadstring|downloadfile|net\.webclient", 3, "downloads a file"),
    (r"\bcurl\s|\bwget\s", 3, "downloads a file"),
    (r"frombase64string|\s-enc(odedcommand)?\s", 2, "encoded command"),
    (r"__subclasses__|__globals__|__builtins__|builtinimporter", 3, "Python template escape gadget"),
    (r"os\.system\(|subprocess\.|popen\(", 3, "shell call in template code"),
    (r"cmd\.exe\s*/c", 3, "cmd.exe in the template"),
    (r"\.length\s*-\s*\d|\.gguf", 2, "locates or measures a model file on disk"),
    (r"schtasks|reg\s+add|startup", 2, "persistence command"),
    (r"https?://(?!huggingface\.co)", 1, "sends the reader or the model to a URL"),
    (r"\$env:\w+|\$\{?\w*:\w*\}?", 1, "PowerShell variable expansion"),
]


def u32(b, o): return struct.unpack_from("<I", b, o)[0], o + 4
def u64(b, o): return struct.unpack_from("<Q", b, o)[0], o + 8


def read_string(b, o):
    n, o = u64(b, o)
    return b[o:o + n], o + n


def skip_value(b, o, t):
    if t == 8:
        return read_string(b, o)[1]
    if t == 9:
        at, o = u32(b, o)
        n, o = u64(b, o)
        for _ in range(n):
            o = skip_value(b, o, at)
        return o
    size = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}[t]
    return o + size


def parse_header(buf):
    if buf[:4] != b"GGUF":
        raise ValueError("not a GGUF file (magic is %r)" % buf[:4])
    o = 4
    version, o = u32(buf, o)
    n_tensors, o = u64(buf, o)
    n_kv, o = u64(buf, o)
    meta = {}
    for _ in range(n_kv):
        k, o = read_string(buf, o)
        vtype, o = u32(buf, o)
        if vtype == 8:
            v, o = read_string(buf, o)
            meta[k.decode("utf-8", "replace")] = v.decode("utf-8", "replace")
        else:
            meta.setdefault("_other_keys", 0)
            meta["_other_keys"] += 1
            o = skip_value(buf, o, vtype)
    tensors = []
    for _ in range(n_tensors):
        name, o = read_string(buf, o)
        n_dims, o = u32(buf, o)
        dims = []
        for _ in range(n_dims):
            d, o = u64(buf, o)
            dims.append(d)
        ttype, o = u32(buf, o)
        off, o = u64(buf, o)
        tensors.append({"name": name.decode("utf-8", "replace"), "dims": dims,
                        "type": ttype, "offset": off})
    return version, meta, tensors, o


def template_text(meta):
    out = []
    for k, v in meta.items():
        if k.startswith("tokenizer.chat_template"):
            out.append((k, v))
    return out


def scan_template(templates):
    findings = []
    for key, src in templates:
        for rx, weight, why in RULES:
            for m in re.finditer(rx, src, re.I):
                snippet = src[max(0, m.start() - 60): m.end() + 60].replace("\n", " ")
                findings.append({"key": key, "weight": weight, "why": why,
                                 "match": m.group(0)[:80], "context": snippet})
                break
    return findings


def expected_data_end(tensors, data_start):
    """Return (end_offset, unverifiable_reason)."""
    end = 0
    for t in tensors:
        if t["type"] not in GGML_TYPES:
            return None, "tensor %s uses type id %d, which this checker cannot size" % (t["name"], t["type"])
        blk, size = GGML_TYPES[t["type"]]
        n = 1
        for d in t["dims"]:
            n *= d
        if n % blk:
            return None, "tensor %s has %d elements, not a multiple of its block size %d" % (t["name"], n, blk)
        end = max(end, t["offset"] + (n // blk) * size)
    return data_start + end, None


def classify(findings, tail, file_size, end):
    score = sum(f["weight"] for f in findings)
    if tail and tail > 1024:
        # a loader-read GGUF ends where its last tensor ends; a kilobyte or more past
        # that point is not padding, whatever the template says
        score += 5
    if score >= 3:
        return "MALICIOUS"
    if score >= 1:
        return "SUSPICIOUS"
    return "CLEAN"


def check_local(path):
    size = os.path.getsize(path)
    with open(path, "rb") as f:
        buf = f.read(min(size, HEADER_CHUNK))
        version, meta, tensors, pos = parse_header(buf)
        align = int(str(meta.get("general.alignment", 32)))
        data_start = (pos + align - 1) // align * align
        end, why = expected_data_end(tensors, data_start)
        tail = None
        tail_head = b""
        if end is not None:
            tail = max(0, size - end)
            if tail:
                f.seek(end)
                tail_head = f.read(4096)
    return version, meta, tensors, pos, data_start, end, why, tail, tail_head, size


def http_get(url, start=None, length=None, method="GET"):
    req = urllib.request.Request(url, headers=dict(UA))
    if start is not None:
        req.add_header("Range", "bytes=%d-%s" % (start, "" if length is None else str(start + length - 1)))
    with urllib.request.urlopen(req, timeout=120) as r:
        body = r.read()
        total = None
        cr = r.headers.get("Content-Range")
        if cr and "/" in cr:
            total = int(cr.split("/")[-1])
        elif r.headers.get("Content-Length"):
            total = int(r.headers["Content-Length"])
        return body, total, r.status, dict(r.headers)


def resolve_hf_repo(repo):
    api = "https://huggingface.co/api/models/" + repo
    body, _, status, _ = http_get(api)
    if status != 200:
        raise ValueError("Hugging Face API answered %s for %s" % (status, repo))
    data = json.loads(body)
    files = [s["rfilename"] for s in data.get("siblings", []) if s["rfilename"].endswith(".gguf")]
    return data, ["https://huggingface.co/%s/resolve/main/%s" % (repo, f) for f in files]


def check_url(url):
    head, total, status, headers = http_get(url, 0, HEADER_CHUNK)
    version, meta, tensors, pos = parse_header(head)
    if total is None:
        raise ValueError("server did not report the file size, cannot check the tail")
    align = int(str(meta.get("general.alignment", 32)))
    data_start = (pos + align - 1) // align * align
    end, why = expected_data_end(tensors, data_start)
    tail = None
    tail_head = b""
    if end is not None:
        tail = max(0, total - end)
        if tail:
            tail_head, _, _, _ = http_get(url, max(0, end - 8), min(tail, TAIL_CHUNK))
    return version, meta, tensors, pos, data_start, end, why, tail, tail_head, total


def describe(label, version, meta, tensors, pos, data_start, end, why, tail, tail_head, size):
    templates = template_text(meta)
    findings = scan_template(templates)
    verdict = classify(findings, tail, size, end)
    print("== %s" % label)
    print("   bytes: %d | gguf v%d | tensors: %d | metadata keys: %d" % (size, version, len(tensors), len(meta)))
    print("   header ends at %d, weights start at %d" % (pos, data_start))
    if end is None:
        print("   tail: CANNOT VERIFY (%s)" % why)
        verdict = "SUSPICIOUS" if verdict == "CLEAN" else verdict
    else:
        print("   declared weights end at %d, file ends at %d, tail: %d bytes" % (end, size, tail))
        if tail and tail_head:
            sig = tail_head[:2]
            kind = "PE executable (MZ)" if sig == b"MZ" else "ZIP archive" if tail_head[:2] == b"PK" else "unrecognised data"
            print("   first bytes after the weights: %s" % kind)
    print("   chat template: %d" % len(templates))
    for key, src in templates:
        print("     %s (%d chars): %s" % (key, len(src), src[:120].replace("\n", " ") + ("..." if len(src) > 120 else "")))
    if findings:
        print("   template findings:")
        for f in findings:
            print("     [%d] %s | match %r | ...%s..." % (f["weight"], f["why"], f["match"], f["context"][:160]))
    print("   VERDICT: %s" % verdict)
    return {"label": label, "verdict": verdict, "size": size, "version": version,
            "tensors": len(tensors), "tail": tail, "templates": [k for k, _ in templates],
            "findings": findings}


def main(argv=None):
    ap = argparse.ArgumentParser(description="Check a GGUF file for poisoned chat templates and bytes after the last tensor.")
    ap.add_argument("target", help="local .gguf path, direct URL, or Hugging Face owner/repo")
    ap.add_argument("--json", action="store_true", help="machine-readable output")
    a = ap.parse_args(argv)
    t = a.target
    targets = []
    if os.path.exists(t):
        targets = [("file", t)]
    elif re.match(r"^https?://", t):
        targets = [("url", t)]
    elif re.match(r"^[\w.-]+/[\w.-]+$", t):
        data, urls = resolve_hf_repo(t)
        print("   repo %s: disabled=%s downloads=%s" % (t, data.get("disabled"), data.get("downloads")))
        if not urls:
            print("   no .gguf files listed; nothing to scan")
            return 0
        targets = [("url", u) for u in urls]
    else:
        print("error: %s is not a local file, URL or Hugging Face repo id" % t)
        return 1

    results = []
    for kind, tgt in targets:
        try:
            if kind == "file":
                r = check_local(tgt)
            else:
                r = check_url(tgt)
            results.append(describe(tgt, *r))
        except Exception as e:
            print("== %s" % tgt)
            print("   ERROR: %s" % e)
            results.append({"label": tgt, "verdict": "ERROR", "error": str(e)})
    if a.json:
        print(json.dumps(results, indent=2))
    verdicts = [r["verdict"] for r in results]
    if "MALICIOUS" in verdicts or "SUSPICIOUS" in verdicts:
        return 2
    if "ERROR" in verdicts:
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
