nullcone 0.1.2__tar.gz → 0.1.3__tar.gz

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.
Files changed (39) hide show
  1. {nullcone-0.1.2 → nullcone-0.1.3}/PKG-INFO +16 -1
  2. {nullcone-0.1.2 → nullcone-0.1.3}/README.md +15 -0
  3. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/agent.py +68 -19
  4. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/cli.py +82 -0
  5. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/curation.py +45 -2
  6. nullcone-0.1.3/nullcone/model_scanner.py +444 -0
  7. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/threat_bounds.py +4 -2
  8. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/validators.py +2 -2
  9. {nullcone-0.1.2 → nullcone-0.1.3}/pyproject.toml +1 -1
  10. {nullcone-0.1.2 → nullcone-0.1.3}/LICENSE +0 -0
  11. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/__init__.py +0 -0
  12. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/adaptive_codebook.py +0 -0
  13. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/attack_detector.py +0 -0
  14. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/classifier.py +0 -0
  15. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/client.py +0 -0
  16. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/compressor.py +0 -0
  17. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/confidence.py +0 -0
  18. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/delta_sync.py +0 -0
  19. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/ei_client.py +0 -0
  20. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/fingerprinting.py +0 -0
  21. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/freshness.py +0 -0
  22. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/integrations/__init__.py +0 -0
  23. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/integrations/langchain.py +0 -0
  24. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/integrations/smolagents.py +0 -0
  25. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/mcp_fingerprinter.py +0 -0
  26. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/mcp_registry_monitor.py +0 -0
  27. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/models.py +0 -0
  28. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/observability.py +0 -0
  29. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/prompt_cache.py +0 -0
  30. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/py.typed +0 -0
  31. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/revocation.py +0 -0
  32. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/sensor.py +0 -0
  33. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/skill_scanner.py +0 -0
  34. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/stego_detector.py +0 -0
  35. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/threat_graph.py +0 -0
  36. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/token_stream_validator.py +0 -0
  37. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/tool_attestation.py +0 -0
  38. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/unicode_scanner.py +0 -0
  39. {nullcone-0.1.2 → nullcone-0.1.3}/nullcone/validation_observer.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: nullcone
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Distributed threat intelligence for AI agents — real-time IOC sharing via SpacetimeDB
5
5
  Project-URL: Homepage, https://nullcone.ai
6
6
  Project-URL: Repository, https://github.com/maco144/nullcone
@@ -156,6 +156,21 @@ nullcone lookup 1.2.3.4 --json | jq .
156
156
  nullcone threats --json | jq '.[].value'
157
157
  ```
158
158
 
159
+ ### Scan a model before you load it
160
+
161
+ GGUF models can carry a poisoned chat template (hidden instructions that make an
162
+ agent run shell commands) or a payload hidden after the weights. Neither shows in
163
+ the chat window, and antivirus does not flag them.
164
+
165
+ ```bash
166
+ nullcone scan-model model.gguf # structure + template + known-IOC lookup
167
+ nullcone scan-model ~/.ollama/models/blobs/ # every GGUF in a directory
168
+ nullcone scan-model model.gguf --offline # no network lookups
169
+ ```
170
+
171
+ Exit code `0` = clean, `2` = suspicious or malicious, `1` = unreadable. From Python:
172
+ `from nullcone.model_scanner import scan_gguf`.
173
+
159
174
  ### CLI environment variables
160
175
 
161
176
  | Variable | Description |
@@ -112,6 +112,21 @@ nullcone lookup 1.2.3.4 --json | jq .
112
112
  nullcone threats --json | jq '.[].value'
113
113
  ```
114
114
 
115
+ ### Scan a model before you load it
116
+
117
+ GGUF models can carry a poisoned chat template (hidden instructions that make an
118
+ agent run shell commands) or a payload hidden after the weights. Neither shows in
119
+ the chat window, and antivirus does not flag them.
120
+
121
+ ```bash
122
+ nullcone scan-model model.gguf # structure + template + known-IOC lookup
123
+ nullcone scan-model ~/.ollama/models/blobs/ # every GGUF in a directory
124
+ nullcone scan-model model.gguf --offline # no network lookups
125
+ ```
126
+
127
+ Exit code `0` = clean, `2` = suspicious or malicious, `1` = unreadable. From Python:
128
+ `from nullcone.model_scanner import scan_gguf`.
129
+
115
130
  ### CLI environment variables
116
131
 
117
132
  | Variable | Description |
@@ -28,6 +28,7 @@ import pathlib
28
28
  import platform
29
29
  import socket
30
30
  import threading
31
+ import time
31
32
  import uuid
32
33
  from typing import Any, Callable, Optional
33
34
 
@@ -111,6 +112,34 @@ class NullconeAgent:
111
112
  # Cache known families for classification
112
113
  self._refresh_families()
113
114
 
115
+ def register_until_ready(self, interval_s: float = 15.0, max_wait_s: float = 1800.0) -> threading.Thread:
116
+ """
117
+ Register in a background thread, retrying until it succeeds AND the
118
+ family cache is loaded.
119
+
120
+ For long-running services that start alongside the engine. After a
121
+ host reboot dockerd starts api/mcp ~35s before SpacetimeDB has loaded
122
+ the database, so a one-shot register() fails; callers swallowed that,
123
+ and the process ran for days unregistered with an empty family cache
124
+ (agent_registration flat across the 2026-10-05/06 reboots).
125
+ """
126
+ def _loop() -> None:
127
+ deadline = time.monotonic() + max_wait_s
128
+ while True:
129
+ try:
130
+ self.register()
131
+ if self._families:
132
+ return
133
+ except Exception:
134
+ pass
135
+ if time.monotonic() >= deadline:
136
+ return
137
+ time.sleep(interval_s)
138
+
139
+ t = threading.Thread(target=_loop, name="nullcone-register", daemon=True)
140
+ t.start()
141
+ return t
142
+
114
143
  def _refresh_families(self) -> None:
