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/__init__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Nullcone — distributed threat intelligence client SDK.
|
|
3
|
+
|
|
4
|
+
Quick start:
|
|
5
|
+
from nullcone import NullconeAgent, IOC, IOCType
|
|
6
|
+
|
|
7
|
+
with NullconeAgent() as agent:
|
|
8
|
+
result = agent.submit_ioc(IOC(ioc_type=IOCType.DOMAIN, value="evil.example.com"))
|
|
9
|
+
"""
|
|
10
|
+
from .agent import NullconeAgent
|
|
11
|
+
from .models import (
|
|
12
|
+
IOC,
|
|
13
|
+
IOCType,
|
|
14
|
+
Severity,
|
|
15
|
+
ActionTaken,
|
|
16
|
+
ThreatSignature,
|
|
17
|
+
MalwareFamily,
|
|
18
|
+
AgentInfo,
|
|
19
|
+
SubmitResult,
|
|
20
|
+
DetectionEvent,
|
|
21
|
+
)
|
|
22
|
+
from .client import SpacetimeDBClient, SpacetimeDBSubscriber, SpacetimeDBError
|
|
23
|
+
from .ei_client import EIClient, EIVerification, EIError, ALLOWED_ENTITY_TYPES
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"NullconeAgent",
|
|
27
|
+
"IOC",
|
|
28
|
+
"IOCType",
|
|
29
|
+
"Severity",
|
|
30
|
+
"ActionTaken",
|
|
31
|
+
"ThreatSignature",
|
|
32
|
+
"MalwareFamily",
|
|
33
|
+
"AgentInfo",
|
|
34
|
+
"SubmitResult",
|
|
35
|
+
"DetectionEvent",
|
|
36
|
+
"SpacetimeDBClient",
|
|
37
|
+
"SpacetimeDBSubscriber",
|
|
38
|
+
"SpacetimeDBError",
|
|
39
|
+
"EIClient",
|
|
40
|
+
"EIVerification",
|
|
41
|
+
"EIError",
|
|
42
|
+
"ALLOWED_ENTITY_TYPES",
|
|
43
|
+
]
|
nullcone/agent.py
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
"""
|
|
2
|
+
MalwareIntelAgent
|
|
3
|
+
|
|
4
|
+
Main agent class for the distributed malware intelligence network.
|
|
5
|
+
Each endpoint (honeypot, EDR sensor, network tap, sandbox) runs one agent.
|
|
6
|
+
|
|
7
|
+
Flow:
|
|
8
|
+
1. Agent registers with SpacetimeDB on startup
|
|
9
|
+
2. Agent subscribes to ThreatSignature table — gets real-time updates
|
|
10
|
+
from ALL other agents the moment a new IOC is submitted anywhere
|
|
11
|
+
3. Agent submits IOCs with binary-encoded metadata
|
|
12
|
+
4. SpacetimeDB reducer atomically deduplicates, increments counts
|
|
13
|
+
5. Agent reports detections back as ThreatEvent records
|
|
14
|
+
|
|
15
|
+
Compression:
|
|
16
|
+
- IOC metadata binary-encoded into compact envelope (0xF35B THREAT_IOC header)
|
|
17
|
+
- SecuritySymbol THREAT_IOC / THREAT_PATTERN encoded as threat_symbol column
|
|
18
|
+
- ~10x metadata key savings + gzip on context text
|
|
19
|
+
|
|
20
|
+
Classifier Integration:
|
|
21
|
+
- Keyword-based family classification (zero deps, runs inline)
|
|
22
|
+
- Optional semantic embedding similarity (sentence-transformers)
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import json
|
|
27
|
+
import pathlib
|
|
28
|
+
import platform
|
|
29
|
+
import socket
|
|
30
|
+
import threading
|
|
31
|
+
import uuid
|
|
32
|
+
from typing import Any, Callable, Optional
|
|
33
|
+
|
|
34
|
+
from .classifier import classify
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _sql_str(s: str) -> str:
|
|
38
|
+
"""Escape a string for safe interpolation into SpacetimeDB SQL."""
|
|
39
|
+
return s.replace("'", "''")
|
|
40
|
+
from .compressor import compress, threat_symbol_for
|
|
41
|
+
from .models import (
|
|
42
|
+
ActionTaken,
|
|
43
|
+
DetectionEvent,
|
|
44
|
+
IOC,
|
|
45
|
+
MalwareFamily,
|
|
46
|
+
SubmitResult,
|
|
47
|
+
ThreatSignature,
|
|
48
|
+
)
|
|
49
|
+
from .client import SpacetimeDBClient, SpacetimeDBError, SpacetimeDBSubscriber
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class NullconeAgent:
|
|
53
|
+
"""
|
|
54
|
+
Distributed malware intelligence agent.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
spacetime_url: SpacetimeDB HTTP URL (default: http://localhost:3000)
|
|
58
|
+
ws_url: SpacetimeDB WebSocket URL (default: ws://localhost:3000)
|
|
59
|
+
database: SpacetimeDB database name (default: malware-intel)
|
|
60
|
+
agent_id: Stable agent identity (default: auto-generated UUID)
|
|
61
|
+
token: Optional auth token for secured SpacetimeDB instances
|
|
62
|
+
auto_classify: Auto-classify IOC family on submit (default: True)
|
|
63
|
+
use_embeddings: Use sentence-transformers for family classification
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(
|
|
67
|
+
self,
|
|
68
|
+
spacetime_url: str = "http://localhost:3000",
|
|
69
|
+
ws_url: str = "ws://localhost:3000",
|
|
70
|
+
database: str = "nullcone",
|
|
71
|
+
agent_id: Optional[str] = None,
|
|
72
|
+
token: Optional[str] = None,
|
|
73
|
+
auto_classify: bool = True,
|
|
74
|
+
use_embeddings: bool = False,
|
|
75
|
+
):
|
|
76
|
+
self.agent_id = agent_id or str(uuid.uuid4())
|
|
77
|
+
self.auto_classify = auto_classify
|
|
78
|
+
self.use_embeddings = use_embeddings
|
|
79
|
+
self._families: list[MalwareFamily] = []
|
|
80
|
+
|
|
81
|
+
self._client = SpacetimeDBClient(
|
|
82
|
+
base_url=spacetime_url,
|
|
83
|
+
database=database,
|
|
84
|
+
token=token,
|
|
85
|
+
)
|
|
86
|
+
self._subscriber = SpacetimeDBSubscriber(
|
|
87
|
+
ws_url=ws_url,
|
|
88
|
+
database=database,
|
|
89
|
+
token=token,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
# ------------------------------------------------------------------
|
|
93
|
+
# Registration
|
|
94
|
+
# ------------------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
def register(self) -> None:
|
|
97
|
+
"""Register this agent with SpacetimeDB. Safe to call multiple times."""
|
|
98
|
+
capabilities = json.dumps({
|
|
99
|
+
"sensors": ["file", "network", "process"],
|
|
100
|
+
"actions": ["block", "quarantine", "log"],
|
|
101
|
+
})
|
|
102
|
+
self._client.call_reducer(
|
|
103
|
+
"register_agent",
|
|
104
|
+
self.agent_id,
|
|
105
|
+
socket.gethostname(),
|
|
106
|
+
platform.system(),
|
|
107
|
+
capabilities,
|
|
108
|
+
)
|
|
109
|
+
# Cache known families for classification
|
|
110
|
+
self._refresh_families()
|
|
111
|
+
|
|
112
|
+
def _refresh_families(self) -> None:
|
|
113
|
+
"""Load known malware families from SpacetimeDB into local cache."""
|
|
114
|
+
try:
|
|
115
|
+
rows = self._client.sql("SELECT * FROM malware_family")
|
|
116
|
+
self._families = [MalwareFamily.from_dict(r) for r in rows]
|
|
117
|
+
except Exception:
|
|
118
|
+
self._families = []
|
|
119
|
+
|
|
120
|
+
# ------------------------------------------------------------------
|
|
121
|
+
# IOC Submission
|
|
122
|
+
# ------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
def submit_ioc(self, ioc: IOC) -> SubmitResult:
|
|
125
|
+
"""
|
|
126
|
+
Submit an IOC to the shared threat intelligence database.
|
|
127
|
+
|
|
128
|
+
Automatically:
|
|
129
|
+
- Classifies into malware family (keyword + optional embedding)
|
|
130
|
+
- Compresses metadata into compact binary envelope
|
|
131
|
+
- Deduplicates atomically in SpacetimeDB reducer
|
|
132
|
+
- All subscribed agents receive the new/updated IOC instantly
|
|
133
|
+
|
|
134
|
+
Returns SubmitResult indicating "new", "duplicate", or "updated".
|
|
135
|
+
"""
|
|
136
|
+
# Auto-classify family if not already set
|
|
137
|
+
if self.auto_classify and not ioc.family_hint:
|
|
138
|
+
ioc.family_hint = classify(
|
|
139
|
+
ioc,
|
|
140
|
+
families=self._families,
|
|
141
|
+
use_embeddings=self.use_embeddings,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
# Compress metadata into binary envelope
|
|
145
|
+
meta_compressed = compress(ioc)
|
|
146
|
+
threat_symbol = list(threat_symbol_for(ioc))
|
|
147
|
+
value_hash = ioc.value_hash()
|
|
148
|
+
|
|
149
|
+
try:
|
|
150
|
+
self._client.call_reducer(
|
|
151
|
+
"submit_ioc",
|
|
152
|
+
self.agent_id,
|
|
153
|
+
ioc.ioc_type.value,
|
|
154
|
+
ioc.value,
|
|
155
|
+
value_hash,
|
|
156
|
+
list(meta_compressed),
|
|
157
|
+
threat_symbol,
|
|
158
|
+
ioc.family_hint or "",
|
|
159
|
+
ioc.severity,
|
|
160
|
+
ioc.confidence,
|
|
161
|
+
",".join(ioc.tags),
|
|
162
|
+
)
|
|
163
|
+
except SpacetimeDBError as e:
|
|
164
|
+
return SubmitResult(
|
|
165
|
+
status="error",
|
|
166
|
+
signature_id=None,
|
|
167
|
+
detection_count=0,
|
|
168
|
+
message=str(e),
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
# Query to determine if it was new or duplicate
|
|
172
|
+
rows = self._client.sql(
|
|
173
|
+
f"SELECT id, detection_count FROM threat_signature "
|
|
174
|
+
f"WHERE value_hash = '{value_hash}'"
|
|
175
|
+
)
|
|
176
|
+
if rows:
|
|
177
|
+
row = rows[0]
|
|
178
|
+
count = row.get("detection_count", 1)
|
|
179
|
+
status = "new" if count == 1 else "updated"
|
|
180
|
+
return SubmitResult(
|
|
181
|
+
status=status,
|
|
182
|
+
signature_id=row.get("id"),
|
|
183
|
+
detection_count=count,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
return SubmitResult(status="new", signature_id=None, detection_count=1)
|
|
187
|
+
|
|
188
|
+
def submit_batch(self, iocs: list[IOC]) -> list[SubmitResult]:
|
|
189
|
+
"""Submit multiple IOCs. Returns results in order."""
|
|
190
|
+
return [self.submit_ioc(ioc) for ioc in iocs]
|
|
191
|
+
|
|
192
|
+
# ------------------------------------------------------------------
|
|
193
|
+
# Detection Reporting
|
|
194
|
+
# ------------------------------------------------------------------
|
|
195
|
+
|
|
196
|
+
def report_detection(
|
|
197
|
+
self,
|
|
198
|
+
signature_id: int,
|
|
199
|
+
action: ActionTaken,
|
|
200
|
+
context: Optional[dict[str, Any]] = None,
|
|
201
|
+
) -> None:
|
|
202
|
+
"""
|
|
203
|
+
Report that this agent detected and acted on a known threat signature.
|
|
204
|
+
|
|
205
|
+
Increments detection_count on the signature and creates a ThreatEvent
|
|
206
|
+
record visible to all other agents in real-time.
|
|
207
|
+
"""
|
|
208
|
+
self._client.call_reducer(
|
|
209
|
+
"report_detection",
|
|
210
|
+
self.agent_id,
|
|
211
|
+
signature_id,
|
|
212
|
+
action.value,
|
|
213
|
+
json.dumps(context or {}),
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
def vote_false_positive(self, signature_id: int, reason: str = "") -> None:
|
|
217
|
+
"""
|
|
218
|
+
Report that a signature is likely a false positive.
|
|
219
|
+
|
|
220
|
+
When >20% of agents vote FP, ThreatSignature.is_likely_fp returns True.
|
|
221
|
+
"""
|
|
222
|
+
self._client.call_reducer(
|
|
223
|
+
"vote_false_positive",
|
|
224
|
+
self.agent_id,
|
|
225
|
+
signature_id,
|
|
226
|
+
reason,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
# ------------------------------------------------------------------
|
|
230
|
+
# Query
|
|
231
|
+
# ------------------------------------------------------------------
|
|
232
|
+
|
|
233
|
+
def find_by_value(self, value: str) -> Optional[ThreatSignature]:
|
|
234
|
+
"""Look up a threat signature by its exact IOC value."""
|
|
235
|
+
rows = self._client.sql(
|
|
236
|
+
f"SELECT * FROM threat_signature WHERE value = '{_sql_str(value)}'"
|
|
237
|
+
)
|
|
238
|
+
return ThreatSignature.from_dict(rows[0]) if rows else None
|
|
239
|
+
|
|
240
|
+
def find_by_hash(self, value_hash: str) -> Optional[ThreatSignature]:
|
|
241
|
+
"""Look up a threat signature by its pre-computed value_hash."""
|
|
242
|
+
rows = self._client.sql(
|
|
243
|
+
f"SELECT * FROM threat_signature WHERE value_hash = '{_sql_str(value_hash)}'"
|
|
244
|
+
)
|
|
245
|
+
return ThreatSignature.from_dict(rows[0]) if rows else None
|
|
246
|
+
|
|
247
|
+
def recent_threats(self, limit: int = 50, min_severity: int = 0) -> list[ThreatSignature]:
|
|
248
|
+
"""Return the most recently seen threats, optionally filtered by severity."""
|
|
249
|
+
rows = self._client.sql(
|
|
250
|
+
f"SELECT * FROM threat_signature "
|
|
251
|
+
f"WHERE severity >= {int(min_severity)} "
|
|
252
|
+
f"ORDER BY last_seen DESC LIMIT {int(limit)}"
|
|
253
|
+
)
|
|
254
|
+
return [ThreatSignature.from_dict(r) for r in rows]
|
|
255
|
+
|
|
256
|
+
def family_threats(self, family_name: str) -> list[ThreatSignature]:
|
|
257
|
+
"""Return all IOCs associated with a specific malware family."""
|
|
258
|
+
rows = self._client.sql(
|
|
259
|
+
f"SELECT * FROM threat_signature WHERE family_name = '{_sql_str(family_name)}'"
|
|
260
|
+
)
|
|
261
|
+
return [ThreatSignature.from_dict(r) for r in rows]
|
|
262
|
+
|
|
263
|
+
def stats(self) -> dict[str, Any]:
|
|
264
|
+
"""Return aggregate statistics for the threat database."""
|
|
265
|
+
try:
|
|
266
|
+
sig_rows = self._client.sql("SELECT COUNT(*) as n FROM threat_signature")
|
|
267
|
+
fam_rows = self._client.sql("SELECT COUNT(*) as n FROM malware_family")
|
|
268
|
+
agent_rows = self._client.sql("SELECT COUNT(*) as n FROM agent_registration")
|
|
269
|
+
event_rows = self._client.sql("SELECT COUNT(*) as n FROM threat_event")
|
|
270
|
+
return {
|
|
271
|
+
"total_signatures": sig_rows[0]["n"] if sig_rows else 0,
|
|
272
|
+
"total_families": fam_rows[0]["n"] if fam_rows else 0,
|
|
273
|
+
"total_agents": agent_rows[0]["n"] if agent_rows else 0,
|
|
274
|
+
"total_events": event_rows[0]["n"] if event_rows else 0,
|
|
275
|
+
}
|
|
276
|
+
except Exception:
|
|
277
|
+
return {}
|
|
278
|
+
|
|
279
|
+
# ------------------------------------------------------------------
|
|
280
|
+
# Poll-based sync (recommended for most agents)
|
|
281
|
+
# ------------------------------------------------------------------
|
|
282
|
+
|
|
283
|
+
def poll_since(
|
|
284
|
+
self,
|
|
285
|
+
last_id: int = 0,
|
|
286
|
+
batch_size: int = 1000,
|
|
287
|
+
min_severity: int = 0,
|
|
288
|
+
) -> tuple[list[ThreatSignature], int]:
|
|
289
|
+
"""
|
|
290
|
+
Fetch threat signatures added since last_id (exclusive), then disconnect.
|
|
291
|
+
|
|
292
|
+
This is the recommended sync pattern for EDR sensors, honeypots, and
|
|
293
|
+
any agent that doesn't need sub-second latency. The HTTP connection
|
|
294
|
+
is opened, data fetched, and closed — no persistent socket required.
|
|
295
|
+
|
|
296
|
+
Returns (new_signatures, new_high_water_mark).
|
|
297
|
+
new_high_water_mark is the max id seen; pass it back on the next call.
|
|
298
|
+
Returns ([], last_id) if nothing new.
|
|
299
|
+
|
|
300
|
+
Typical usage:
|
|
301
|
+
last_id = load_persisted_state() # int, 0 on first run
|
|
302
|
+
sigs, last_id = agent.poll_since(last_id)
|
|
303
|
+
apply_to_local_blocklist(sigs)
|
|
304
|
+
save_state(last_id)
|
|
305
|
+
"""
|
|
306
|
+
query = f"SELECT * FROM threat_signature WHERE id > {last_id}"
|
|
307
|
+
if min_severity:
|
|
308
|
+
query += f" AND severity >= {min_severity}"
|
|
309
|
+
query += f" LIMIT {batch_size}"
|
|
310
|
+
|
|
311
|
+
rows = self._client.sql(query)
|
|
312
|
+
if not rows:
|
|
313
|
+
return [], last_id
|
|
314
|
+
|
|
315
|
+
sigs = [ThreatSignature.from_dict(r) for r in rows]
|
|
316
|
+
new_hwm = max(s.id for s in sigs)
|
|
317
|
+
return sigs, new_hwm
|
|
318
|
+
|
|
319
|
+
def sync_loop(
|
|
320
|
+
self,
|
|
321
|
+
callback: Callable[[list[ThreatSignature]], None],
|
|
322
|
+
interval: float = 300.0,
|
|
323
|
+
state_file: Optional[str] = None,
|
|
324
|
+
min_severity: int = 0,
|
|
325
|
+
batch_size: int = 1000,
|
|
326
|
+
) -> None:
|
|
327
|
+
"""
|
|
328
|
+
Start a background poll-and-disconnect sync loop.
|
|
329
|
+
|
|
330
|
+
Every `interval` seconds:
|
|
331
|
+
1. Opens an HTTP connection
|
|
332
|
+
2. Fetches all signatures with id > last_seen_id
|
|
333
|
+
3. Calls callback(new_signatures) if anything new
|
|
334
|
+
4. Persists the new high-water mark to state_file
|
|
335
|
+
5. Closes the connection
|
|
336
|
+
|
|
337
|
+
The high-water mark survives restarts via state_file so agents
|
|
338
|
+
never re-process signatures they've already seen.
|
|
339
|
+
|
|
340
|
+
Args:
|
|
341
|
+
callback: Called with list[ThreatSignature] on each new batch
|
|
342
|
+
interval: Poll interval in seconds (default: 300 = 5 min)
|
|
343
|
+
state_file: Path to persist last_id (default: ~/.nullcone/{agent_id}.state)
|
|
344
|
+
min_severity: Skip signatures below this severity level
|
|
345
|
+
batch_size: Max sigs per poll; if full, next poll catches the rest
|
|
346
|
+
"""
|
|
347
|
+
if state_file is None:
|
|
348
|
+
state_dir = pathlib.Path.home() / ".nullcone"
|
|
349
|
+
state_dir.mkdir(exist_ok=True)
|
|
350
|
+
state_file = str(state_dir / f"{self.agent_id}.state")
|
|
351
|
+
|
|
352
|
+
last_id = 0
|
|
353
|
+
try:
|
|
354
|
+
last_id = int(pathlib.Path(state_file).read_text().strip())
|
|
355
|
+
except Exception:
|
|
356
|
+
pass
|
|
357
|
+
|
|
358
|
+
self._sync_stop = threading.Event()
|
|
359
|
+
|
|
360
|
+
def _loop() -> None:
|
|
361
|
+
nonlocal last_id
|
|
362
|
+
while not self._sync_stop.is_set():
|
|
363
|
+
try:
|
|
364
|
+
new_sigs, new_hwm = self.poll_since(
|
|
365
|
+
last_id, batch_size=batch_size, min_severity=min_severity
|
|
366
|
+
)
|
|
367
|
+
if new_sigs:
|
|
368
|
+
callback(new_sigs)
|
|
369
|
+
if new_hwm != last_id:
|
|
370
|
+
last_id = new_hwm
|
|
371
|
+
try:
|
|
372
|
+
pathlib.Path(state_file).write_text(str(last_id))
|
|
373
|
+
except Exception:
|
|
374
|
+
pass
|
|
375
|
+
except Exception:
|
|
376
|
+
pass
|
|
377
|
+
self._sync_stop.wait(interval)
|
|
378
|
+
|
|
379
|
+
self._sync_thread = threading.Thread(target=_loop, daemon=True, name="nullcone-sync")
|
|
380
|
+
self._sync_thread.start()
|
|
381
|
+
|
|
382
|
+
def stop_sync(self) -> None:
|
|
383
|
+
"""Stop the background sync loop."""
|
|
384
|
+
if hasattr(self, "_sync_stop"):
|
|
385
|
+
self._sync_stop.set()
|
|
386
|
+
if hasattr(self, "_sync_thread"):
|
|
387
|
+
self._sync_thread.join(timeout=5.0)
|
|
388
|
+
|
|
389
|
+
# ------------------------------------------------------------------
|
|
390
|
+
# Real-Time Subscriptions (use only when sub-second latency is needed)
|
|
391
|
+
# ------------------------------------------------------------------
|
|
392
|
+
|
|
393
|
+
def subscribe_new_threats(
|
|
394
|
+
self,
|
|
395
|
+
callback: Callable[[ThreatSignature], None],
|
|
396
|
+
min_severity: int = 0,
|
|
397
|
+
) -> None:
|
|
398
|
+
"""
|
|
399
|
+
Subscribe to new IOCs from all agents in real-time.
|
|
400
|
+
|
|
401
|
+
callback is called in a background thread whenever any agent
|
|
402
|
+
submits a new IOC that passes the severity filter.
|
|
403
|
+
|
|
404
|
+
Call start_subscriptions() after setting up all subscriptions.
|
|
405
|
+
"""
|
|
406
|
+
query = f"SELECT * FROM threat_signature WHERE severity >= {min_severity}"
|
|
407
|
+
|
|
408
|
+
def on_insert(event: dict) -> None:
|
|
409
|
+
row = event.get("row", {})
|
|
410
|
+
sig = ThreatSignature.from_dict(row)
|
|
411
|
+
callback(sig)
|
|
412
|
+
|
|
413
|
+
self._subscriber.subscribe(query, on_insert=on_insert)
|
|
414
|
+
|
|
415
|
+
def subscribe_high_severity(
|
|
416
|
+
self,
|
|
417
|
+
callback: Callable[[ThreatSignature], None],
|
|
418
|
+
threshold: int = 7,
|
|
419
|
+
) -> None:
|
|
420
|
+
"""Subscribe specifically to high/critical severity IOCs."""
|
|
421
|
+
self.subscribe_new_threats(callback, min_severity=threshold)
|
|
422
|
+
|
|
423
|
+
def start_subscriptions(self) -> None:
|
|
424
|
+
"""Start the background WebSocket subscription thread."""
|
|
425
|
+
self._subscriber.start()
|
|
426
|
+
|
|
427
|
+
def stop_subscriptions(self) -> None:
|
|
428
|
+
"""Stop the background subscription thread."""
|
|
429
|
+
self._subscriber.stop()
|
|
430
|
+
|
|
431
|
+
# ------------------------------------------------------------------
|
|
432
|
+
# Context Manager
|
|
433
|
+
# ------------------------------------------------------------------
|
|
434
|
+
|
|
435
|
+
def __enter__(self) -> "NullconeAgent":
|
|
436
|
+
self.register()
|
|
437
|
+
return self
|
|
438
|
+
|
|
439
|
+
def __exit__(self, *_) -> None:
|
|
440
|
+
self.stop_sync()
|
|
441
|
+
self.stop_subscriptions()
|
|
442
|
+
self._client.close()
|