nullcone 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.
nullcone/client.py ADDED
@@ -0,0 +1,278 @@
1
+ """
2
+ SpacetimeDB HTTP + WebSocket Client
3
+
4
+ Wraps SpacetimeDB's REST API for reducer calls and WebSocket API for
5
+ real-time table subscriptions. No SpacetimeDB Python SDK dependency —
6
+ uses httpx (already in project) and websockets.
7
+
8
+ SpacetimeDB HTTP API:
9
+ POST /v1/database/{db}/call/{reducer} → call a reducer
10
+ GET /v1/database/{db}/sql → run SQL query
11
+
12
+ SpacetimeDB WebSocket API:
13
+ ws://{host}/v1/subscribe/{db} → subscribe to table changes
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import json
19
+ import threading
20
+ from typing import Any, Callable, ClassVar, Optional
21
+
22
+ import httpx
23
+
24
+
25
+ class SpacetimeDBError(Exception):
26
+ pass
27
+
28
+
29
+ class SpacetimeDBClient:
30
+ """
31
+ Synchronous client for SpacetimeDB reducer calls and SQL queries.
32
+
33
+ For real-time subscriptions, use SpacetimeDBSubscriber (async/threaded).
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ base_url: str = "http://localhost:3000",
39
+ database: str = "nullcone",
40
+ token: Optional[str] = None,
41
+ timeout: float = 10.0,
42
+ ):
43
+ self.base_url = base_url.rstrip("/")
44
+ self.database = database
45
+ headers = {"Content-Type": "application/json"}
46
+ if token:
47
+ headers["Authorization"] = f"Bearer {token}"
48
+ self._http = httpx.Client(
49
+ base_url=self.base_url,
50
+ headers=headers,
51
+ timeout=timeout,
52
+ )
53
+
54
+ def call_reducer(self, reducer_name: str, *args: Any) -> dict[str, Any]:
55
+ """
56
+ Call a SpacetimeDB reducer with positional arguments.
57
+
58
+ SpacetimeDB expects args as a JSON array.
59
+ Returns the reducer response dict.
60
+ """
61
+ url = f"/v1/database/{self.database}/call/{reducer_name}"
62
+ payload = json.dumps(list(args))
63
+ resp = self._http.post(url, content=payload.encode())
64
+ if resp.status_code not in (200, 204):
65
+ raise SpacetimeDBError(
66
+ f"Reducer '{reducer_name}' failed [{resp.status_code}]: {resp.text}"
67
+ )
68
+ if resp.content:
69
+ return resp.json()
70
+ return {}
71
+
72
+ def sql(self, query: str) -> list[dict[str, Any]]:
73
+ """
74
+ Execute a SQL SELECT query against SpacetimeDB.
75
+
76
+ Returns list of row dicts.
77
+ """
78
+ url = f"/v1/database/{self.database}/sql"
79
+ # SpacetimeDB 2.0 expects plain-text SQL body
80
+ resp = self._http.post(
81
+ url,
82
+ content=query.encode(),
83
+ headers={"Content-Type": "text/plain"},
84
+ )
85
+ if resp.status_code != 200:
86
+ raise SpacetimeDBError(
87
+ f"SQL query failed [{resp.status_code}]: {resp.text}"
88
+ )
89
+ data = resp.json()
90
+ # Response: [{"schema": {"elements": [{"name": {"some": col}, ...}]}, "rows": [[v,...], ...]}]
91
+ if not data:
92
+ return []
93
+ result = data[0]
94
+ cols = [e["name"]["some"] for e in result["schema"]["elements"]]
95
+ return [dict(zip(cols, row)) for row in result.get("rows", [])]
96
+
97
+ def health(self) -> bool:
98
+ """Return True if the SpacetimeDB instance is reachable."""
99
+ try:
100
+ # SpacetimeDB 2.x moved the health endpoint to /v1/health
101
+ for path in ("/v1/health", "/health"):
102
+ resp = self._http.get(path)
103
+ if resp.status_code == 200:
104
+ return True
105
+ return False
106
+ except Exception:
107
+ return False
108
+
109
+ def close(self):
110
+ self._http.close()
111
+
112
+ def __enter__(self):
113
+ return self
114
+
115
+ def __exit__(self, *_):
116
+ self.close()
117
+
118
+
119
+ class SpacetimeDBSubscriber:
120
+ """
121
+ Threaded WebSocket subscriber for real-time table change notifications.
122
+
123
+ Usage:
124
+ sub = SpacetimeDBSubscriber("ws://localhost:3000", "nullcone")
125
+ sub.subscribe(
126
+ "SELECT * FROM threat_signature",
127
+ on_insert=lambda row: print("New IOC:", row),
128
+ on_update=lambda row: print("Updated IOC:", row),
129
+ )
130
+ sub.start()
131
+ # ... later ...
132
+ sub.stop()
133
+ """
134
+
135
+ def __init__(
136
+ self,
137
+ ws_url: str = "ws://localhost:3000",
138
+ database: str = "nullcone",
139
+ token: Optional[str] = None,
140
+ ):
141
+ self.ws_url = ws_url.rstrip("/")
142
+ self.database = database
143
+ self.token = token
144
+ self._queries: list[dict] = []
145
+ self._thread: Optional[threading.Thread] = None
146
+ self._stop_event = threading.Event()
147
+
148
+ def subscribe(
149
+ self,
150
+ sql_query: str,
151
+ on_insert: Optional[Callable[[dict], None]] = None,
152
+ on_update: Optional[Callable[[dict], None]] = None,
153
+ on_delete: Optional[Callable[[dict], None]] = None,
154
+ ) -> None:
155
+ """Register a SQL subscription with callbacks for row changes."""
156
+ self._queries.append({
157
+ "query": sql_query,
158
+ "on_insert": on_insert,
159
+ "on_update": on_update,
160
+ "on_delete": on_delete,
161
+ })
162
+
163
+ def start(self) -> None:
164
+ """Start the subscription listener in a background thread."""
165
+ self._stop_event.clear()
166
+ self._thread = threading.Thread(target=self._run, daemon=True)
167
+ self._thread.start()
168
+
169
+ def stop(self) -> None:
170
+ """Signal the background thread to stop and wait for it."""
171
+ self._stop_event.set()
172
+ if self._thread:
173
+ self._thread.join(timeout=5.0)
174
+
175
+ # Column names per table — used to convert array rows to dicts in TransactionUpdateLight
176
+ _TABLE_COLUMNS: ClassVar[dict[str, list[str]]] = {
177
+ "threat_signature": [
178
+ "id", "ioc_type", "value_hash", "value", "meta_compressed", "threat_symbol",
179
+ "family_name", "severity", "confidence", "source_agent_id",
180
+ "first_seen", "last_seen", "detection_count", "false_positive_votes", "tags",
181
+ ],
182
+ "agent_registration": [
183
+ "agent_id", "hostname", "os_type", "capabilities",
184
+ "registered_at", "last_seen", "ioc_submissions", "detections_reported",
185
+ ],
186
+ "malware_family": [
187
+ "id", "name", "aliases", "threat_level", "description",
188
+ "first_seen", "ioc_count", "category",
189
+ ],
190
+ "threat_event": [
191
+ "id", "signature_id", "agent_id", "action_taken", "context_json", "timestamp",
192
+ ],
193
+ }
194
+
195
+ def _run(self) -> None:
196
+ """Thread entry: run async event loop for WebSocket."""
197
+ try:
198
+ asyncio.run(self._listen())
199
+ except Exception:
200
+ pass
201
+
202
+ async def _listen(self) -> None:
203
+ """WebSocket listener — receives SpacetimeDB transaction updates."""
204
+ try:
205
+ import websockets
206
+ except ImportError:
207
+ raise RuntimeError("pip install websockets to use subscriptions")
208
+
209
+ # SpacetimeDB 2.0: endpoint is /v1/database/{db}/subscribe, subprotocol v1.json.spacetimedb
210
+ url = f"{self.ws_url}/v1/database/{self.database}/subscribe"
211
+ headers = {}
212
+ if self.token:
213
+ headers["Authorization"] = f"Bearer {self.token}"
214
+
215
+ subscribe_msg = json.dumps({
216
+ "Subscribe": {
217
+ "query_strings": [q["query"] for q in self._queries],
218
+ "request_id": 1,
219
+ }
220
+ })
221
+
222
+ try:
223
+ async with websockets.connect(
224
+ url,
225
+ subprotocols=["v1.json.spacetimedb"],
226
+ additional_headers=headers,
227
+ ) as ws:
228
+ # Drain initial IdentityToken message
229
+ await ws.recv()
230
+ await ws.send(subscribe_msg)
231
+ while not self._stop_event.is_set():
232
+ try:
233
+ raw = await asyncio.wait_for(ws.recv(), timeout=1.0)
234
+ except asyncio.TimeoutError:
235
+ continue
236
+ self._dispatch(json.loads(raw))
237
+ except Exception:
238
+ pass
239
+
240
+ def _row_to_dict(self, table_name: str, row: Any) -> dict:
241
+ """Convert an array row to a dict using known column names for the table."""
242
+ if isinstance(row, dict):
243
+ return row
244
+ cols = self._TABLE_COLUMNS.get(table_name)
245
+ if cols:
246
+ return dict(zip(cols, row))
247
+ return {}
248
+
249
+ def _dispatch(self, msg: dict) -> None:
250
+ """Route incoming SpacetimeDB transaction update to registered callbacks."""
251
+ # InitialSubscription fires on subscribe — skip (historical data, not live events)
252
+ if "InitialSubscription" in msg:
253
+ return
254
+
255
+ # TransactionUpdateLight carries live inserts/deletes from reducers
256
+ tx = msg.get("TransactionUpdateLight", {})
257
+ if not tx:
258
+ return
259
+
260
+ for table in tx.get("update", {}).get("tables", []):
261
+ table_name = table.get("table_name", "")
262
+ for upd in table.get("updates", []):
263
+ for insert_str in upd.get("inserts", []):
264
+ row = self._row_to_dict(table_name, json.loads(insert_str))
265
+ for query_handler in self._queries:
266
+ if query_handler["on_insert"]:
267
+ try:
268
+ query_handler["on_insert"]({"table": table_name, "row": row})
269
+ except Exception:
270
+ pass
271
+ for delete_str in upd.get("deletes", []):
272
+ row = self._row_to_dict(table_name, json.loads(delete_str))
273
+ for query_handler in self._queries:
274
+ if query_handler["on_delete"]:
275
+ try:
276
+ query_handler["on_delete"]({"table": table_name, "row": row})
277
+ except Exception:
278
+ pass
nullcone/compressor.py ADDED
@@ -0,0 +1,421 @@
1
+ """
2
+ IOC Metadata Compressor
3
+
4
+ Compresses IOC metadata into a compact binary envelope:
5
+ - Fixed 2-byte header: SecuritySymbol THREAT_IOC (0xF3 0x5B)
6
+ - Version byte
7
+ - Field count byte
8
+ - Per field: varies by key code range (see below)
9
+ - Optional gzip-compressed context appended at end
10
+
11
+ Field key code ranges
12
+ ---------------------
13
+ 0x01–0x1F variable-length [key][2B-len][value]
14
+ 0x20–0x7F family code [key] only — key code encodes family name (0 extra bytes)
15
+ 0x80–0x85 compact binary [key][fixed N bytes] — hash/IP as raw binary, no length prefix
16
+ 0xC0–0xEF tag code [key] only — key code encodes one tag string (0 extra bytes)
17
+ 0xFF context marker (not a field, terminates field list)
18
+
19
+ Compact binary fields (0x80–0x85) replace both the ioc_type and value fields
20
+ with a single code that implies the type and encodes the value as raw bytes:
21
+ 0x80 sha256_bin 32 bytes → IOCType.SHA256
22
+ 0x81 sha1_bin 20 bytes → IOCType.SHA1
23
+ 0x82 md5_bin 16 bytes → IOCType.MD5
24
+ 0x83 ipv4_bin 4 bytes → IOCType.IP (dotted-decimal IPv4)
25
+ 0x84 ipv6_bin 16 bytes → IOCType.IP (compressed IPv6)
26
+ 0x85 imphash_bin 16 bytes → IOCType.IMPHASH
27
+
28
+ Family codes (0x20–0x7F) and tag codes (0xC0–0xEF) use the key byte itself
29
+ as the data — no length prefix, no value bytes. Unknown families/tags fall
30
+ back to variable-length UTF-8 fields (0x05 / 0x06).
31
+
32
+ The compressed envelope is stored in SpacetimeDB's meta_compressed column
33
+ and can be decoded without any external dependencies.
34
+ """
35
+ from __future__ import annotations
36
+
37
+ import gzip
38
+ import socket
39
+ import struct
40
+ from typing import Any
41
+
42
+ from .models import IOC, IOCType
43
+
44
+ # SecuritySymbol THREAT_IOC = 0xF35B (2 bytes: 0xF3, 0x5B)
45
+ THREAT_IOC_HEADER = bytes([0xF3, 0x5B])
46
+ # SecuritySymbol THREAT_PATTERN = 0xF35C for YARA rules
47
+ THREAT_PATTERN_HEADER = bytes([0xF3, 0x5C])
48
+
49
+ FORMAT_VERSION = 0x01
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # Standard variable-length field keys (0x01–0x1F)
53
+ # ---------------------------------------------------------------------------
54
+ _KEY = {
55
+ "ioc_type": 0x01, # 1-byte type code (see _TYPE_CODE)
56
+ "value": 0x02, # UTF-8 string fallback for non-binary types
57
+ "severity": 0x03, # 2 bytes packed: [severity u8][confidence u8]
58
+ "family": 0x05, # UTF-8 fallback for families not in code table
59
+ "tags": 0x06, # comma-joined UTF-8 fallback for unknown tags
60
+ "source": 0x07, # source sensor/agent identifier
61
+ }
62
+ _KEY_INV = {v: k for k, v in _KEY.items()}
63
+
64
+ # IOC type codes — 1 byte replaces the full type string
65
+ _TYPE_CODE = {
66
+ IOCType.MD5: 0x01,
67
+ IOCType.SHA1: 0x02,
68
+ IOCType.SHA256: 0x03,
69
+ IOCType.IP: 0x04,
70
+ IOCType.IP_PORT: 0x05,
71
+ IOCType.DOMAIN: 0x06,
72
+ IOCType.URL: 0x07,
73
+ IOCType.YARA: 0x08,
74
+ IOCType.EMAIL: 0x09,
75
+ IOCType.MUTEX: 0x0A,
76
+ IOCType.REGISTRY: 0x0B,
77
+ IOCType.FILEPATH: 0x0C,
78
+ IOCType.ASN: 0x0D,
79
+ IOCType.JA3: 0x0E,
80
+ IOCType.IMPHASH: 0x0F,
81
+ IOCType.CVE: 0x10,
82
+ IOCType.PROMPT: 0x11,
83
+ IOCType.SKILL: 0x12,
84
+ }
85
+ _TYPE_CODE_INV = {v: k.value for k, v in _TYPE_CODE.items()}
86
+
87
+ # ---------------------------------------------------------------------------
88
+ # Compact binary field codes (0x80–0x85)
89
+ # Format: [key][fixed N bytes] — no length prefix.
90
+ # Each code implies both the IOC type and that the value is raw binary.
91
+ # ---------------------------------------------------------------------------
92
+ _COMPACT_SIZES: dict[int, int] = {
93
+ 0x80: 32, # sha256_bin → hash_sha256
94
+ 0x81: 20, # sha1_bin → hash_sha1
95
+ 0x82: 16, # md5_bin → hash_md5
96
+ 0x83: 4, # ipv4_bin → ip (inet_aton / inet_ntoa)
97
+ 0x84: 16, # ipv6_bin → ip (inet_pton AF_INET6)
98
+ 0x85: 16, # imphash_bin → imphash
99
+ }
100
+ _COMPACT_IOC_TYPE: dict[int, str] = {
101
+ 0x80: "hash_sha256",
102
+ 0x81: "hash_sha1",
103
+ 0x82: "hash_md5",
104
+ 0x83: "ip",
105
+ 0x84: "ip",
106
+ 0x85: "imphash",
107
+ }
108
+
109
+ # ---------------------------------------------------------------------------
110
+ # Family name codes (0x20–0x7F, 96 slots)
111
+ # Top 96 families by prevalence — ordered to keep the most common at lowest
112
+ # codes for potential future prefix compression.
113
+ # ---------------------------------------------------------------------------
114
+ _FAMILY_NAMES_96 = [
115
+ # Loaders / banking trojans
116
+ "Emotet", "TrickBot", "QakBot", "IcedID", "Dridex", "Ursnif",
117
+ # C2 frameworks
118
+ "Cobalt Strike", "Metasploit", "Sliver", "Brute Ratel",
119
+ # Stealers
120
+ "RedLine", "Raccoon", "Vidar", "Agent Tesla", "FormBook", "Lumma",
121
+ "StealC", "Rhadamanthys", "Aurora Stealer", "Atomic Stealer",
122
+ "Azorult", "Snake Keylogger",
123
+ # RATs
124
+ "AsyncRAT", "NjRAT", "Remcos", "DarkComet", "XWorm", "QuasarRAT",
125
+ "Warzone RAT", "DCRat", "NanoCore", "PlugX",
126
+ # Nation-state implants
127
+ "Turla", "SUNBURST", "Kimsuky",
128
+ # Ransomware
129
+ "LockBit", "BlackCat", "Conti", "Black Basta", "WannaCry",
130
+ "REvil", "Clop", "Hive", "Akira", "RansomHub", "Play", "Royal",
131
+ "DarkSide", "Maze", "Dharma", "NotPetya",
132
+ # Wipers
133
+ "HermeticWiper", "WhisperGate", "Shamoon", "CaddyWiper", "Industroyer",
134
+ # Botnets
135
+ "Mirai", "Moobot", "XorDDoS", "BotenaGo", "Cyclops Blink",
136
+ # Droppers / loaders
137
+ "GuLoader", "BazarLoader", "Bumblebee", "Pikabot", "DarkGate",
138
+ "SocGholish", "SmokeLoader", "PrivateLoader",
139
+ # Ransomware (continued)
140
+ "Cuba", "Medusa", "BianLian", "Babuk", "BlackMatter", "Egregor",
141
+ "AvosLocker", "Rhysida", "Hunters International",
142
+ # Banking / fraud
143
+ "Zeus", "GameOver Zeus", "Zloader", "Danabot",
144
+ # APT toolkits
145
+ "Carbanak", "Winnti", "OceanLotus", "Gamaredon",
146
+ # APT groups
147
+ "APT29", "APT28", "Sandworm", "Lazarus Group",
148
+ "Volt Typhoon", "Salt Typhoon", "MuddyWater",
149
+ # Additional stealers
150
+ "Mars Stealer", "Phemedrone", "CryptBot",
151
+ ]
152
+ assert len(_FAMILY_NAMES_96) == 96, f"Expected 96 family names, got {len(_FAMILY_NAMES_96)}"
153
+
154
+ _FAMILY_CODE: dict[str, int] = {name: 0x20 + i for i, name in enumerate(_FAMILY_NAMES_96)}
155
+ _FAMILY_CODE_INV: dict[int, str] = {0x20 + i: name for i, name in enumerate(_FAMILY_NAMES_96)}
156
+
157
+ # ---------------------------------------------------------------------------
158
+ # Tag codes (0xC0–0xEF, 48 slots)
159
+ # Individual tags encoded as single bytes. Multiple tag codes can appear in
160
+ # sequence. Tags not in this table fall back to comma-joined UTF-8 (key 0x06).
161
+ # ---------------------------------------------------------------------------
162
+ _TAG_NAMES_48 = [
163
+ # Threat category
164
+ "c2", "phishing", "ransomware", "loader", "stealer", "beacon",
165
+ "trojan", "botnet", "rat", "dropper", "worm", "apt",
166
+ "backdoor", "credential-theft", "data-exfiltration", "lateral-movement",
167
+ "persistence", "privilege-escalation", "defense-evasion",
168
+ "spyware", "keylogger", "adware", "cryptominer", "banking",
169
+ # Platform / vector
170
+ "mobile", "iot", "macro", "typosquat", "fast-flux", "gate",
171
+ # TTPs
172
+ "double-extortion", "process-injection", "powershell",
173
+ "telnet", "smb", "rdp",
174
+ # Delivery
175
+ "malspam", "drive-by", "supply-chain", "zero-day", "exploit",
176
+ # File types
177
+ "lnk", "iso", "zip", "pdf", "office",
178
+ # Network
179
+ "tls", "cobalt-strike",
180
+ ]
181
+ assert len(_TAG_NAMES_48) == 48, f"Expected 48 tag names, got {len(_TAG_NAMES_48)}"
182
+
183
+ _TAG_CODE: dict[str, int] = {tag: 0xC0 + i for i, tag in enumerate(_TAG_NAMES_48)}
184
+ _TAG_CODE_INV: dict[int, str] = {0xC0 + i: tag for i, tag in enumerate(_TAG_NAMES_48)}
185
+
186
+
187
+ # ---------------------------------------------------------------------------
188
+ # Encoding helpers
189
+ # ---------------------------------------------------------------------------
190
+
191
+ def _encode_field(key_code: int, value: bytes) -> bytes:
192
+ """Variable-length field: [1-byte key] + [2-byte big-endian length] + [value]"""
193
+ return bytes([key_code]) + struct.pack(">H", len(value)) + value
194
+
195
+
196
+ def _try_compact_binary(ioc: IOC) -> bytes | None:
197
+ """
198
+ Attempt to encode (ioc_type + value) as a single compact binary field.
199
+
200
+ Handles SHA256, SHA1, MD5, IMPHASH (hex→raw bytes) and IPv4/IPv6 (text→4/16 bytes).
201
+ Returns the compact field bytes if applicable, None otherwise.
202
+ The compact code replaces both the 0x01 ioc_type and 0x02 value fields.
203
+ """
204
+ v = ioc.value.strip()
205
+ t = ioc.ioc_type
206
+ try:
207
+ if t == IOCType.SHA256 and len(v) == 64:
208
+ return bytes([0x80]) + bytes.fromhex(v)
209
+ if t == IOCType.SHA1 and len(v) == 40:
210
+ return bytes([0x81]) + bytes.fromhex(v)
211
+ if t == IOCType.MD5 and len(v) == 32:
212
+ return bytes([0x82]) + bytes.fromhex(v)
213
+ if t == IOCType.IMPHASH and len(v) == 32:
214
+ return bytes([0x85]) + bytes.fromhex(v)
215
+ if t == IOCType.IP:
216
+ try:
217
+ return bytes([0x83]) + socket.inet_aton(v) # IPv4 → 4 bytes
218
+ except OSError:
219
+ return bytes([0x84]) + socket.inet_pton(socket.AF_INET6, v) # IPv6 → 16 bytes
220
+ except (ValueError, OSError):
221
+ pass
222
+ return None
223
+
224
+
225
+ # ---------------------------------------------------------------------------
226
+ # Public API
227
+ # ---------------------------------------------------------------------------
228
+
229
+ def compress(ioc: IOC) -> bytes:
230
+ """
231
+ Compress IOC metadata into a binary metadata envelope.
232
+
233
+ Encoding precedence per field:
234
+ - ioc_type + value: compact binary (0x80–0x85) when applicable,
235
+ else standard variable-length (0x01 + 0x02)
236
+ - family: 1-byte code (0x20–0x7F) when in table, else UTF-8 (0x05)
237
+ - each tag: 1-byte code (0xC0–0xEF) when in table; remainder as
238
+ comma-joined UTF-8 fallback (0x06)
239
+ - severity+confidence: always packed as 2 bytes under key 0x03
240
+ - source: omitted when "local", else UTF-8 (0x07)
241
+ - context: gzip-compressed, appended after fields with 0xFF marker
242
+
243
+ Format:
244
+ [0xF3][0x5B or 0x5C] SecuritySymbol header (2 bytes)
245
+ [0x01] format version (1 byte)
246
+ [N] field count (1 byte)
247
+ [field_0 .. field_N-1] encoded fields
248
+ [0xFF][4B len][gzip bytes] context block (if context non-empty)
249
+ """
250
+ header = THREAT_PATTERN_HEADER if ioc.ioc_type == IOCType.YARA else THREAT_IOC_HEADER
251
+ fields: list[bytes] = []
252
+
253
+ # --- ioc_type + value ---
254
+ compact = _try_compact_binary(ioc)
255
+ if compact:
256
+ fields.append(compact)
257
+ else:
258
+ type_code = _TYPE_CODE.get(ioc.ioc_type, 0xFF)
259
+ fields.append(_encode_field(_KEY["ioc_type"], bytes([type_code])))
260
+ fields.append(_encode_field(_KEY["value"], ioc.value.encode("utf-8", errors="replace")))
261
+
262
+ # --- severity + confidence packed ---
263
+ fields.append(_encode_field(_KEY["severity"], struct.pack("BB", ioc.severity, ioc.confidence)))
264
+
265
+ # --- family ---
266
+ if ioc.family_hint:
267
+ fam_code = _FAMILY_CODE.get(ioc.family_hint)
268
+ if fam_code is not None:
269
+ fields.append(bytes([fam_code])) # 1-byte implicit
270
+ else:
271
+ fields.append(_encode_field(_KEY["family"], ioc.family_hint.encode("utf-8")))
272
+
273
+ # --- tags ---
274
+ if ioc.tags:
275
+ unknown_tags: list[str] = []
276
+ for tag in ioc.tags:
277
+ tag_code = _TAG_CODE.get(tag)
278
+ if tag_code is not None:
279
+ fields.append(bytes([tag_code])) # 1-byte implicit
280
+ else:
281
+ unknown_tags.append(tag)
282
+ if unknown_tags:
283
+ fields.append(_encode_field(_KEY["tags"], ",".join(unknown_tags).encode("utf-8")))
284
+
285
+ # --- source ---
286
+ if ioc.source and ioc.source != "local":
287
+ fields.append(_encode_field(_KEY["source"], ioc.source.encode("utf-8")))
288
+
289
+ # --- assemble ---
290
+ body = header + bytes([FORMAT_VERSION, len(fields)])
291
+ for f in fields:
292
+ body += f
293
+
294
+ # --- context: gzip-compressed with 0xFF marker ---
295
+ if ioc.context:
296
+ ctx_gz = gzip.compress(ioc.context.encode("utf-8"), compresslevel=6)
297
+ body += bytes([0xFF]) + struct.pack(">I", len(ctx_gz)) + ctx_gz
298
+
299
+ return body
300
+
301
+
302
+ def decompress(data: bytes) -> dict[str, Any]:
303
+ """
304
+ Decode a binary IOC envelope back to a plain dict.
305
+
306
+ Returns keys: ioc_type, value, severity, confidence, family, tags (list),
307
+ source, context (optional).
308
+ Unknown key codes are skipped safely (length-prefixed fields skip N bytes;
309
+ implicit codes are 1 byte total so always safe to skip).
310
+ """
311
+ if len(data) < 4:
312
+ raise ValueError("Data too short")
313
+
314
+ header = data[:2]
315
+ if header not in (THREAT_IOC_HEADER, THREAT_PATTERN_HEADER):
316
+ raise ValueError(f"Invalid header: {header.hex()}")
317
+
318
+ version = data[2]
319
+ if version != FORMAT_VERSION:
320
+ raise ValueError(f"Unsupported version: {version}")
321
+
322
+ field_count = data[3]
323
+ offset = 4
324
+ result: dict[str, Any] = {}
325
+ tags_list: list[str] = []
326
+
327
+ for _ in range(field_count):
328
+ if offset >= len(data):
329
+ break
330
+ key_code = data[offset]
331
+ offset += 1
332
+
333
+ # -- family code (0x20–0x7F): 1 byte total, no extra bytes --
334
+ if 0x20 <= key_code <= 0x7F:
335
+ result["family"] = _FAMILY_CODE_INV.get(key_code, "")
336
+
337
+ # -- tag code (0xC0–0xEF): 1 byte total, no extra bytes --
338
+ elif 0xC0 <= key_code <= 0xEF:
339
+ tag = _TAG_CODE_INV.get(key_code)
340
+ if tag:
341
+ tags_list.append(tag)
342
+
343
+ # -- compact binary (0x80–0x85): fixed N bytes, no length prefix --
344
+ elif key_code in _COMPACT_SIZES:
345
+ size = _COMPACT_SIZES[key_code]
346
+ if offset + size > len(data):
347
+ break
348
+ value_bytes = data[offset:offset + size]
349
+ offset += size
350
+ result["ioc_type"] = _COMPACT_IOC_TYPE[key_code]
351
+ if key_code == 0x83:
352
+ result["value"] = socket.inet_ntoa(value_bytes)
353
+ elif key_code == 0x84:
354
+ result["value"] = socket.inet_ntop(socket.AF_INET6, value_bytes)
355
+ else:
356
+ result["value"] = value_bytes.hex()
357
+
358
+ # -- variable-length (0x01–0x1F and any unrecognised): [key][2B len][value] --
359
+ else:
360
+ if offset + 2 > len(data):
361
+ break
362
+ length = struct.unpack(">H", data[offset:offset + 2])[0]
363
+ offset += 2
364
+ if offset + length > len(data):
365
+ break
366
+ value_bytes = data[offset:offset + length]
367
+ offset += length
368
+
369
+ key_name = _KEY_INV.get(key_code)
370
+ if key_name == "ioc_type":
371
+ result["ioc_type"] = _TYPE_CODE_INV.get(value_bytes[0], "unknown")
372
+ elif key_name == "severity":
373
+ result["severity"] = value_bytes[0]
374
+ result["confidence"] = value_bytes[1] if len(value_bytes) > 1 else 0
375
+ elif key_name in ("value", "family", "source"):
376
+ result[key_name] = value_bytes.decode("utf-8", errors="replace")
377
+ elif key_name == "tags":
378
+ # UTF-8 fallback tags (unknown tags not in code table)
379
+ for t in value_bytes.decode("utf-8").split(","):
380
+ if t:
381
+ tags_list.append(t)
382
+ # Unknown key codes with variable-length format are skipped safely
383
+ # (we already advanced offset past the value bytes above)
384
+
385
+ if tags_list:
386
+ result["tags"] = tags_list
387
+
388
+ # -- context block: 0xFF marker + 4-byte length + gzip bytes --
389
+ if offset < len(data) and data[offset] == 0xFF:
390
+ offset += 1
391
+ if offset + 4 <= len(data):
392
+ ctx_len = struct.unpack(">I", data[offset:offset + 4])[0]
393
+ offset += 4
394
+ ctx_gz = data[offset:offset + ctx_len]
395
+ try:
396
+ result["context"] = gzip.decompress(ctx_gz).decode("utf-8")
397
+ except Exception:
398
+ result["context"] = ""
399
+
400
+ return result
401
+
402
+
403
+ def compression_ratio(ioc: IOC) -> float:
404
+ """Return compression ratio: raw_json_bytes / compressed_bytes."""
405
+ import json
406
+ raw = len(json.dumps(ioc.to_dict()).encode())
407
+ compressed = len(compress(ioc))
408
+ return raw / max(compressed, 1)
409
+
410
+
411
+ # SecuritySymbol bytes for threat operations — used in threat_symbol column
412
+ THREAT_SYMBOL_IOC = bytes([0xF3, 0x5B]) # THREAT_IOC
413
+ THREAT_SYMBOL_PATTERN = bytes([0xF3, 0x5C]) # THREAT_PATTERN
414
+ THREAT_SYMBOL_ANOMALY = bytes([0xF3, 0x5D]) # THREAT_ANOMALY
415
+
416
+
417
+ def threat_symbol_for(ioc: IOC) -> bytes:
418
+ """Return the 2-byte SecuritySymbol most appropriate for this IOC type."""
419
+ if ioc.ioc_type == IOCType.YARA:
420
+ return THREAT_SYMBOL_PATTERN
421
+ return THREAT_SYMBOL_IOC