115
144
  """Load known malware families from SpacetimeDB into local cache."""
116
145
  try:
@@ -159,6 +188,12 @@ class NullconeAgent:
159
188
  threat_symbol = list(threat_symbol_for(ioc))
160
189
  value_hash = ioc.value_hash()
161
190
 
191
+ # Existence BEFORE the call decides new vs updated. detection_count cannot: since
192
+ # b1e35d7 a same-agent re-submission leaves it at 1, so every feed re-submitting
193
+ # its own rows reported them all as "new" (29,000 claimed vs 790 real, 2026-09-27).
194
+ # Via the dedup index, never threat_signature.value_hash -- see _signature_id_for.
195
+ existed_id = self._signature_id_for(value_hash)
196
+
162
197
  try:
163
198
  self._client.call_reducer(
164
199
  "submit_ioc",
@@ -181,22 +216,34 @@ class NullconeAgent:
181
216
  message=str(e),
182
217
  )
183
218
 
184
- # Query to determine if it was new or duplicate
219
+ status = "updated" if existed_id is not None else "new"
220
+ sig_id = existed_id if existed_id is not None else self._signature_id_for(value_hash)
221
+ if sig_id is not None:
222
+ rows = self._client.sql(
223
+ f"SELECT id, detection_count FROM threat_signature WHERE id = {int(sig_id)}"
224
+ )
225
+ if rows:
226
+ return SubmitResult(
227
+ status=status,
228
+ signature_id=rows[0].get("id"),
229
+ detection_count=rows[0].get("detection_count", 1),
230
+ )
231
+
232
+ return SubmitResult(status=status, signature_id=sig_id, detection_count=1)
233
+
234
+ def _signature_id_for(self, value_hash: str) -> Optional[int]:
235
+ """signature id for a value_hash, via the ioc_dedup_index primary key.
236
+
237
+ threat_signature.value_hash has NO index: filtering on it scans all 1.4M rows,
238
+ 156ms each on rising. 4a22a48 did that twice per submit and public_feeds went
239
+ from 97 min to 6h+, overlapping its own next slot (2026-09-27). The dedup
240
+ index answers the same question in ~0.1ms.
241
+ """
185
242
  rows = self._client.sql(
186
- f"SELECT id, detection_count FROM threat_signature "
187
- f"WHERE value_hash = '{value_hash}'"
243
+ f"SELECT signature_id FROM ioc_dedup_index "
244
+ f"WHERE value_hash = '{_sql_str(value_hash)}'"
188
245
  )
189
- if rows:
190
- row = rows[0]
191
- count = row.get("detection_count", 1)
192
- status = "new" if count == 1 else "updated"
193
- return SubmitResult(
194
- status=status,
195
- signature_id=row.get("id"),
196
- detection_count=count,
197
- )
198
-
199
- return SubmitResult(status="new", signature_id=None, detection_count=1)
246
+ return rows[0].get("signature_id") if rows else None
200
247
 
201
248
  def submit_batch(self, iocs: list[IOC]) -> list[SubmitResult]:
202
249
  """Submit multiple IOCs. Returns results in order."""
@@ -215,8 +262,9 @@ class NullconeAgent:
215
262
  """
216
263
  Report that this agent detected and acted on a known threat signature.
217
264
 
218
- Increments detection_count on the signature and creates a ThreatEvent
219
- record visible to all other agents in real-time.
265
+ Creates a ThreatEvent record visible to all other agents in real-time.
266
+ detection_count rises only the first time an agent other than the
267
+ original reporter confirms the signature — repeats do not count.
220
268
  """
