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/__init__.py +43 -0
- nullcone/agent.py +442 -0
- nullcone/classifier.py +2361 -0
- nullcone/cli.py +796 -0
- nullcone/client.py +278 -0
- nullcone/compressor.py +421 -0
- nullcone/ei_client.py +183 -0
- nullcone/models.py +206 -0
- nullcone/py.typed +0 -0
- nullcone/sensor.py +542 -0
- nullcone-0.1.0.data/data/nullcone/py.typed +0 -0
- nullcone-0.1.0.dist-info/METADATA +213 -0
- nullcone-0.1.0.dist-info/RECORD +16 -0
- nullcone-0.1.0.dist-info/WHEEL +4 -0
- nullcone-0.1.0.dist-info/entry_points.txt +2 -0
- nullcone-0.1.0.dist-info/licenses/LICENSE +21 -0
nullcone/sensor.py
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Agent Threat Sensor
|
|
3
|
+
|
|
4
|
+
Lightweight, embeddable threat detection sensor for Python agents.
|
|
5
|
+
Any agent that imports this module gains:
|
|
6
|
+
|
|
7
|
+
1. OBSERVE — hash files, report network connections, DNS queries
|
|
8
|
+
2. CHECK — instant IOC lookup against the shared SpacetimeDB
|
|
9
|
+
3. SUBSCRIBE— real-time push when any other agent reports a new threat
|
|
10
|
+
|
|
11
|
+
The real power: when Agent A (honeypot) on machine 1 observes a new C2 IP
|
|
12
|
+
and calls sensor.observe_connection("185.220.101.34", 4444), all agents
|
|
13
|
+
subscribed via sensor.subscribe() on every other machine receive the alert
|
|
14
|
+
over WebSocket in under 100ms — before they've ever seen that IP.
|
|
15
|
+
|
|
16
|
+
Quick start:
|
|
17
|
+
from nullcone.sensor import ThreatSensor
|
|
18
|
+
|
|
19
|
+
sensor = ThreatSensor(
|
|
20
|
+
server="http://localhost:3000",
|
|
21
|
+
agent_id="my-agent-prod-01",
|
|
22
|
+
)
|
|
23
|
+
sensor.register()
|
|
24
|
+
|
|
25
|
+
# Subscribe to real-time threat feed
|
|
26
|
+
sensor.subscribe(lambda sig: print(f"THREAT: {sig.ioc_type} {sig.value[:40]}"))
|
|
27
|
+
|
|
28
|
+
# Observe a file before executing it
|
|
29
|
+
verdict = sensor.observe_file("/tmp/suspicious.exe")
|
|
30
|
+
if verdict.is_threat:
|
|
31
|
+
print(f"BLOCKED: {verdict.family} severity={verdict.severity}")
|
|
32
|
+
|
|
33
|
+
# Observe an outbound connection
|
|
34
|
+
verdict = sensor.observe_connection("185.220.101.34", 4444)
|
|
35
|
+
|
|
36
|
+
# Observe a DNS query
|
|
37
|
+
verdict = sensor.observe_dns("updates-cdn.microsofts-store.com")
|
|
38
|
+
|
|
39
|
+
# Observe a URL before fetching
|
|
40
|
+
verdict = sensor.observe_url("http://malicious.example/payload.exe")
|
|
41
|
+
"""
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
import hashlib
|
|
45
|
+
import json
|
|
46
|
+
import os
|
|
47
|
+
import threading
|
|
48
|
+
import time
|
|
49
|
+
import urllib.parse
|
|
50
|
+
from dataclasses import dataclass, field
|
|
51
|
+
from pathlib import Path
|
|
52
|
+
from typing import Callable, Optional
|
|
53
|
+
|
|
54
|
+
import httpx
|
|
55
|
+
|
|
56
|
+
try:
|
|
57
|
+
import websockets
|
|
58
|
+
import asyncio
|
|
59
|
+
_HAS_WEBSOCKETS = True
|
|
60
|
+
except ImportError:
|
|
61
|
+
_HAS_WEBSOCKETS = False
|
|
62
|
+
|
|
63
|
+
SPACETIME_URL = "http://localhost:3000"
|
|
64
|
+
DATABASE = "nullcone"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# ---------------------------------------------------------------------------
|
|
68
|
+
# Result types
|
|
69
|
+
# ---------------------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class ThreatVerdict:
|
|
73
|
+
"""Result of a sensor observation check."""
|
|
74
|
+
ioc_type: str
|
|
75
|
+
value: str
|
|
76
|
+
is_known: bool # True if IOC is in the shared DB
|
|
77
|
+
is_threat: bool # True if severity >= threat_threshold
|
|
78
|
+
severity: int # 0-10
|
|
79
|
+
confidence: int # 0-100
|
|
80
|
+
family: str # malware family name, "" if unknown
|
|
81
|
+
detection_count: int
|
|
82
|
+
false_positive_votes: int
|
|
83
|
+
tags: str
|
|
84
|
+
signature_id: Optional[int] = None
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def is_likely_fp(self) -> bool:
|
|
88
|
+
"""Heuristic: likely false positive if FP votes > 20% of detections."""
|
|
89
|
+
if self.detection_count == 0:
|
|
90
|
+
return False
|
|
91
|
+
return (self.false_positive_votes / self.detection_count) > 0.20
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def action(self) -> str:
|
|
95
|
+
if not self.is_known:
|
|
96
|
+
return "unknown"
|
|
97
|
+
if self.is_likely_fp:
|
|
98
|
+
return "allow"
|
|
99
|
+
if self.severity >= 9:
|
|
100
|
+
return "block"
|
|
101
|
+
if self.severity >= 7:
|
|
102
|
+
return "alert"
|
|
103
|
+
return "log"
|
|
104
|
+
|
|
105
|
+
def __str__(self) -> str:
|
|
106
|
+
if not self.is_known:
|
|
107
|
+
return f"[UNKNOWN] {self.ioc_type}:{self.value[:40]}"
|
|
108
|
+
sym = "🔴" if self.severity >= 9 else "🟠" if self.severity >= 7 else "🟡"
|
|
109
|
+
return (f"{sym} [{self.action.upper()}] {self.ioc_type}:{self.value[:40]} "
|
|
110
|
+
f"— {self.family} sev={self.severity} conf={self.confidence}%")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
CLEAN_VERDICT = ThreatVerdict(
|
|
114
|
+
ioc_type="", value="", is_known=False, is_threat=False,
|
|
115
|
+
severity=0, confidence=0, family="", detection_count=0,
|
|
116
|
+
false_positive_votes=0, tags="",
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@dataclass
|
|
121
|
+
class ThreatSignature:
|
|
122
|
+
"""A threat signature received via subscription."""
|
|
123
|
+
id: int
|
|
124
|
+
ioc_type: str
|
|
125
|
+
value: str
|
|
126
|
+
family_name: str
|
|
127
|
+
severity: int
|
|
128
|
+
confidence: int
|
|
129
|
+
source_agent_id: str
|
|
130
|
+
detection_count: int
|
|
131
|
+
tags: str
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# ---------------------------------------------------------------------------
|
|
135
|
+
# Core sensor
|
|
136
|
+
# ---------------------------------------------------------------------------
|
|
137
|
+
|
|
138
|
+
class ThreatSensor:
|
|
139
|
+
"""
|
|
140
|
+
Embeddable threat sensor. One instance per agent process.
|
|
141
|
+
|
|
142
|
+
Thread-safe: observe_* and check() can be called from multiple threads.
|
|
143
|
+
subscribe() starts a background WebSocket listener thread.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
def __init__(
|
|
147
|
+
self,
|
|
148
|
+
server: str = SPACETIME_URL,
|
|
149
|
+
database: str = DATABASE,
|
|
150
|
+
agent_id: str = "sensor",
|
|
151
|
+
hostname: str = "",
|
|
152
|
+
threat_threshold: int = 7, # severity >= this triggers is_threat=True
|
|
153
|
+
cache_ttl: int = 300, # seconds to cache lookup results
|
|
154
|
+
):
|
|
155
|
+
self.server = server.rstrip("/")
|
|
156
|
+
self.database = database
|
|
157
|
+
self.agent_id = agent_id
|
|
158
|
+
self.hostname = hostname or os.uname().nodename
|
|
159
|
+
self.threat_threshold = threat_threshold
|
|
160
|
+
self._http = httpx.Client(timeout=15.0)
|
|
161
|
+
self._cache: dict[str, tuple[ThreatVerdict, float]] = {}
|
|
162
|
+
self._cache_ttl = cache_ttl
|
|
163
|
+
self._lock = threading.Lock()
|
|
164
|
+
self._subscriber_thread: Optional[threading.Thread] = None
|
|
165
|
+
self._callbacks: list[Callable[[ThreatSignature], None]] = []
|
|
166
|
+
self._running = False
|
|
167
|
+
|
|
168
|
+
# ------------------------------------------------------------------
|
|
169
|
+
# Registration
|
|
170
|
+
# ------------------------------------------------------------------
|
|
171
|
+
|
|
172
|
+
def register(self, capabilities: str = "sensor") -> bool:
|
|
173
|
+
"""Register this agent with SpacetimeDB. Safe to call on every startup."""
|
|
174
|
+
return self._call("register_agent",
|
|
175
|
+
self.agent_id, self.hostname, "python", capabilities)
|
|
176
|
+
|
|
177
|
+
# ------------------------------------------------------------------
|
|
178
|
+
# Observe methods — submit + check in one call
|
|
179
|
+
# ------------------------------------------------------------------
|
|
180
|
+
|
|
181
|
+
def observe_file(self, path: str | Path, submit: bool = True) -> ThreatVerdict:
|
|
182
|
+
"""
|
|
183
|
+
Hash a file and check it against the threat DB.
|
|
184
|
+
If unknown and submit=True, the hash is submitted as a new IOC
|
|
185
|
+
so other agents benefit from the observation.
|
|
186
|
+
"""
|
|
187
|
+
try:
|
|
188
|
+
data = Path(path).read_bytes()
|
|
189
|
+
except (OSError, PermissionError) as e:
|
|
190
|
+
return CLEAN_VERDICT
|
|
191
|
+
|
|
192
|
+
sha256 = hashlib.sha256(data).hexdigest()
|
|
193
|
+
md5 = hashlib.md5(data).hexdigest()
|
|
194
|
+
|
|
195
|
+
verdict = self.check("hash_sha256", sha256)
|
|
196
|
+
if not verdict.is_known:
|
|
197
|
+
verdict = self.check("hash_md5", md5)
|
|
198
|
+
|
|
199
|
+
if not verdict.is_known and submit:
|
|
200
|
+
self._submit_ioc(
|
|
201
|
+
ioc_type="hash_sha256",
|
|
202
|
+
value=sha256,
|
|
203
|
+
family="",
|
|
204
|
+
severity=5,
|
|
205
|
+
confidence=50,
|
|
206
|
+
tags=f"agent-observed,{self.agent_id},file",
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
return verdict
|
|
210
|
+
|
|
211
|
+
def observe_connection(self, ip: str, port: int = 0,
|
|
212
|
+
submit: bool = True) -> ThreatVerdict:
|
|
213
|
+
"""Check an outbound IP connection against the threat DB."""
|
|
214
|
+
ioc_value = f"{ip}:{port}" if port else ip
|
|
215
|
+
ioc_type = "ip_port" if port else "ip"
|
|
216
|
+
verdict = self.check(ioc_type, ioc_value)
|
|
217
|
+
|
|
218
|
+
if not verdict.is_known and submit:
|
|
219
|
+
self._submit_ioc(
|
|
220
|
+
ioc_type=ioc_type,
|
|
221
|
+
value=ioc_value,
|
|
222
|
+
family="",
|
|
223
|
+
severity=5,
|
|
224
|
+
confidence=50,
|
|
225
|
+
tags=f"agent-observed,{self.agent_id},network",
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
return verdict
|
|
229
|
+
|
|
230
|
+
def observe_dns(self, domain: str, submit: bool = True) -> ThreatVerdict:
|
|
231
|
+
"""Check a DNS query against the threat DB."""
|
|
232
|
+
domain = domain.lower().strip().rstrip(".")
|
|
233
|
+
verdict = self.check("domain", domain)
|
|
234
|
+
|
|
235
|
+
if not verdict.is_known and submit:
|
|
236
|
+
self._submit_ioc(
|
|
237
|
+
ioc_type="domain",
|
|
238
|
+
value=domain,
|
|
239
|
+
family="",
|
|
240
|
+
severity=5,
|
|
241
|
+
confidence=50,
|
|
242
|
+
tags=f"agent-observed,{self.agent_id},dns",
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
return verdict
|
|
246
|
+
|
|
247
|
+
def observe_url(self, url: str, submit: bool = True) -> ThreatVerdict:
|
|
248
|
+
"""Check a URL against the threat DB."""
|
|
249
|
+
verdict = self.check("url", url)
|
|
250
|
+
|
|
251
|
+
# Also check the domain component
|
|
252
|
+
if not verdict.is_known:
|
|
253
|
+
try:
|
|
254
|
+
parsed = urllib.parse.urlparse(url)
|
|
255
|
+
if parsed.netloc:
|
|
256
|
+
verdict = self.check("domain", parsed.netloc.lower())
|
|
257
|
+
except Exception:
|
|
258
|
+
pass
|
|
259
|
+
|
|
260
|
+
if not verdict.is_known and submit:
|
|
261
|
+
self._submit_ioc(
|
|
262
|
+
ioc_type="url",
|
|
263
|
+
value=url,
|
|
264
|
+
family="",
|
|
265
|
+
severity=5,
|
|
266
|
+
confidence=50,
|
|
267
|
+
tags=f"agent-observed,{self.agent_id},url",
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
return verdict
|
|
271
|
+
|
|
272
|
+
def report_detection(self, signature_id: int, action: str,
|
|
273
|
+
context: dict | None = None) -> bool:
|
|
274
|
+
"""
|
|
275
|
+
Report that this agent detected and acted on a known threat.
|
|
276
|
+
Increments the global detection_count in SpacetimeDB so the
|
|
277
|
+
community knows how widespread this IOC is.
|
|
278
|
+
|
|
279
|
+
action: "logged" | "alerted" | "blocked" | "quarantined" | "eradicated"
|
|
280
|
+
"""
|
|
281
|
+
ctx_json = json.dumps(context or {})
|
|
282
|
+
ok = self._call("report_detection", self.agent_id,
|
|
283
|
+
signature_id, action, ctx_json)
|
|
284
|
+
return ok
|
|
285
|
+
|
|
286
|
+
def vote_false_positive(self, signature_id: int, reason: str = "") -> bool:
|
|
287
|
+
"""
|
|
288
|
+
Flag an IOC as a false positive. When FP votes exceed 20% of
|
|
289
|
+
detections, is_likely_fp becomes True and action returns 'allow'.
|
|
290
|
+
"""
|
|
291
|
+
return self._call("vote_false_positive", self.agent_id,
|
|
292
|
+
signature_id, reason)
|
|
293
|
+
|
|
294
|
+
# ------------------------------------------------------------------
|
|
295
|
+
# Lookup
|
|
296
|
+
# ------------------------------------------------------------------
|
|
297
|
+
|
|
298
|
+
def check(self, ioc_type: str, value: str) -> ThreatVerdict:
|
|
299
|
+
"""
|
|
300
|
+
Instant IOC lookup with local TTL cache.
|
|
301
|
+
Returns a ThreatVerdict indicating threat level and recommended action.
|
|
302
|
+
"""
|
|
303
|
+
cache_key = f"{ioc_type}:{value.lower().strip()}"
|
|
304
|
+
|
|
305
|
+
with self._lock:
|
|
306
|
+
if cache_key in self._cache:
|
|
307
|
+
verdict, ts = self._cache[cache_key]
|
|
308
|
+
if time.time() - ts < self._cache_ttl:
|
|
309
|
+
return verdict
|
|
310
|
+
|
|
311
|
+
verdict = self._lookup(ioc_type, value)
|
|
312
|
+
|
|
313
|
+
with self._lock:
|
|
314
|
+
self._cache[cache_key] = (verdict, time.time())
|
|
315
|
+
|
|
316
|
+
return verdict
|
|
317
|
+
|
|
318
|
+
def _lookup(self, ioc_type: str, value: str) -> ThreatVerdict:
|
|
319
|
+
value_hash = hashlib.sha256(
|
|
320
|
+
f"{ioc_type}:{value.strip().lower()}".encode()
|
|
321
|
+
).hexdigest()
|
|
322
|
+
|
|
323
|
+
# Look up by dedup index — O(1) hash lookup
|
|
324
|
+
rows = self._sql(
|
|
325
|
+
f"SELECT signature_id FROM ioc_dedup_index "
|
|
326
|
+
f"WHERE value_hash = '{value_hash}'"
|
|
327
|
+
)
|
|
328
|
+
if not rows:
|
|
329
|
+
return ThreatVerdict(
|
|
330
|
+
ioc_type=ioc_type, value=value, is_known=False,
|
|
331
|
+
is_threat=False, severity=0, confidence=0,
|
|
332
|
+
family="", detection_count=0, false_positive_votes=0, tags="",
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
sig_id = rows[0][0]
|
|
336
|
+
sig_rows = self._sql(
|
|
337
|
+
f"SELECT id, ioc_type, value, family_name, severity, confidence, "
|
|
338
|
+
f"source_agent_id, detection_count, false_positive_votes, tags "
|
|
339
|
+
f"FROM threat_signature WHERE id = {sig_id}"
|
|
340
|
+
)
|
|
341
|
+
if not sig_rows:
|
|
342
|
+
return CLEAN_VERDICT
|
|
343
|
+
|
|
344
|
+
row = sig_rows[0]
|
|
345
|
+
severity = row[4]
|
|
346
|
+
return ThreatVerdict(
|
|
347
|
+
ioc_type=row[1],
|
|
348
|
+
value=row[2],
|
|
349
|
+
is_known=True,
|
|
350
|
+
is_threat=severity >= self.threat_threshold,
|
|
351
|
+
severity=severity,
|
|
352
|
+
confidence=row[5],
|
|
353
|
+
family=row[3],
|
|
354
|
+
detection_count=row[7],
|
|
355
|
+
false_positive_votes=row[8],
|
|
356
|
+
tags=row[9],
|
|
357
|
+
signature_id=row[0],
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
# ------------------------------------------------------------------
|
|
361
|
+
# Real-time subscription
|
|
362
|
+
# ------------------------------------------------------------------
|
|
363
|
+
|
|
364
|
+
def subscribe(
|
|
365
|
+
self,
|
|
366
|
+
callback: Callable[[ThreatSignature], None],
|
|
367
|
+
min_severity: int = 7,
|
|
368
|
+
) -> None:
|
|
369
|
+
"""
|
|
370
|
+
Register a callback that fires whenever any agent submits a new
|
|
371
|
+
threat signature matching min_severity.
|
|
372
|
+
|
|
373
|
+
Uses SpacetimeDB WebSocket subscription — push, not polling.
|
|
374
|
+
The callback runs in a background thread.
|
|
375
|
+
|
|
376
|
+
Example:
|
|
377
|
+
def on_threat(sig):
|
|
378
|
+
if sig.severity >= 9:
|
|
379
|
+
firewall.block(sig.value)
|
|
380
|
+
|
|
381
|
+
sensor.subscribe(on_threat, min_severity=8)
|
|
382
|
+
"""
|
|
383
|
+
self._callbacks.append((callback, min_severity))
|
|
384
|
+
if not self._running:
|
|
385
|
+
self._start_subscriber()
|
|
386
|
+
|
|
387
|
+
def _start_subscriber(self):
|
|
388
|
+
if not _HAS_WEBSOCKETS:
|
|
389
|
+
# Fallback: poll every 10s if websockets not installed
|
|
390
|
+
self._running = True
|
|
391
|
+
t = threading.Thread(target=self._poll_loop, daemon=True)
|
|
392
|
+
t.start()
|
|
393
|
+
self._subscriber_thread = t
|
|
394
|
+
return
|
|
395
|
+
|
|
396
|
+
self._running = True
|
|
397
|
+
t = threading.Thread(target=self._ws_loop, daemon=True)
|
|
398
|
+
t.start()
|
|
399
|
+
self._subscriber_thread = t
|
|
400
|
+
|
|
401
|
+
def _poll_loop(self):
|
|
402
|
+
"""Fallback: poll for new signatures every 10s."""
|
|
403
|
+
last_id = 0
|
|
404
|
+
while self._running:
|
|
405
|
+
try:
|
|
406
|
+
rows = self._sql(
|
|
407
|
+
f"SELECT id, ioc_type, value, family_name, severity, confidence, "
|
|
408
|
+
f"source_agent_id, detection_count, tags "
|
|
409
|
+
f"FROM threat_signature WHERE id > {last_id}"
|
|
410
|
+
)
|
|
411
|
+
for row in rows:
|
|
412
|
+
sig = ThreatSignature(
|
|
413
|
+
id=row[0], ioc_type=row[1], value=row[2],
|
|
414
|
+
family_name=row[3], severity=row[4], confidence=row[5],
|
|
415
|
+
source_agent_id=row[6], detection_count=row[7], tags=row[8],
|
|
416
|
+
)
|
|
417
|
+
last_id = max(last_id, sig.id)
|
|
418
|
+
for cb, min_sev in self._callbacks:
|
|
419
|
+
if sig.severity >= min_sev:
|
|
420
|
+
try:
|
|
421
|
+
cb(sig)
|
|
422
|
+
except Exception:
|
|
423
|
+
pass
|
|
424
|
+
except Exception:
|
|
425
|
+
pass
|
|
426
|
+
time.sleep(10)
|
|
427
|
+
|
|
428
|
+
def _ws_loop(self):
|
|
429
|
+
"""WebSocket subscriber — receives push from SpacetimeDB on insert."""
|
|
430
|
+
import asyncio
|
|
431
|
+
import websockets as ws
|
|
432
|
+
|
|
433
|
+
async def _connect():
|
|
434
|
+
db_id = self._get_db_identity()
|
|
435
|
+
ws_url = (self.server.replace("http://", "ws://")
|
|
436
|
+
.replace("https://", "wss://")
|
|
437
|
+
+ f"/v1/database/{db_id}/subscribe")
|
|
438
|
+
|
|
439
|
+
subscribe_msg = json.dumps({
|
|
440
|
+
"subscribe": {
|
|
441
|
+
"query_strings": [
|
|
442
|
+
"SELECT * FROM threat_signature"
|
|
443
|
+
]
|
|
444
|
+
}
|
|
445
|
+
})
|
|
446
|
+
|
|
447
|
+
while self._running:
|
|
448
|
+
try:
|
|
449
|
+
async with ws.connect(ws_url) as websocket:
|
|
450
|
+
await websocket.send(subscribe_msg)
|
|
451
|
+
async for raw in websocket:
|
|
452
|
+
try:
|
|
453
|
+
msg = json.loads(raw)
|
|
454
|
+
self._handle_ws_msg(msg)
|
|
455
|
+
except Exception:
|
|
456
|
+
pass
|
|
457
|
+
except Exception:
|
|
458
|
+
await asyncio.sleep(5)
|
|
459
|
+
|
|
460
|
+
asyncio.run(_connect())
|
|
461
|
+
|
|
462
|
+
def _handle_ws_msg(self, msg: dict):
|
|
463
|
+
"""Parse SpacetimeDB subscription update and fire callbacks."""
|
|
464
|
+
# SpacetimeDB sends SubscriptionUpdate with table_updates
|
|
465
|
+
updates = msg.get("SubscriptionUpdate", {}).get("table_updates", [])
|
|
466
|
+
for table_update in updates:
|
|
467
|
+
if table_update.get("table_name") != "threat_signature":
|
|
468
|
+
continue
|
|
469
|
+
for op in table_update.get("table_row_operations", []):
|
|
470
|
+
if op.get("op") != "insert":
|
|
471
|
+
continue
|
|
472
|
+
row = op.get("row", [])
|
|
473
|
+
if len(row) < 10:
|
|
474
|
+
continue
|
|
475
|
+
try:
|
|
476
|
+
sig = ThreatSignature(
|
|
477
|
+
id=row[0], ioc_type=row[1], value=row[3],
|
|
478
|
+
family_name=row[6], severity=row[7], confidence=row[8],
|
|
479
|
+
source_agent_id=row[9], detection_count=row[12], tags=row[14],
|
|
480
|
+
)
|
|
481
|
+
for cb, min_sev in self._callbacks:
|
|
482
|
+
if sig.severity >= min_sev:
|
|
483
|
+
cb(sig)
|
|
484
|
+
except Exception:
|
|
485
|
+
pass
|
|
486
|
+
|
|
487
|
+
def _get_db_identity(self) -> str:
|
|
488
|
+
"""Get the SpacetimeDB internal database identity hash."""
|
|
489
|
+
r = self._http.get(f"{self.server}/v1/database/{self.database}/identity")
|
|
490
|
+
if r.status_code == 200:
|
|
491
|
+
return r.json().get("identity", self.database)
|
|
492
|
+
return self.database
|
|
493
|
+
|
|
494
|
+
def stop(self):
|
|
495
|
+
"""Stop the background subscription thread."""
|
|
496
|
+
self._running = False
|
|
497
|
+
|
|
498
|
+
# ------------------------------------------------------------------
|
|
499
|
+
# Helpers
|
|
500
|
+
# ------------------------------------------------------------------
|
|
501
|
+
|
|
502
|
+
def _call(self, reducer: str, *args) -> bool:
|
|
503
|
+
url = f"{self.server}/v1/database/{self.database}/call/{reducer}"
|
|
504
|
+
try:
|
|
505
|
+
r = self._http.post(
|
|
506
|
+
url, content=json.dumps(list(args)).encode(),
|
|
507
|
+
headers={"Content-Type": "application/json"},
|
|
508
|
+
)
|
|
509
|
+
return r.status_code in (200, 204)
|
|
510
|
+
except Exception:
|
|
511
|
+
return False
|
|
512
|
+
|
|
513
|
+
def _sql(self, query: str) -> list:
|
|
514
|
+
url = f"{self.server}/v1/database/{self.database}/sql"
|
|
515
|
+
try:
|
|
516
|
+
r = self._http.post(url, content=query.encode(),
|
|
517
|
+
headers={"Content-Type": "text/plain"})
|
|
518
|
+
if r.status_code == 200:
|
|
519
|
+
data = r.json()
|
|
520
|
+
return data[0].get("rows", []) if data else []
|
|
521
|
+
except Exception:
|
|
522
|
+
pass
|
|
523
|
+
return []
|
|
524
|
+
|
|
525
|
+
def _submit_ioc(self, ioc_type: str, value: str, family: str,
|
|
526
|
+
severity: int, confidence: int, tags: str) -> bool:
|
|
527
|
+
value_hash = hashlib.sha256(
|
|
528
|
+
f"{ioc_type}:{value.strip().lower()}".encode()
|
|
529
|
+
).hexdigest()
|
|
530
|
+
header = [0xF3, 0x5B]
|
|
531
|
+
return self._call(
|
|
532
|
+
"submit_ioc", self.agent_id, ioc_type, value, value_hash,
|
|
533
|
+
header + [0x01, 0x00], header, family, severity, confidence, tags,
|
|
534
|
+
)
|
|
535
|
+
|
|
536
|
+
def __enter__(self):
|
|
537
|
+
self.register()
|
|
538
|
+
return self
|
|
539
|
+
|
|
540
|
+
def __exit__(self, *_):
|
|
541
|
+
self.stop()
|
|
542
|
+
self._http.close()
|
|
File without changes
|