How to Check a GGUF Model Before You Load It: Hidden Bytes and Poisoned Chat Templates
A GGUF file is not only weights. It also carries a chat template, which is a small program that runs on every prompt. And it can carry bytes that no model loader ever reads. This week, a security research post showed att
A GGUF file is not only weights. It also carries a chat template, which is a small program that runs on every prompt. And it can carry bytes that no model loader ever reads. This week, a security research post showed attackers using both on Hugging Face.
This article explains what was found, where data can hide inside a GGUF file, and how to check a model before you load it. It ends with a small Python script that uses only the standard library. The script reads the file header, prints the chat template, and tells you if the file is bigger than its own tensor table says it should be.
The attack details below come from Malspark's report, published on November 27, 2026. This article does not use the malicious files. The checker was run against two clean public models and against harmless test files built for this article, and its output is shown as it came out.
What the scan found
According to the report, Malspark scanned every public model repository on Hugging Face on November 26: 3,273,389 repositories in total. That included 226,310 GGUF repositories holding 2.56 PB of weights, and 572,184 chat templates parsed without running them. The report says headers and file ends were read with HTTP Range requests, so no model was downloaded in full.
After manual review, five repositories from two accounts were left:
- Mir2k/Huihui-Qwen3.5-9B-abliterated-GGUF: a reply-prefix template plus a hidden Windows program. 1,488 downloads.
- Mir2k/Inkling-2-Mini-Uncensored-GGUF: the same trick, with the hidden program compressed. 458 downloads.
- timdedid/qwen3.8-cyber-uncensored, qwen3-cyber-UNCENSORED-2 and qwen3-cyber-UNCENSORED: a template that hijacks coding agents. 271, 136 and 75 downloads.
That adds up to 2,428 downloads as of November 27. At scan time the day before, the count was 1,502. The report notes that Hugging Face counts downloads, not people, so the number of affected users is lower or equal.
As of November 29, the Hugging Face model API marks all five repositories as "disabled": true.
The story reached the Hacker News front page on November 28, where it had 308 points and 94 comments at the time of writing.
How a GGUF file is laid out
The GGUF specification in the ggml repository describes a simple layout, in this order:
-
Header: the magic bytes
GGUF, a version number (3 for the current spec), the tensor count and the metadata count. -
Metadata: key-value pairs. One of them is
tokenizer.chat_template, a Jinja (a text template language) string. - Tensor table: for each tensor, its name, shape, type and an offset.
-
Padding: zero bytes up to the next multiple of
general.alignment. The spec says to assume 32 if the key is missing. - Tensor data: the weights. Each tensor sits at its offset, counted from the start of this section.
The important detail is that the file itself tells you where the model data ends. Take the start of the tensor data section, add the offset of the farthest tensor, and add that tensor's size in bytes. Every byte after that point is outside the model. A runtime has no reason to read it.
Malspark puts it this way: runtimes such as llama.cpp and LM Studio "read exactly the byte ranges the header points to and ignore everything else."
The two halves of the attack
Half 1: the chat template
The chat template turns a list of messages into the exact text the model reads. The report says C++ runtimes render it in a restricted engine with no Python behind it. So the classic template-injection payloads that reach the operating system do not work there.
The attackers did not need that. They used normal template logic to add text that the user never sees in the chat window:
- In the timdedid models, if the user's latest message contains
What is, the template inserts a fake[SYSTEM DIRECTIVE]. It tells an agent to call itspowershelltool, download a script intoC:\Windows\Temp\payload.ps1and run it in a hidden window. The README advised against replacing the embedded template. The second-stage script was not recovered, so what it would have installed is unknown. - In the Mir2k models, the template adds a French system message telling the model to begin every reply with one PowerShell line, "copied character by character." A user who pastes that line runs the payload.
This half is not GGUF-specific. The report points out that Safetensors and PyTorch models carry the same kind of template in tokenizer_config.json or chat_template.jinja. One HN commenter made the same point: Safetensors would not help with the template part.
Half 2: bytes after the last tensor
This half is specific to GGUF. Mir2k appended a whole Windows program after the last tensor. Loaders never read it, so the model still loads and answers normally.
The first model carried the plain program followed by about half a megabyte of filler. That way, a scanner that only reads the last few kilobytes of a file sees nothing. The second model carried the same program compressed with raw Deflate, which removes every recognizable file signature. The PowerShell line from the template is the link between the two halves. It finds the largest .gguf file in the user's profile, reads its last bytes, writes them to %TEMP%\d.exe and starts it.
The report says Safetensors files cannot do this, because the loader refuses a file whose declared tensors do not fill it exactly.
Plant first, arm later
The timing matters for anyone who downloads models. The report gives this order of events:
- November 22: Mir2k creates 14 repositories. Twelve are empty placeholders named after expected releases, such as Qwen4-27B and DeepSeek-V4. The Huihui model is uploaded with the program already appended, but with a clean template.
- November 24: the Inkling model follows, with the compressed program and again a clean template.
- November 26, morning: both templates are replaced within about an hour. Nine hours later they are replaced again, now searching the whole user profile for the model file.
So a download from before November 26 contained the payload but not the trigger. A template check on November 25 would have passed. This is a strong argument for pinning a model to a specific commit, which comes up again below.
The recovered program, which the report calls "ollie", is an 11.47 MB Windows binary. Most of it, 10.25 MB, is a bundled copy of Tor. The report's static analysis shows it steals saved browser passwords from Chrome, Edge and Brave. It also targets the Phantom and MetaMask wallet extensions, supports keylogging and screenshots, and mines Monero when the machine is idle.
Three more hiding places, shown in the lab only
The report also built synthetic test files for three places the real malware did not use:
-
Alignment padding: raising
general.alignmentfrom 32 to several megabytes creates a large gap that loaders skip. - GGUF plus ZIP: GGUF is read from the start and ZIP from the end, so a ZIP archive appended to a model can still load as a model and also import as Python code.
- Zero-scale blocks: in Q8_0, each block of 32 values has one scale. With a scale of zero, any 32 bytes decode to zero weights, so the block can carry hidden data.
According to the report, none of these changes a dequantized weight, and none triggers a warning in llama.cpp or gguf-py.
Step 1: read the template before you download
You do not need to download a model to read its chat template. The Hugging Face model API returns parsed GGUF metadata, including the template, when you ask for the gguf field. It can also return the current commit hash:
import json
import sys
import urllib.request
repo = sys.argv[1] # for example Qwen/Qwen2.5-0.5B-Instruct-GGUF
url = f"https://huggingface.co/api/models/{repo}?expand[]=gguf&expand[]=sha"
with urllib.request.urlopen(url) as resp:
info = json.load(resp)
print("commit:", info.get("sha"))
print(info.get("gguf", {}).get("chat_template", "(no template in the API metadata)"))
Run against Qwen/Qwen2.5-0.5B-Instruct-GGUF, it printed commit 9217f5db79a29953eb74d5343926648285ec7e67 and a template that starts with {%- if tools %}. For one of the disabled Mir2k repositories, it printed no template at all.
Two limits apply. The API returns a single gguf entry for the whole repository, and a repository can hold several GGUF files. And as the Mir2k timeline shows, the template can change after you look. So once you have read a template you trust, download from that exact commit instead of main:
curl -L -o model.gguf \
"https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/9217f5db79a29953eb74d5343926648285ec7e67/qwen2.5-0.5b-instruct-q4_0.gguf"
A later template change on Hugging Face then cannot reach your copy. Run the checker below on it anyway, since a commit you pinned can still be one that was already armed.
Step 2: check the file you downloaded
The script below reads only the header, the metadata and the tensor table. It never loads the weights and never runs the template. It needs Python 3 and nothing else.
To get each tensor's size, it uses the block sizes from GGML_QUANT_SIZES in llama.cpp's gguf-py constants. For example, a Q4_0 block holds 32 weights in 18 bytes, and a Q4_K block holds 256 weights in 144 bytes.
#!/usr/bin/env python3
"""gguf_check.py: read a GGUF file's header without loading the model."""
import re
import struct
import sys
# (block size, bytes per block) per ggml type id, from gguf-py GGML_QUANT_SIZES
QUANT_SIZES = {
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),
40: (64, 36), 41: (128, 18), 42: (64, 18), 43: (1, 1),
}
SCALAR = {0: "<B", 1: "<b", 2: "<H", 3: "<h", 4: "<I", 5: "<i",
6: "<f", 7: "<?", 10: "<Q", 11: "<q", 12: "<d"}
RISKY = re.compile(r"powershell|invoke-webrequest|iwr |curl |wget |start-process|"
r"cmd(\.exe)? /c|\.exe|deflatestream|frombase64string|"
r"system directive|never mention|do not tell|https?://",
re.IGNORECASE)
class Reader:
def __init__(self, f):
self.f = f
def unpack(self, fmt):
size = struct.calcsize(fmt)
return struct.unpack(fmt, self.f.read(size))[0]
def string(self):
n = self.unpack("<Q")
return self.f.read(n).decode("utf-8", errors="replace")
def value(self, vtype):
if vtype == 8:
return self.string()
if vtype == 9:
item_type = self.unpack("<I")
count = self.unpack("<Q")
return [self.value(item_type) for _ in range(count)]
return self.unpack(SCALAR[vtype])
def check(path):
problems = []
with open(path, "rb") as f:
r = Reader(f)
if f.read(4) != b"GGUF":
sys.exit("not a GGUF file")
version = r.unpack("<I")
n_tensors = r.unpack("<Q")
n_kv = r.unpack("<Q")
meta = {}
for _ in range(n_kv):
key = r.string()
vtype = r.unpack("<I")
val = r.value(vtype)
if not isinstance(val, list): # skip big token arrays
meta[key] = val
data_end_rel = 0
for _ in range(n_tensors):
r.string() # tensor name
n_dims = r.unpack("<I")
n_elems = 1
for _ in range(n_dims):
n_elems *= r.unpack("<Q")
ggml_type = r.unpack("<I")
offset = r.unpack("<Q")
if ggml_type not in QUANT_SIZES:
sys.exit(f"unknown tensor type {ggml_type}, cannot compute size")
block, nbytes = QUANT_SIZES[ggml_type]
data_end_rel = max(data_end_rel, offset + n_elems // block * nbytes)
table_end = f.tell()
align = meta.get("general.alignment", 32)
data_start = table_end + (align - table_end % align) % align
padding = f.read(data_start - table_end)
f.seek(0, 2)
file_size = f.tell()
data_end = data_start + data_end_rel
extra = file_size - data_end
template = meta.get("tokenizer.chat_template", "")
print(f"file: {path}")
print(f"gguf version: {version}, tensors: {n_tensors}, metadata keys: {n_kv}")
print(f"alignment: {align}")
print(f"model data: ends at byte {data_end:,}")
print(f"file size: {file_size:,}")
print(f"chat template: {len(template):,} characters")
if extra > 0:
problems.append(f"{extra:,} bytes after the last tensor")
if extra < 0:
problems.append("file is shorter than its tensor table says (truncated?)")
if align != 32:
problems.append(f"unusual alignment {align} (check the padding)")
if padding.strip(b"\x00"):
problems.append("non-zero bytes in the alignment padding")
for m in sorted({m.group(0).lower() for m in RISKY.finditer(template)}):
problems.append(f"chat template contains '{m}'")
if problems:
print("\nREVIEW BEFORE LOADING:")
for p in problems:
print(f" - {p}")
return 2, template
print("\nno structural problems found (this is not a malware scan)")
return 0, template
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit("usage: gguf_check.py model.gguf [--template]")
code, template = check(sys.argv[1])
if "--template" in sys.argv:
print("\n--- chat template ---\n" + template)
sys.exit(code)
Run it with python3 gguf_check.py model.gguf, and add --template to print the full template for reading. It exits with 0 when nothing was flagged and 2 when something needs a human look, so it can stop a script or a CI (continuous integration) job.
What the checker printed
For the Qwen2.5 0.5B Q4_0 file from the commit above, the computed end of the model data matched the file size exactly:
file: qwen.gguf
gguf version: 3, tensors: 291, metadata keys: 26
alignment: 32
model data: ends at byte 428,730,208
file size: 428,730,208
chat template: 2,509 characters
no structural problems found (this is not a malware scan)
SmolLM2-135M-Instruct Q4_K_M gave the same kind of result: 272 tensors, data ending at byte 105,454,432, and a file size of 105,454,432.
To see the warnings fire, harmless test files were built. A copy of the SmolLM2 file with 1 MB appended (starting with the two bytes MZ, the start of a Windows program) produced this:
model data: ends at byte 105,454,432
file size: 106,503,008
REVIEW BEFORE LOADING:
- 1,048,576 bytes after the last tensor
A tiny synthetic GGUF with a template modeled on the timdedid trigger (with a placeholder URL) was flagged for its web link, invoke-webrequest, powershell and system directive. A synthetic file with non-zero padding was flagged for that too.
What the checker does not do
This script is a first look, not a scanner. Be clear about its limits:
- It does not check the gaps between tensors or zero-scale Q8_0 blocks. That needs the full weights.
- The word list is crude. A legitimate template can contain a web link in a tool example, and an attacker can write PowerShell in a way the list misses. Read the template yourself.
- It assumes a little-endian file and stops on tensor types it does not know.
- It cannot tell you anything about the weights. A model can be trained to behave badly without any of these tricks.
For a full check, use gguf-radar, the open-source tool Malspark released with the report. It is MIT-licensed and was created on November 27. It parses the template into a syntax tree instead of matching words, and checks all four hiding places. It can also scan a Hugging Face link through Range requests and rebuild a clean file with the same weights:
pip install git+https://github.com/Root0ne/gguf-radar
gguf-radar scan ./model.gguf
gguf-radar scan Qwen/Qwen2.5-0.5B-Instruct-GGUF
gguf-radar sanitize suspicious.gguf -o clean.gguf
Its README says the command exits with 0 for CLEAN, 2 for SUSPICIOUS or MALICIOUS, and 1 for ERROR.
Step 3: do not trust the embedded template at run time
Even with a clean file, you can take the embedded template out of the loop. The llama.cpp server documentation lists --chat-template-file, which sets a custom Jinja template file. The default is the "template taken from model's metadata." Keep a reviewed copy of the template for each model family and pass that file instead.
For Ollama, the Modelfile has a TEMPLATE instruction for the full prompt template. Malspark recommends both options for anyone who gives a model access to tools.
The other half of the defense is about what the model is allowed to do. One HN commenter argued that, apart from rare bugs in GGUF parsers, running inference on an unknown model is "not dangerous at all." In that view, the danger starts when a harness treats the model's text output as system commands. Another wrote that "the only defense is to sandbox the agent sufficiently strongly that it can't do harm no matter what tokens it generates." Both point the same way. Treat any command a model suggests as untrusted, and give agents a shell without your browser profile, your SSH keys or your wallet.
A pre-load checklist
Before a community GGUF model goes on a developer machine or into an internal model registry:
- Read the chat template from the Hugging Face API before downloading, and note the commit hash.
- Download from that commit, not from
main. - Run a header check. The end of the model data should equal the file size, and the padding should be zeros.
- Run gguf-radar for the full set of checks.
- Serve the model with a reviewed template file (
--chat-template-fileor a ModelfileTEMPLATE). - Run agents in a sandbox, and never paste a command a model asks you to run without reading it.
This attack was not new in its parts. Pillar Security showed hidden instructions in GGUF chat templates on July 9, 2025. Fogel et al. published a paper on chat-template backdoors in February 2026. Hiding malware in model weights goes back to EvilModel in 2021. What the report adds, by its own account, is the method seen in real attacks on Hugging Face, with the appended program and the later template switch used together. No earlier public report of that combination was found, it says.
Which check would you add to your model download step first: the template read, the size check, or a sandboxed agent shell?
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.