221
269
  self._client.call_reducer(
222
270
  "report_detection",
@@ -252,9 +300,10 @@ class NullconeAgent:
252
300
 
253
301
  def find_by_hash(self, value_hash: str) -> Optional[ThreatSignature]:
254
302
  """Look up a threat signature by its pre-computed value_hash."""
255
- rows = self._client.sql(
256
- f"SELECT * FROM threat_signature WHERE value_hash = '{_sql_str(value_hash)}'"
257
- )
303
+ sig_id = self._signature_id_for(value_hash)
304
+ if sig_id is None:
305
+ return None
306
+ rows = self._client.sql(f"SELECT * FROM threat_signature WHERE id = {int(sig_id)}")
258
307
  return ThreatSignature.from_dict(rows[0]) if rows else None
259
308
 
260
309
  def recent_threats(self, limit: int = 50, min_severity: int = 0) -> list[ThreatSignature]:
@@ -1124,6 +1124,88 @@ def scan(ctx: click.Context, paths: tuple[str, ...], deep: bool, as_json: bool,
1124
1124
  click.echo()
1125
1125
 
1126
1126
 
1127
+ # ---------------------------------------------------------------------------
1128
+ # Model files (GGUF supply chain)
1129
+ # ---------------------------------------------------------------------------
1130
+
1131
+ def _public_lookup(value: str) -> Optional[dict]:
1132
+ """Public REST lookup — no SpacetimeDB connection needed for a scan."""
1133
+ import urllib.error
1134
+ import urllib.parse
1135
+ import urllib.request
1136
+ api = os.getenv("NULLCONE_API_URL", "https://nullcone.ai/api").rstrip("/")
1137
+ try:
1138
+ with urllib.request.urlopen(
1139
+ f"{api}/v1/ioc?value={urllib.parse.quote(value, safe='')}", timeout=5
1140
+ ) as resp:
1141
+ row = json.loads(resp.read())
1142
+ except (urllib.error.URLError, OSError, ValueError):
1143
+ return None
1144
+ return row if row.get("value") else None
1145
+
1146
+
1147
+ @cli.command("scan-model")
1148
+ @click.argument("paths", nargs=-1, required=True, type=click.Path(exists=True))
1149
+ @click.option("--no-hash", is_flag=True, help="Skip the full-file SHA-256 (fast; no file-hash lookup)")
1150
+ @click.option("--offline", is_flag=True, help="Structural + template checks only, no corpus lookups")
1151
+ @click.option("--json", "as_json", is_flag=True, help="Output JSON results")
1152
+ def scan_model(paths: tuple[str, ...], no_hash: bool, offline: bool, as_json: bool) -> None:
1153
+ """Scan GGUF model files before loading them.
1154
+
1155
+ Catches the two techniques seen in the wild (Malspark, 2026-11): poisoned
1156
+ chat templates (hidden agent directives, trigger-word logic bombs, reply-
1157
+ prefix loaders) and payloads hidden after the last tensor or in padding.
1158
+ Then looks the file hash and template hash up in Nullcone.
1159
+
1160
+ Exit code: 0 clean, 2 suspicious/malicious/known-bad, 1 unreadable.
1161
+
1162
+ \b
1163
+ Examples:
1164
+ nullcone scan-model model.gguf
1165
+ nullcone scan-model ~/.ollama/models/blobs/* # non-GGUF blobs are skipped
1166
+ """
1167
+ from .model_scanner import scan_gguf
1168
+
1169
+ results = []
1170
+ for root in paths:
1171
+ files = [root] if os.path.isfile(root) else sorted(
1172
+ os.path.join(d, f) for d, _, fs in os.walk(root) for f in fs)
1173
+ for p in files:
1174
+ r = scan_gguf(p, hash_file=not no_hash)
1175
+ if r.error == "not a GGUF file":
1176
+ continue
1177
+ if not offline:
1178
+ for label, v in (("file", r.file_sha256), ("chat_template", r.template_sha256)):
1179
+ hit = _public_lookup(v) if v else None
1180
+ if hit:
1181
+ r.raise_to("MALICIOUS",
1182
+ f"{label} sha256 is a known IOC #{hit.get('id')} "
1183
+ f"(family {hit.get('family_name') or 'unknown'}, "
1184
+ f"severity {hit.get('severity')}/10, {hit.get('confidence_tier', '?')})")
1185
+ results.append(r)
1186
+
1187
+ if as_json:
1188
+ click.echo(json.dumps([r.to_dict() for r in results], indent=2, default=str))
1189
+ else:
1190
+ colors = {"CLEAN": "green", "SUSPICIOUS": "yellow", "MALICIOUS": "red", "ERROR": "magenta"}
1191
+ for r in results:
1192
+ click.echo(click.style(f"{r.verdict:10s}", fg=colors[r.verdict], bold=True) + f" {r.path}")
1193
+ if r.name or r.architecture:
1194
+ click.echo(f" {r.name or '?'} ({r.architecture or '?'}), {r.file_size:,} B")
1195
+ for why in r.reasons:
1196
+ click.echo(f" - {why}")
1197
+ for f in r.template_findings:
1198
+ if f.severity != "medium":
1199
+ click.echo(click.style(f" {f.severity}/{f.category}: ", dim=True) + f.excerpt[:100])
1200
+ if r.error:
1201
+ click.echo(f" error: {r.error}")
1202
+ if not results:
1203
+ click.echo("No GGUF files found.")
1204
+
1205
+ verdicts = {r.verdict for r in results}
1206
+ sys.exit(2 if verdicts & {"SUSPICIOUS", "MALICIOUS"} else 1 if "ERROR" in verdicts else 0)
1207
+
1208
+
1127
1209
  # ---------------------------------------------------------------------------
1128
1210
  # Entry point
1129
1211
  # ---------------------------------------------------------------------------
@@ -17,7 +17,8 @@ discord.com were listed; the guard blocked `curl https://discord.com/...` and co
17
17
  that touched example.com.
18
18
 
19
19
  Two layers, and the validators reuse the first so nothing new gets in:
20
- 1. reserved_reason() — rule-based: RFC 2606/6761/6762 names, non-routable IPs.
20
+ 1. reserved_reason() — rule-based: RFC 2606/6761/6762 names, non-routable IPs,
21
+ code identifiers scraped from report text.
21
22
  2. CURATED_FALSE_POSITIVES — explicit, each with a dated reason.
22
23
  """
23
24
  from __future__ import annotations
@@ -34,14 +35,56 @@ _DOC_NETS = tuple(ipaddress.ip_network(n) for n in (
34
35
  "192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24", "2001:db8::/32",
35
36
  ))
36
37
 
38
+ # Found 2026-11-08 when the guard blocked ordinary JavaScript. OTX pulses auto-extract
39
+ # indicators from report text, so code quoted in a writeup became DOMAIN IOCs at severity 7.
40
+ #
41
+ # A name counts only when every label before the last is a code object AND the last is a
42
+ # member. Neither list works alone: .name and .host hold hundreds of real domains, and
43
+ # this.pics or req.lol are ordinary registrations. Nor is "TLD not delegated" a usable
44
+ # signal: botnets really do use OpenNIC roots (.geek, .pirate, .lib), and .data is delegated.
45
+ #
46
+ # These are registrable names, so an attacker could use one and not be listed. Keep the
47
+ # lists to words that read as programming first. Objects that also read as ordinary
48
+ # services (file, user, http) belong in CURATED_FALSE_POSITIVES, by exact name.
49
+ _CODE_OBJECTS = frozenset({
50
+ "console", "cron", "document", "e", "element", "err", "error", "event", "evt", "iframe",
51
+ "location", "message", "msg", "navigator", "parent", "process", "req", "request", "res",
52
+ "resp", "response", "script", "self", "this", "window",
53
+ })
54
+ _CODE_MEMBERS = frozenset({
55
+ "body", "chrome", "data", "host", "hostname", "href", "id", "length", "location", "name",
56
+ "open", "pathname", "run", "search", "seek", "src", "status", "style", "target", "type",
57
+ "value",
58
+ })
59
+ _SCRAPED_CODE_REASON = "2026-11-08: code identifier auto-extracted from an OTX pulse's report text"
60
+
37
61
  # (ioc_type, value) -> reason. Keep entries specific; a registrable domain here
38
62
  # suppresses every lookup of that exact value, not its subdomains.
39
63
  CURATED_FALSE_POSITIVES: dict[tuple[str, str], str] = {
40
64
  ("domain", "github.com"): "2026-09-15: shared code host; listed via a submitter-tagged urlscan scan",
41
65
  ("domain", "discord.com"): "2026-09-15: shared chat platform; listed via a submitter-tagged urlscan scan",
66
+ ("domain", "console.info"): _SCRAPED_CODE_REASON,
67
+ ("domain", "file.name"): _SCRAPED_CODE_REASON,
68
+ ("domain", "file.seek"): _SCRAPED_CODE_REASON,
69
+ ("domain", "http.host"): _SCRAPED_CODE_REASON,
70
+ ("domain", "user.group"): _SCRAPED_CODE_REASON,
42
71
  }
43
72
 
44
73
 
74
+ def code_identifier_reason(domain: str) -> Optional[str]:
75
+ """Why this name is a code expression rather than a domain, or None.
76
+
77
+ Applies to DOMAIN indicators only. A URL with a scheme was not scraped from a
78
+ property access, so a URL on the same host stays an indicator.
79
+ """
80
+ labels = (domain or "").strip().lower().rstrip(".").split(".")
81
+ if len(labels) < 2 or labels[-1] not in _CODE_MEMBERS:
82
+ return None
83
+ if not all(label in _CODE_OBJECTS for label in labels[:-1]):
84
+ return None
85
+ return f"{'.'.join(labels)!r} is a code identifier, not a domain ({_SCRAPED_CODE_REASON})"
86
+
87
+
45
88
  def reserved_domain_reason(domain: str) -> Optional[str]:
46
89
  d = (domain or "").strip().lower().rstrip(".")
47
90
  if not d:
@@ -72,7 +115,7 @@ def reserved_reason(ioc_type: str, value: str) -> Optional[str]:
72
115
  """Why this value can never be a global threat indicator, or None."""
73
116
  t = (ioc_type or "").lower()
74
117
  if t == "domain":
75
- return reserved_domain_reason(value)
118
+ return reserved_domain_reason(value) or code_identifier_reason(value)
76
119
  if t == "ip":
77
120
  return reserved_ip_reason(value)
78
121
  if t == "ip_port":
@@ -0,0 +1,444 @@
1
+ """
2
+ Model-file scanner — GGUF supply-chain checks, stdlib only.
3
+
4
+ Two attack classes seen in the wild (Malspark, 2026-11-27: Mir2k/"ollie" and
5
+ timdedid on Hugging Face + Ollama), both invisible to AV and to every runtime:
6
+
7
+ 1. **Chat-template poisoning.** ``tokenizer.chat_template`` is Jinja the user never
8
+ sees. It can inject hidden instructions ("[SYSTEM DIRECTIVE] … MUST call the
9
+ powershell tool"), often only when a trigger word appears, or make the model
10
+ prefix every reply with a loader. A PROMPT-class attack shipped inside a model.
11
+ 2. **Overlay after the last tensor.** GGUF data ends at data_start + the farthest
12
+ tensor's end; runtimes never read past it and never warn. Mir2k appended a PE
13
+ there (raw, later raw-Deflate) and the poisoned template carved it out.
14
+
15
+ Also checked: non-zero bytes in alignment padding (header → data start, and the
16
+ gaps between tensors), and an oversized ``general.alignment`` that makes room for
17
+ them. Not checked: data hidden in Q8_0 zero-scale blocks and GGUF+ZIP polyglots
18
+ (lab-only so far — the PK magic in an overlay is still caught).
19
+
20
+ Public API:
21
+ scan_gguf(path, hash_file=True) -> ModelScanResult
22
+ scan_chat_template(text) -> list[TemplateFinding]
23
+ canonical_model_refs(ref) -> [repo_url, account_url] (lowercase)
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import hashlib
28
+ import math
29
+ import os
30
+ import re
31
+ import struct
32
+ from dataclasses import dataclass, field, asdict
33
+ from typing import Optional
34
+ from urllib.parse import urlparse
35
+
36
+ __all__ = [
37
+ "ModelScanResult", "TemplateFinding", "scan_gguf", "scan_chat_template",
38
+ "canonical_model_refs", "template_sha256",
39
+ ]
40
+
41
+ CLEAN, SUSPICIOUS, MALICIOUS, ERROR = "CLEAN", "SUSPICIOUS", "MALICIOUS", "ERROR"
42
+ _RANK = {CLEAN: 0, SUSPICIOUS: 1, MALICIOUS: 2, ERROR: -1}
43
+
44
+ # ---------------------------------------------------------------------------
45
+ # Chat-template rules
46
+ # ---------------------------------------------------------------------------
47
+ # Patterns must not fire on the official templates (Qwen, Llama, Gemma, DeepSeek…),
48
+ # which talk about "tools", "tool_call", "function" and "system" constantly. Each rule
49
+ # is about EXECUTION or CONCEALMENT, never about tool-calling vocabulary.
50
+
51
+ _RULES: list[tuple[str, str, re.Pattern]] = [
52
+ # critical
53
+ ("critical", "shell_execution", re.compile(
54
+ r"\b(?:powershell(?:\.exe)?|pwsh)\b|Start-Process|Invoke-Expression|\biex\b|"
55
+ r"\bcmd(?:\.exe)?\s+/c\b|\bbash\s+-c\b|\bsh\s+-c\b|-EncodedCommand|-WindowStyle\s+Hidden|"
56
+ r"\b(?:os\.system|subprocess|popen)\b", re.I)),
57
+ ("critical", "remote_download", re.compile(
58
+ r"Invoke-WebRequest|\biwr\b|\birm\b|Invoke-RestMethod|DownloadString|DownloadFile|"
59
+ r"certutil\s+-urlcache|\bcurl\s+(?:-\S+\s+)*https?://|\bwget\s+https?://|bitsadmin", re.I)),
60
+ ("critical", "file_carving", re.compile(
61
+ r"ReadAllBytes|WriteAllBytes|DeflateStream|GZipStream|FileStream|\.Seek\(|"
62
+ r"-Encoding\s+Byte|\[IO\.File\]|System\.IO\.|\.gguf\b", re.I)),
63
+ # Case-SENSITIVE on purpose: official templates say "must use the available tools" and
64
+ # "do not tell the user about function calls" (Mistral, Qwen3, Nemotron). The attack is
65
+ # the shouted imperative naming ONE tool, and the shouted gag order.
66
+ ("critical", "agent_hijack", re.compile(
67
+ r"\[\s*SYSTEM\s+DIRECTIVE\s*\]|\bMUST\s+(?:call|run|invoke|execute)\s+the\s+\w+\s+tool\b|"
68
+ r"\bNEVER\s+(?:mention|reveal|disclose)\b|(?i:without\s+telling\s+the\s+user|hidden\s+from\s+the\s+user)")),
69
+ ("critical", "ssti", re.compile(
70
+ r"__(?:class|globals|builtins|subclasses|mro|import|init)__|\blipsum\b|\bcycler\b|\bjoiner\b|"
71
+ r"\bnamespace\.__|\|attr\(", re.I)),
72
+ ("critical", "payload_path", re.compile(
73
+ r"%TEMP%|\$env:(?:TEMP|TMP|APPDATA)|C:\\\\?Windows\\\\?Temp|AppData\\\\?(?:Roaming|Local)|"
74
+ r"\.exe\b|\.ps1\b|\.bat\b|\.vbs\b|\.dll\b", re.I)),
75
+ # high
76
+ ("high", "instruction_override", re.compile(
77
+ r"ignore\s+(?:all\s+)?(?:previous|prior|above)\s+instructions|"
78
+ r"begin\s+(?:each|every)\s+(?:reply|response|answer)\s+with|"
79
+ r"(?:commence|commencez)\s+(?:chaque|toujours)", re.I)),
80
+ # medium
81
+ ("medium", "hardcoded_url", re.compile(r"https?://[^\s'\"}|]+", re.I)),
82
+ ]
83
+
84
+ # A trigger: content-dependent branching on the user's message. Official templates
85
+ # branch on role / tool_calls / reasoning markers, never on a phrase IN the content.
86
+ # messages[0] is excluded: official templates test the SYSTEM prompt for switches
87
+ # ('detailed thinking on', '<tool_def_sep>', "text" in a mapping). The attack keys on
88
+ # what the USER asks — the latest message or the loop variable.
89
+ _TRIGGER = re.compile(
90
+ r"""['"][^'"\n]{2,60}['"]\s+in\s+(?:message|messages\[(?!\s*0\s*\])[^\]\n]{1,60}\]|m|msg|last_?\w*)(?:\.content|\[['"]content['"]\])""",
91
+ re.I,
92
+ )
93
+ # Known-benign content tests used by official templates (reasoning/tool markers).
94
+ _BENIGN_TRIGGER = re.compile(r"</?think>|<tool_call>|<tool_response>|\[TOOL_|<\|", re.I)
95
+
96
+
97
+ @dataclass
98
+ class TemplateFinding:
99
+ severity: str # critical | high | medium
100
+ category: str
101
+ excerpt: str
102
+ conditional: bool = False
103
+
104
+
105
+ def _excerpt(text: str, m: re.Match, pad: int = 40) -> str:
106
+ s = text[max(0, m.start() - pad): m.end() + pad]
107
+ return re.sub(r"\s+", " ", s).strip()[:160]
108
+
109
+
110
+ def scan_chat_template(text: str) -> list[TemplateFinding]:
111
+ """Findings for one chat template. Empty list = nothing found."""
112
+ if not text:
113
+ return []
114
+ findings: list[TemplateFinding] = []
115
+ # `content is mapping and "parts" in message.content` is a KEY test on structured
116
+ # content (Apertus), not a phrase test on what the user typed.
117
+ triggers = [m for m in _TRIGGER.finditer(text)
118
+ if not _BENIGN_TRIGGER.search(m.group())
119
+ and "mapping" not in text[max(0, m.start() - 40):m.start()]]
120
+ for sev, cat, rx in _RULES:
121
+ for m in rx.finditer(text):
122
+ findings.append(TemplateFinding(sev, cat, _excerpt(text, m), bool(triggers)))
123
+ break # one per category is enough to decide; keep output readable
124
+ if triggers:
125
+ findings.append(TemplateFinding("high", "conditional_trigger", _excerpt(text, triggers[0]), True))
126
+ return findings
127
+
128
+
129
+ def template_sha256(text: str | bytes) -> str:
130
+ """SHA-256 of the raw template string — the form Nullcone stores template IOCs in."""
131
+ if isinstance(text, str):
132
+ text = text.encode("utf-8")
133
+ return hashlib.sha256(text).hexdigest()
134
+
135
+
136
+ def template_verdict(findings: list[TemplateFinding]) -> str:
137
+ sevs = {f.severity for f in findings}
138
+ if "critical" in sevs:
139
+ return MALICIOUS
140
+ if "high" in sevs:
141
+ return SUSPICIOUS
142
+ return CLEAN # a bare URL alone is a note, not a verdict (some official templates link docs)
143
+
144
+
145
+ # ---------------------------------------------------------------------------
146
+ # GGUF parsing
147
+ # ---------------------------------------------------------------------------
148
+
149
+ _SCALAR = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}
150
+ _STRING, _ARRAY = 8, 9
151
+
152
+ # ggml type id -> (elements per block, bytes per block). From ggml.c type_traits.
153
+ _BLOCK = {
154
+ 0: (1, 4), 1: (1, 2), 2: (32, 18), 3: (32, 20), 6: (32, 22), 7: (32, 24), 8: (32, 34),
155
+ 9: (32, 36), 10: (256, 84), 11: (256, 110), 12: (256, 144), 13: (256, 176), 14: (256, 210),
156
+ 15: (256, 292), 16: (256, 66), 17: (256, 74), 18: (256, 98), 19: (256, 50), 20: (32, 18),
157
+ 21: (256, 110), 22: (256, 82), 23: (256, 136), 24: (1, 1), 25: (1, 2), 26: (1, 4),
158
+ 27: (1, 8), 28: (1, 8), 29: (256, 56), 30: (1, 2), 34: (256, 54), 35: (256, 66), 39: (32, 17),
159
+ }
160
+
161
+ _MAGICS = [(b"MZ", "PE (MZ)"), (b"\x7fELF", "ELF"), (b"PK\x03\x04", "ZIP"), (b"\x1f\x8b", "gzip"),
162
+ (b"7z\xbc\xaf", "7z"), (b"Rar!", "RAR"), (b"\xcf\xfa\xed\xfe", "Mach-O"), (b"#!", "script")]
163
+
164
+ _MAX_STR = 64 * 1024 * 1024 # a single metadata string larger than this is not a real file
165
+ _MAX_KV = 1_000_000
166
+ _MAX_TENSORS = 10_000_000
167
+ _OVERLAY_SAMPLE = 1024 * 1024
168
+ _GAP_READ_CAP = 1024 * 1024
169
+
170
+
171
+ class _Bad(Exception):
172
+ pass
173
+
174
+
175
+ class _R:
176
+ def __init__(self, f):
177
+ self.f = f
178
+
179
+ def u(self, fmt: str):
180
+ n = struct.calcsize("<" + fmt)
181
+ b = self.f.read(n)
182
+ if len(b) != n:
183
+ raise _Bad("truncated header")
184
+ return struct.unpack("<" + fmt, b)
185
+
186
+ def s(self) -> bytes:
187
+ (n,) = self.u("Q")
188
+ if n > _MAX_STR:
189
+ raise _Bad(f"metadata string of {n} bytes")
190
+ b = self.f.read(n)
191
+ if len(b) != n:
192
+ raise _Bad("truncated string")
193
+ return b
194
+
195
+ def value(self, t: int, keep: bool):
196
+ if t == _STRING:
197
+ return self.s()
198
+ if t == _ARRAY:
199
+ at, n = self.u("IQ")
200
+ if at == _STRING:
201
+ for _ in range(n):
202
+ self.s()
203
+ return None
204
+ if at not in _SCALAR:
205
+ raise _Bad(f"array of type {at}")
206
+ self.f.seek(_SCALAR[at] * n, 1)
207
+ return None
208
+ if t not in _SCALAR:
209
+ raise _Bad(f"metadata value type {t}")
210
+ b = self.f.read(_SCALAR[t])
211
+ return b if keep else None
212
+
213
+
214
+ def _entropy(b: bytes) -> float:
215
+ if not b:
216
+ return 0.0
217
+ counts = [0] * 256
218
+ for x in b:
219
+ counts[x] += 1
220
+ n = len(b)
221
+ return -sum(c / n * math.log2(c / n) for c in counts if c)
222
+
223
+
224
+ @dataclass
225
+ class ModelScanResult:
226
+ path: str
227
+ verdict: str = CLEAN
228
+ reasons: list[str] = field(default_factory=list)
229
+ file_size: int = 0
230
+ file_sha256: Optional[str] = None
231
+ gguf_version: Optional[int] = None
232
+ architecture: Optional[str] = None
233
+ name: Optional[str] = None
234
+ alignment: int = 32
235
+ expected_eof: Optional[int] = None
236
+ overlay_bytes: int = 0
237
+ overlay_entropy: float = 0.0
238
+ overlay_magic: Optional[str] = None
239
+ slack_nonzero_bytes: int = 0
240
+ duplicate_keys: list[str] = field(default_factory=list)
241
+ template_sha256: Optional[str] = None
242
+ template_findings: list[TemplateFinding] = field(default_factory=list)
243
+ error: Optional[str] = None
244
+
245
+ def raise_to(self, verdict: str, reason: str) -> None:
246
+ if _RANK[verdict] > _RANK.get(self.verdict, 0):
247
+ self.verdict = verdict
248
+ self.reasons.append(reason)
249
+
250
+ def to_dict(self) -> dict:
251
+ return asdict(self)
252
+
253
+
254
+ def _hash_file(path: str) -> str:
255
+ h = hashlib.sha256()
256
+ with open(path, "rb") as f:
257
+ for chunk in iter(lambda: f.read(8 * 1024 * 1024), b""):
258
+ h.update(chunk)
259
+ return h.hexdigest()
260
+
261
+
262
+ def scan_gguf(path: str, hash_file: bool = True) -> ModelScanResult:
263
+ """Structural + template scan of one GGUF file. Never executes or renders anything."""
264
+ r = ModelScanResult(path=path)
265
+ try:
266
+ r.file_size = os.path.getsize(path)
267
+ with open(path, "rb") as f:
268
+ _scan(f, r)
269
+ except _Bad as e:
270
+ # A finding made before the parse failed (a poisoned template, say) stands:
271
+ # ERROR only replaces CLEAN, never a verdict already earned.
272
+ r.error = str(e)
273
+ if r.verdict == CLEAN:
274
+ r.verdict = ERROR
275
+ return r
276
+ except OSError as e:
277
+ r.verdict, r.error = ERROR, f"{type(e).__name__}: {e}"
278
+ return r
279
+ if hash_file:
280
+ r.file_sha256 = _hash_file(path)
281
+ return r
282
+
283
+
284
+ def _scan(f, r: ModelScanResult) -> None:
285
+ rd = _R(f)
286
+ if f.read(4) != b"GGUF":
287
+ raise _Bad("not a GGUF file")
288
+ (ver,) = rd.u("I")
289
+ if ver not in (2, 3):
290
+ raise _Bad(f"unsupported GGUF version {ver}")
291
+ r.gguf_version = ver
292
+ n_tensors, n_kv = rd.u("QQ")
293
+ if n_kv > _MAX_KV or n_tensors > _MAX_TENSORS:
294
+ raise _Bad(f"implausible counts (tensors={n_tensors}, kv={n_kv})")
295
+
296
+ seen: set[bytes] = set()
297
+ templates: list[bytes] = []
298
+ for _ in range(n_kv):
299
+ k = rd.s()
300
+ (t,) = rd.u("I")
301
+ keep = k in (b"general.alignment", b"general.architecture", b"general.name") or k.startswith(b"tokenizer.chat_template")
302
+ v = rd.value(t, keep)
303
+ if k in seen:
304
+ r.duplicate_keys.append(k.decode("utf-8", "replace"))
305
+ seen.add(k)
306
+ if k == b"general.alignment" and v is not None and len(v) == 4:
307
+ r.alignment = struct.unpack("<I", v)[0]
308
+ elif k == b"general.architecture" and isinstance(v, bytes):
309
+ r.architecture = v.decode("utf-8", "replace")
310
+ elif k == b"general.name" and isinstance(v, bytes):
311
+ r.name = v.decode("utf-8", "replace")
312
+ elif k.startswith(b"tokenizer.chat_template") and isinstance(v, bytes):
313
+ templates.append(v)
314
+
315
+ if r.alignment == 0 or r.alignment & (r.alignment - 1):
316
+ raise _Bad(f"general.alignment {r.alignment} is not a power of two")
317
+
318
+ spans: list[tuple[int, int]] = []
319
+ unknown = None
320
+ for _ in range(n_tensors):
321
+ rd.s()
322
+ (nd,) = rd.u("I")
323
+ if nd > 8:
324
+ raise _Bad(f"tensor with {nd} dims")
325
+ dims = rd.u("Q" * nd) if nd else ()
326
+ ty, off = rd.u("IQ")
327
+ n = 1
328
+ for d in dims:
329
+ n *= d
330
+ blk = _BLOCK.get(ty)
331
+ if blk is None:
332
+ unknown = ty
333
+ continue
334
+ spans.append((off, off + n // blk[0] * blk[1]))
335
+
336
+ header_end = f.tell()
337
+ data_start = (header_end + r.alignment - 1) // r.alignment * r.alignment
338
+
339
+ # -- template --
340
+ if templates:
341
+ tmpl = b"\n".join(templates)
342
+ r.template_sha256 = template_sha256(templates[0])
343
+ r.template_findings = scan_chat_template(tmpl.decode("utf-8", "replace"))
344
+ tv = template_verdict(r.template_findings)
345
+ if tv != CLEAN:
346
+ cats = ", ".join(sorted({x.category for x in r.template_findings if x.severity != "medium"}))
347
+ r.raise_to(tv, f"chat_template: {cats}")
348
+
349
+ if r.duplicate_keys:
350
+ r.raise_to(SUSPICIOUS, f"duplicate metadata keys: {', '.join(r.duplicate_keys[:5])}")
351
+ if r.alignment > 4096:
352
+ r.raise_to(SUSPICIOUS, f"general.alignment {r.alignment} (normal is 32) leaves room for hidden data")
353
+
354
+ # -- padding slack: header -> data start, and every inter-tensor gap --
355
+ gaps = [(header_end, data_start)]
356
+ spans.sort()
357
+ for (a, b), (c, _) in zip(spans, spans[1:]):
358
+ if c > b:
359
+ gaps.append((data_start + b, data_start + c))
360
+ for a, b in gaps:
361
+ if b <= a:
362
+ continue
363
+ f.seek(a)
364
+ chunk = f.read(min(b - a, _GAP_READ_CAP))
365
+ r.slack_nonzero_bytes += len(chunk) - chunk.count(0)
366
+ if r.slack_nonzero_bytes:
367
+ sev = MALICIOUS if r.slack_nonzero_bytes > 16 else SUSPICIOUS
368
+ r.raise_to(sev, f"{r.slack_nonzero_bytes} non-zero bytes in alignment padding")
369
+
370
+ # -- overlay after the last tensor --
371
+ if unknown is not None:
372
+ r.raise_to(SUSPICIOUS, f"unknown tensor type {unknown}: end of data not computable, overlay not checked")
373
+ return
374
+ # No tensors (vocab-only files): the data section is empty, and writers differ on
375
+ # whether they pad out to it. Either is fine; the padding was checked as slack above.
376
+ r.expected_eof = data_start + max(e for _, e in spans) if spans else min(data_start, r.file_size)
377
+ r.overlay_bytes = r.file_size - r.expected_eof
378
+ if r.overlay_bytes < 0:
379
+ raise _Bad(f"file is {-r.overlay_bytes} bytes shorter than its tensors (truncated download?)")
380
+ if r.overlay_bytes:
381
+ f.seek(r.expected_eof)
382
+ sample = f.read(min(r.overlay_bytes, _OVERLAY_SAMPLE))
383
+ r.overlay_entropy = round(_entropy(sample), 3)
384
+ head = sample.lstrip(b"\x00")[:8]
385
+ r.overlay_magic = next((name for magic, name in _MAGICS if head.startswith(magic)), None)
386
+ if r.overlay_magic or r.overlay_bytes > 64 * 1024 or r.overlay_entropy > 7.0:
387
+ why = r.overlay_magic or (f"entropy {r.overlay_entropy}" if r.overlay_entropy > 7.0 else "size")
388
+ r.raise_to(MALICIOUS, f"{r.overlay_bytes} bytes after the last tensor ({why}) — never read by any runtime")
389
+ else:
390
+ r.raise_to(SUSPICIOUS, f"{r.overlay_bytes} bytes after the last tensor")
391
+
392
+
393
+ # ---------------------------------------------------------------------------
394
+ # Model references -> canonical IOC values
395
+ # ---------------------------------------------------------------------------
396
+
397
+ _SEG = r"[A-Za-z0-9][A-Za-z0-9._-]{0,95}"
398
+ _HF_HOSTS = ("huggingface.co", "hf.co", "www.huggingface.co")
399
+ _OLLAMA_HOSTS = ("ollama.com", "www.ollama.com", "registry.ollama.ai", "ollama.ai")
400
+
401
+
402
+ def canonical_model_refs(ref: str, default_hub: str = "huggingface") -> list[str]:
403
+ """Map a model reference to the lowercase repo + account URLs Nullcone stores.
404
+
405
+ Accepts https://huggingface.co/o/r[/resolve/main/x.gguf], hf.co/o/r[:tag],
406
+ huggingface.co/o/r, ollama.com/o/m[:tag], and a bare o/r (``default_hub``).
407
+ Official Ollama library models (``llama3.2``) have no owner and return [].
408
+ """
409
+ ref = (ref or "").strip().strip("'\"")
410
+ if not ref:
411
+ return []
412
+ if "://" not in ref and ref.split("/", 1)[0].lower() in _HF_HOSTS + _OLLAMA_HOSTS:
413
+ ref = "https://" + ref
414
+ if "://" in ref:
415
+ p = urlparse(ref)
416
+ host = (p.hostname or "").lower()
417
+ parts = [x for x in p.path.split("/") if x]
418
+ if host in _OLLAMA_HOSTS and parts[:1] == ["v2"]:
419
+ parts = parts[1:]
420
+ if host in _OLLAMA_HOSTS and parts[:1] == ["library"]:
421
+ return []
422
+ if host in _HF_HOSTS and parts[:1] in (["api"],):
423
+ parts = parts[2:] if len(parts) > 2 else []
424
+ if host in _HF_HOSTS and parts[:1] in (["datasets"], ["spaces"]):
425
+ parts = parts[1:]
426
+ hub = "huggingface" if host in _HF_HOSTS else "ollama" if host in _OLLAMA_HOSTS else None
427
+ if hub is None or len(parts) < 1:
428
+ return []
429
+ owner = parts[0]
430
+ repo = parts[1].split(":")[0] if len(parts) > 1 else None
431
+ else:
432
+ bits = ref.split("/")
433
+ if len(bits) != 2:
434
+ return []
435
+ owner, repo = bits[0], bits[1].split(":")[0]
436
+ hub = default_hub
437
+ if not re.fullmatch(_SEG, owner) or (repo is not None and not re.fullmatch(_SEG, repo)):
438
+ return []
439
+ base = "https://huggingface.co" if hub == "huggingface" else "https://ollama.com"
440
+ out = []
441
+ if repo:
442
+ out.append(f"{base}/{owner}/{repo}".lower())
443
+ out.append(f"{base}/{owner}".lower())
444
+ return out
@@ -265,10 +265,12 @@ _B_C2_CHAIN = ThreatBound(
265
265
  reason_template="C2 address in {ctx.chain_pattern} chain (depth {ctx.chain_depth}) — active interception.",
266
266
  )
267
267
 
268
- # B10: Medium severity — warn
268
+ # B10: Medium severity — warn. Also catches severity 7+ that high_severity_block
269
+ # declined for low confidence: until 2026-11-27 the upper bound was `< 7`, so an
270
+ # unverified severity-9 row returned ALLOW while an unverified severity-5 row WARNed.
269
271
  _B_MEDIUM_SEVERITY = ThreatBound(
270
272
  name="medium_severity_warn",
271
- condition=lambda ctx: 4 <= ctx.severity < 7 and not ctx.is_likely_fp,
273
+ condition=lambda ctx: ctx.severity >= 4 and not ctx.is_likely_fp,
272
274
  action=EnforcementAction.WARN,
273
275
  reason_template="Severity {ctx.severity}/10 — suspicious indicator.",
274
276
  )
@@ -13,7 +13,7 @@ import ipaddress
13
13
  import re
14
14
  from urllib.parse import urlparse
15
15
 
16
- from .curation import reserved_domain_reason, reserved_ip_reason
16
+ from .curation import code_identifier_reason, reserved_domain_reason, reserved_ip_reason
17
17
  from .models import IOCType
18
18
 
19
19
  # ---------------------------------------------------------------------------
@@ -140,7 +140,7 @@ def _validate_domain(value: str) -> str:
140
140
  # A documentation domain reached severity 7 on 2026-09-15 and the guard then
141
141
  # blocked code that touched it. Special-use names resolve to nothing an
142
142
  # attacker controls.
143
- reason = reserved_domain_reason(d)
143
+ reason = reserved_domain_reason(d) or code_identifier_reason(d)
144
144
  if reason:
145
145
  raise ValueError(f"{reason} — not a threat indicator")
146
146
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "nullcone"
7
- version = "0.1.2"
7
+ version = "0.1.3"
8
8
  description = "Distributed threat intelligence for AI agents — real-time IOC sharing via SpacetimeDB"
9
9
  readme = "README.md"
10
10
  license = { text = "Rising Sun License v1.0" }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes