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/cli.py
ADDED
|
@@ -0,0 +1,796 @@
|
|
|
1
|
+
"""
|
|
2
|
+
nullcone CLI — command-line interface for the Nullcone threat intelligence platform.
|
|
3
|
+
|
|
4
|
+
Usage:
|
|
5
|
+
nullcone [OPTIONS] COMMAND [ARGS]...
|
|
6
|
+
|
|
7
|
+
Configuration is persisted in ~/.config/nullcone/cli_config.json.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import platform
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
import uuid
|
|
17
|
+
from dataclasses import asdict
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Optional
|
|
20
|
+
|
|
21
|
+
import click
|
|
22
|
+
|
|
23
|
+
from .agent import NullconeAgent
|
|
24
|
+
from .models import ActionTaken, IOC, IOCType, Severity
|
|
25
|
+
|
|
26
|
+
# ---------------------------------------------------------------------------
|
|
27
|
+
# Config helpers
|
|
28
|
+
# ---------------------------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
CONFIG_DIR = Path.home() / ".config" / "nullcone"
|
|
31
|
+
CONFIG_FILE = CONFIG_DIR / "cli_config.json"
|
|
32
|
+
STATE_DIR = Path.home() / ".nullcone"
|
|
33
|
+
|
|
34
|
+
_IOC_TYPE_ALIASES: dict[str, IOCType] = {
|
|
35
|
+
# short names
|
|
36
|
+
"ip": IOCType.IP,
|
|
37
|
+
"ip_port": IOCType.IP_PORT,
|
|
38
|
+
"domain": IOCType.DOMAIN,
|
|
39
|
+
"url": IOCType.URL,
|
|
40
|
+
"md5": IOCType.MD5,
|
|
41
|
+
"sha1": IOCType.SHA1,
|
|
42
|
+
"sha256": IOCType.SHA256,
|
|
43
|
+
"hash_md5": IOCType.MD5,
|
|
44
|
+
"hash_sha1": IOCType.SHA1,
|
|
45
|
+
"hash_sha256": IOCType.SHA256,
|
|
46
|
+
"yara": IOCType.YARA,
|
|
47
|
+
"email": IOCType.EMAIL,
|
|
48
|
+
"mutex": IOCType.MUTEX,
|
|
49
|
+
"registry": IOCType.REGISTRY,
|
|
50
|
+
"filepath": IOCType.FILEPATH,
|
|
51
|
+
"asn": IOCType.ASN,
|
|
52
|
+
"ja3": IOCType.JA3,
|
|
53
|
+
"imphash": IOCType.IMPHASH,
|
|
54
|
+
"cve": IOCType.CVE,
|
|
55
|
+
"prompt": IOCType.PROMPT,
|
|
56
|
+
"skill": IOCType.SKILL,
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
_SEVERITY_ALIASES: dict[str, int] = {
|
|
60
|
+
"info": 1,
|
|
61
|
+
"low": 3,
|
|
62
|
+
"medium": 5,
|
|
63
|
+
"high": 7,
|
|
64
|
+
"critical": 9,
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
_ACTION_ALIASES: dict[str, ActionTaken] = {a.value: a for a in ActionTaken}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _load_config() -> dict[str, Any]:
|
|
71
|
+
if CONFIG_FILE.exists():
|
|
72
|
+
try:
|
|
73
|
+
return json.loads(CONFIG_FILE.read_text())
|
|
74
|
+
except Exception:
|
|
75
|
+
return {}
|
|
76
|
+
return {}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _save_config(cfg: dict[str, Any]) -> None:
|
|
80
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
81
|
+
CONFIG_FILE.write_text(json.dumps(cfg, indent=2) + "\n")
|
|
82
|
+
CONFIG_FILE.chmod(0o600)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _get_or_create_agent_id(cfg: dict[str, Any]) -> str:
|
|
86
|
+
"""Return existing agent_id or generate + persist a new one."""
|
|
87
|
+
if cfg.get("agent_id"):
|
|
88
|
+
return cfg["agent_id"]
|
|
89
|
+
new_id = f"cli-{uuid.uuid4().hex[:12]}"
|
|
90
|
+
cfg["agent_id"] = new_id
|
|
91
|
+
_save_config(cfg)
|
|
92
|
+
return new_id
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _make_agent(
|
|
96
|
+
url: Optional[str],
|
|
97
|
+
database: Optional[str],
|
|
98
|
+
agent_id: Optional[str],
|
|
99
|
+
token: Optional[str],
|
|
100
|
+
auto_classify: bool = True,
|
|
101
|
+
) -> tuple[NullconeAgent, dict[str, Any]]:
|
|
102
|
+
cfg = _load_config()
|
|
103
|
+
spacetime_url = url or cfg.get("spacetime_url", "http://localhost:3000")
|
|
104
|
+
ws_url = spacetime_url.replace("https://", "wss://").replace("http://", "ws://")
|
|
105
|
+
db = database or cfg.get("database", "nullcone")
|
|
106
|
+
aid = agent_id or _get_or_create_agent_id(cfg)
|
|
107
|
+
tok = token or cfg.get("token")
|
|
108
|
+
agent = NullconeAgent(
|
|
109
|
+
spacetime_url=spacetime_url,
|
|
110
|
+
ws_url=ws_url,
|
|
111
|
+
database=db,
|
|
112
|
+
agent_id=aid,
|
|
113
|
+
token=tok,
|
|
114
|
+
auto_classify=auto_classify,
|
|
115
|
+
)
|
|
116
|
+
return agent, cfg
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _parse_ioc_type(value: str) -> IOCType:
|
|
120
|
+
key = value.strip().lower()
|
|
121
|
+
if key in _IOC_TYPE_ALIASES:
|
|
122
|
+
return _IOC_TYPE_ALIASES[key]
|
|
123
|
+
raise click.BadParameter(
|
|
124
|
+
f"Unknown IOC type '{value}'. Valid: {', '.join(_IOC_TYPE_ALIASES)}"
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _parse_severity(value: str) -> int:
|
|
129
|
+
v = value.strip().lower()
|
|
130
|
+
if v in _SEVERITY_ALIASES:
|
|
131
|
+
return _SEVERITY_ALIASES[v]
|
|
132
|
+
try:
|
|
133
|
+
n = int(v)
|
|
134
|
+
if 0 <= n <= 10:
|
|
135
|
+
return n
|
|
136
|
+
except ValueError:
|
|
137
|
+
pass
|
|
138
|
+
raise click.BadParameter(
|
|
139
|
+
f"Invalid severity '{value}'. Use 0-10 or: info, low, medium, high, critical"
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _parse_action(value: str) -> ActionTaken:
|
|
144
|
+
v = value.strip().lower()
|
|
145
|
+
if v in _ACTION_ALIASES:
|
|
146
|
+
return _ACTION_ALIASES[v]
|
|
147
|
+
raise click.BadParameter(
|
|
148
|
+
f"Unknown action '{value}'. Valid: {', '.join(_ACTION_ALIASES)}"
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _severity_label(n: int) -> str:
|
|
153
|
+
if n >= 9:
|
|
154
|
+
return "CRITICAL"
|
|
155
|
+
if n >= 7:
|
|
156
|
+
return "HIGH"
|
|
157
|
+
if n >= 5:
|
|
158
|
+
return "MEDIUM"
|
|
159
|
+
if n >= 3:
|
|
160
|
+
return "LOW"
|
|
161
|
+
return "INFO"
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _out(data: Any, as_json: bool) -> None:
|
|
165
|
+
"""Print output — JSON to stdout if requested, else human-readable."""
|
|
166
|
+
if as_json:
|
|
167
|
+
click.echo(json.dumps(data, default=str))
|
|
168
|
+
else:
|
|
169
|
+
# data should be a string for human mode
|
|
170
|
+
click.echo(data)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _err(msg: str, as_json: bool, exit_code: int = 1) -> None:
|
|
174
|
+
if as_json:
|
|
175
|
+
click.echo(json.dumps({"error": msg}), err=True)
|
|
176
|
+
else:
|
|
177
|
+
click.echo(f"Error: {msg}", err=True)
|
|
178
|
+
sys.exit(exit_code)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# ---------------------------------------------------------------------------
|
|
182
|
+
# CLI root
|
|
183
|
+
# ---------------------------------------------------------------------------
|
|
184
|
+
|
|
185
|
+
@click.group()
|
|
186
|
+
@click.option("--url", envvar="NULLCONE_URL", default=None, help="SpacetimeDB URL (e.g. http://localhost:3000)")
|
|
187
|
+
@click.option("--database", "--db", envvar="NULLCONE_DB", default=None, help="Database name (default: nullcone)")
|
|
188
|
+
@click.option("--agent-id", envvar="NULLCONE_AGENT_ID", default=None, help="Agent ID (auto-generated if omitted)")
|
|
189
|
+
@click.option("--token", envvar="NULLCONE_TOKEN", default=None, help="Auth token")
|
|
190
|
+
@click.option("--json", "as_json", is_flag=True, envvar="NULLCONE_JSON", help="Output as JSON")
|
|
191
|
+
@click.pass_context
|
|
192
|
+
def cli(ctx: click.Context, url: Optional[str], database: Optional[str], agent_id: Optional[str], token: Optional[str], as_json: bool) -> None:
|
|
193
|
+
"""Nullcone threat intelligence CLI.
|
|
194
|
+
|
|
195
|
+
Credentials and server URL are read from ~/.config/nullcone/cli_config.json
|
|
196
|
+
or overridden via environment variables / flags.
|
|
197
|
+
"""
|
|
198
|
+
ctx.ensure_object(dict)
|
|
199
|
+
ctx.obj["url"] = url
|
|
200
|
+
ctx.obj["database"] = database
|
|
201
|
+
ctx.obj["agent_id"] = agent_id
|
|
202
|
+
ctx.obj["token"] = token
|
|
203
|
+
ctx.obj["as_json"] = as_json
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
# ---------------------------------------------------------------------------
|
|
207
|
+
# config
|
|
208
|
+
# ---------------------------------------------------------------------------
|
|
209
|
+
|
|
210
|
+
@cli.group()
|
|
211
|
+
def config() -> None:
|
|
212
|
+
"""Manage local configuration."""
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
@config.command("show")
|
|
216
|
+
@click.pass_context
|
|
217
|
+
def config_show(ctx: click.Context) -> None:
|
|
218
|
+
"""Show current configuration."""
|
|
219
|
+
cfg = _load_config()
|
|
220
|
+
as_json = ctx.obj["as_json"]
|
|
221
|
+
# Mask token
|
|
222
|
+
display = dict(cfg)
|
|
223
|
+
if display.get("token"):
|
|
224
|
+
display["token"] = display["token"][:8] + "..."
|
|
225
|
+
if as_json:
|
|
226
|
+
_out(display, True)
|
|
227
|
+
else:
|
|
228
|
+
if not display:
|
|
229
|
+
click.echo("No configuration found. Run: nullcone config init")
|
|
230
|
+
return
|
|
231
|
+
for k, v in display.items():
|
|
232
|
+
click.echo(f" {k}: {v}")
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@config.command("set")
|
|
236
|
+
@click.argument("key")
|
|
237
|
+
@click.argument("value")
|
|
238
|
+
def config_set(key: str, value: str) -> None:
|
|
239
|
+
"""Set a configuration value (e.g. spacetime_url, database, agent_id, token)."""
|
|
240
|
+
cfg = _load_config()
|
|
241
|
+
cfg[key] = value
|
|
242
|
+
_save_config(cfg)
|
|
243
|
+
click.echo(f"Set {key}")
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
@config.command("init")
|
|
247
|
+
@click.option("--url", default="http://localhost:3000", prompt="SpacetimeDB URL", help="SpacetimeDB server URL")
|
|
248
|
+
@click.option("--database", default="nullcone", prompt="Database name", help="SpacetimeDB database name")
|
|
249
|
+
@click.option("--token", default="", prompt="Auth token (leave blank if none)", hide_input=True, help="Optional auth token")
|
|
250
|
+
def config_init(url: str, database: str, token: str) -> None:
|
|
251
|
+
"""Interactive setup — write a new configuration file."""
|
|
252
|
+
cfg = _load_config()
|
|
253
|
+
cfg["spacetime_url"] = url
|
|
254
|
+
cfg["database"] = database
|
|
255
|
+
if token:
|
|
256
|
+
cfg["token"] = token
|
|
257
|
+
if not cfg.get("agent_id"):
|
|
258
|
+
cfg["agent_id"] = f"cli-{uuid.uuid4().hex[:12]}"
|
|
259
|
+
_save_config(cfg)
|
|
260
|
+
click.echo(f"Configuration saved to {CONFIG_FILE}")
|
|
261
|
+
click.echo(f" agent_id: {cfg['agent_id']}")
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
# ---------------------------------------------------------------------------
|
|
265
|
+
# register
|
|
266
|
+
# ---------------------------------------------------------------------------
|
|
267
|
+
|
|
268
|
+
@cli.command()
|
|
269
|
+
@click.option("--hostname", default=None, help="Override hostname (defaults to system hostname)")
|
|
270
|
+
@click.option("--os-type", default=None, help="Override OS type (defaults to platform.system())")
|
|
271
|
+
@click.option("--capabilities", default=None, help="JSON blob of agent capabilities")
|
|
272
|
+
@click.pass_context
|
|
273
|
+
def register(ctx: click.Context, hostname: Optional[str], os_type: Optional[str], capabilities: Optional[str]) -> None:
|
|
274
|
+
"""Register this agent with the Nullcone network.
|
|
275
|
+
|
|
276
|
+
Generates a stable agent_id (persisted in config) on first run.
|
|
277
|
+
Safe to call multiple times — registration is idempotent.
|
|
278
|
+
"""
|
|
279
|
+
as_json = ctx.obj["as_json"]
|
|
280
|
+
agent, cfg = _make_agent(
|
|
281
|
+
ctx.obj["url"], ctx.obj["database"], ctx.obj["agent_id"], ctx.obj["token"]
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
if hostname:
|
|
285
|
+
agent._hostname = hostname # type: ignore[attr-defined]
|
|
286
|
+
if os_type:
|
|
287
|
+
agent._os_type = os_type # type: ignore[attr-defined]
|
|
288
|
+
|
|
289
|
+
caps_dict: dict[str, Any] = {}
|
|
290
|
+
if capabilities:
|
|
291
|
+
try:
|
|
292
|
+
caps_dict = json.loads(capabilities)
|
|
293
|
+
except json.JSONDecodeError:
|
|
294
|
+
_err(f"--capabilities must be valid JSON", as_json)
|
|
295
|
+
|
|
296
|
+
try:
|
|
297
|
+
agent.register()
|
|
298
|
+
result = {
|
|
299
|
+
"status": "registered",
|
|
300
|
+
"agent_id": agent.agent_id,
|
|
301
|
+
"spacetime_url": agent._client.base_url, # type: ignore[attr-defined]
|
|
302
|
+
"database": agent._client.database, # type: ignore[attr-defined]
|
|
303
|
+
}
|
|
304
|
+
if as_json:
|
|
305
|
+
_out(result, True)
|
|
306
|
+
else:
|
|
307
|
+
click.echo(f"Registered agent: {agent.agent_id}")
|
|
308
|
+
click.echo(f" server: {agent._client.base_url}") # type: ignore[attr-defined]
|
|
309
|
+
click.echo(f" database: {agent._client.database}") # type: ignore[attr-defined]
|
|
310
|
+
except Exception as exc:
|
|
311
|
+
_err(str(exc), as_json)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
# ---------------------------------------------------------------------------
|
|
315
|
+
# submit
|
|
316
|
+
# ---------------------------------------------------------------------------
|
|
317
|
+
|
|
318
|
+
@cli.command()
|
|
319
|
+
@click.argument("value")
|
|
320
|
+
@click.option("-t", "--type", "ioc_type", required=True, help="IOC type (e.g. ip, domain, sha256, url, cve, prompt, skill)")
|
|
321
|
+
@click.option("-s", "--severity", default="5", help="Severity 0-10 or name (info/low/medium/high/critical). Default: 5")
|
|
322
|
+
@click.option("-c", "--confidence", default=70, type=int, help="Confidence 0-100. Default: 70")
|
|
323
|
+
@click.option("--tags", default="", help="Comma-separated tags (e.g. c2,botnet)")
|
|
324
|
+
@click.option("--source", default="cli", help="Source identifier. Default: cli")
|
|
325
|
+
@click.option("--context", "ctx_text", default="", help="Free-text context / notes")
|
|
326
|
+
@click.option("--family", default=None, help="Malware family hint (e.g. emotet, cobalt-strike)")
|
|
327
|
+
@click.pass_context
|
|
328
|
+
def submit(
|
|
329
|
+
ctx: click.Context,
|
|
330
|
+
value: str,
|
|
331
|
+
ioc_type: str,
|
|
332
|
+
severity: str,
|
|
333
|
+
confidence: int,
|
|
334
|
+
tags: str,
|
|
335
|
+
source: str,
|
|
336
|
+
ctx_text: str,
|
|
337
|
+
family: Optional[str],
|
|
338
|
+
) -> None:
|
|
339
|
+
"""Submit a single IOC to the threat database.
|
|
340
|
+
|
|
341
|
+
\b
|
|
342
|
+
Examples:
|
|
343
|
+
nullcone submit 1.2.3.4 -t ip -s high --tags c2,botnet
|
|
344
|
+
nullcone submit evil.example.com -t domain -s 7
|
|
345
|
+
nullcone submit CVE-2024-1337 -t cve -s critical
|
|
346
|
+
nullcone submit "ignore previous instructions" -t prompt -s 8
|
|
347
|
+
"""
|
|
348
|
+
as_json = ctx.obj["as_json"]
|
|
349
|
+
try:
|
|
350
|
+
parsed_type = _parse_ioc_type(ioc_type)
|
|
351
|
+
parsed_severity = _parse_severity(severity)
|
|
352
|
+
except click.BadParameter as e:
|
|
353
|
+
_err(str(e), as_json)
|
|
354
|
+
return
|
|
355
|
+
|
|
356
|
+
tag_list = [t.strip() for t in tags.split(",") if t.strip()] if tags else []
|
|
357
|
+
|
|
358
|
+
ioc = IOC(
|
|
359
|
+
ioc_type=parsed_type,
|
|
360
|
+
value=value,
|
|
361
|
+
severity=parsed_severity,
|
|
362
|
+
confidence=max(0, min(100, confidence)),
|
|
363
|
+
family_hint=family,
|
|
364
|
+
context=ctx_text,
|
|
365
|
+
tags=tag_list,
|
|
366
|
+
source=source,
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
agent, _ = _make_agent(
|
|
370
|
+
ctx.obj["url"], ctx.obj["database"], ctx.obj["agent_id"], ctx.obj["token"]
|
|
371
|
+
)
|
|
372
|
+
try:
|
|
373
|
+
agent.register()
|
|
374
|
+
result = agent.submit_ioc(ioc)
|
|
375
|
+
if as_json:
|
|
376
|
+
_out({
|
|
377
|
+
"status": result.status,
|
|
378
|
+
"signature_id": result.signature_id,
|
|
379
|
+
"detection_count": result.detection_count,
|
|
380
|
+
"message": result.message,
|
|
381
|
+
"value_hash": ioc.value_hash(),
|
|
382
|
+
}, True)
|
|
383
|
+
else:
|
|
384
|
+
status_symbol = {"new": "[+]", "duplicate": "[=]", "updated": "[^]", "error": "[!]"}.get(result.status, "[?]")
|
|
385
|
+
click.echo(f"{status_symbol} {result.status.upper()} id={result.signature_id} detections={result.detection_count}")
|
|
386
|
+
if result.message:
|
|
387
|
+
click.echo(f" {result.message}")
|
|
388
|
+
except Exception as exc:
|
|
389
|
+
_err(str(exc), as_json)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
# ---------------------------------------------------------------------------
|
|
393
|
+
# submit-batch
|
|
394
|
+
# ---------------------------------------------------------------------------
|
|
395
|
+
|
|
396
|
+
@cli.command("submit-batch")
|
|
397
|
+
@click.argument("file", type=click.Path(exists=True, dir_okay=False))
|
|
398
|
+
@click.option("--source", default="cli-batch", help="Default source if not in file. Default: cli-batch")
|
|
399
|
+
@click.pass_context
|
|
400
|
+
def submit_batch(ctx: click.Context, file: str, source: str) -> None:
|
|
401
|
+
"""Submit a batch of IOCs from a JSON file.
|
|
402
|
+
|
|
403
|
+
\b
|
|
404
|
+
File format (list of objects):
|
|
405
|
+
[
|
|
406
|
+
{"type": "ip", "value": "1.2.3.4", "severity": 7, "tags": ["c2"]},
|
|
407
|
+
{"type": "domain", "value": "evil.example.com", "severity": 5}
|
|
408
|
+
]
|
|
409
|
+
"""
|
|
410
|
+
as_json = ctx.obj["as_json"]
|
|
411
|
+
try:
|
|
412
|
+
raw = json.loads(Path(file).read_text())
|
|
413
|
+
except Exception as e:
|
|
414
|
+
_err(f"Could not parse JSON file: {e}", as_json)
|
|
415
|
+
return
|
|
416
|
+
|
|
417
|
+
if not isinstance(raw, list):
|
|
418
|
+
_err("JSON file must contain a list of IOC objects", as_json)
|
|
419
|
+
return
|
|
420
|
+
|
|
421
|
+
iocs: list[IOC] = []
|
|
422
|
+
errors: list[dict[str, Any]] = []
|
|
423
|
+
for i, item in enumerate(raw):
|
|
424
|
+
try:
|
|
425
|
+
ioc_type = _parse_ioc_type(item.get("type", item.get("ioc_type", "")))
|
|
426
|
+
sev_raw = item.get("severity", 5)
|
|
427
|
+
sev = _parse_severity(str(sev_raw)) if isinstance(sev_raw, str) else int(sev_raw)
|
|
428
|
+
tags = item.get("tags", [])
|
|
429
|
+
if isinstance(tags, str):
|
|
430
|
+
tags = [t.strip() for t in tags.split(",") if t.strip()]
|
|
431
|
+
iocs.append(IOC(
|
|
432
|
+
ioc_type=ioc_type,
|
|
433
|
+
value=item["value"],
|
|
434
|
+
severity=sev,
|
|
435
|
+
confidence=int(item.get("confidence", 70)),
|
|
436
|
+
family_hint=item.get("family") or item.get("family_hint"),
|
|
437
|
+
context=item.get("context", ""),
|
|
438
|
+
tags=tags,
|
|
439
|
+
source=item.get("source", source),
|
|
440
|
+
))
|
|
441
|
+
except Exception as e:
|
|
442
|
+
errors.append({"index": i, "item": item, "error": str(e)})
|
|
443
|
+
|
|
444
|
+
if errors and not as_json:
|
|
445
|
+
click.echo(f"Warning: {len(errors)} item(s) skipped due to parse errors", err=True)
|
|
446
|
+
|
|
447
|
+
if not iocs:
|
|
448
|
+
_err("No valid IOCs to submit", as_json)
|
|
449
|
+
return
|
|
450
|
+
|
|
451
|
+
agent, _ = _make_agent(
|
|
452
|
+
ctx.obj["url"], ctx.obj["database"], ctx.obj["agent_id"], ctx.obj["token"]
|
|
453
|
+
)
|
|
454
|
+
try:
|
|
455
|
+
agent.register()
|
|
456
|
+
results = agent.submit_batch(iocs)
|
|
457
|
+
except Exception as exc:
|
|
458
|
+
_err(str(exc), as_json)
|
|
459
|
+
return
|
|
460
|
+
|
|
461
|
+
counts: dict[str, int] = {"new": 0, "duplicate": 0, "updated": 0, "error": 0}
|
|
462
|
+
out_results = []
|
|
463
|
+
for ioc, result in zip(iocs, results):
|
|
464
|
+
counts[result.status] = counts.get(result.status, 0) + 1
|
|
465
|
+
out_results.append({
|
|
466
|
+
"status": result.status,
|
|
467
|
+
"signature_id": result.signature_id,
|
|
468
|
+
"value": ioc.value,
|
|
469
|
+
"ioc_type": ioc.ioc_type.value,
|
|
470
|
+
})
|
|
471
|
+
|
|
472
|
+
if as_json:
|
|
473
|
+
_out({"summary": counts, "parse_errors": errors, "results": out_results}, True)
|
|
474
|
+
else:
|
|
475
|
+
click.echo(f"Submitted {len(iocs)} IOC(s): {counts['new']} new, {counts['duplicate']} duplicate, {counts['updated']} updated, {counts['error']} errors")
|
|
476
|
+
if errors:
|
|
477
|
+
click.echo(f" {len(errors)} item(s) skipped (parse errors)")
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
# ---------------------------------------------------------------------------
|
|
481
|
+
# lookup
|
|
482
|
+
# ---------------------------------------------------------------------------
|
|
483
|
+
|
|
484
|
+
@cli.command()
|
|
485
|
+
@click.argument("value")
|
|
486
|
+
@click.option("--hash", "by_hash", is_flag=True, help="Treat VALUE as a value_hash (64-char hex) instead of raw IOC value")
|
|
487
|
+
@click.pass_context
|
|
488
|
+
def lookup(ctx: click.Context, value: str, by_hash: bool) -> None:
|
|
489
|
+
"""Look up a single IOC by value or value_hash.
|
|
490
|
+
|
|
491
|
+
\b
|
|
492
|
+
Examples:
|
|
493
|
+
nullcone lookup 1.2.3.4
|
|
494
|
+
nullcone lookup --hash a3f2c1...
|
|
495
|
+
"""
|
|
496
|
+
as_json = ctx.obj["as_json"]
|
|
497
|
+
agent, _ = _make_agent(
|
|
498
|
+
ctx.obj["url"], ctx.obj["database"], ctx.obj["agent_id"], ctx.obj["token"]
|
|
499
|
+
)
|
|
500
|
+
try:
|
|
501
|
+
sig = agent.find_by_hash(value) if by_hash else agent.find_by_value(value)
|
|
502
|
+
except Exception as exc:
|
|
503
|
+
_err(str(exc), as_json)
|
|
504
|
+
return
|
|
505
|
+
|
|
506
|
+
if sig is None:
|
|
507
|
+
if as_json:
|
|
508
|
+
_out({"found": False, "value": value}, True)
|
|
509
|
+
else:
|
|
510
|
+
click.echo(f"Not found: {value}", err=True)
|
|
511
|
+
sys.exit(2)
|
|
512
|
+
|
|
513
|
+
if as_json:
|
|
514
|
+
_out({
|
|
515
|
+
"found": True,
|
|
516
|
+
"id": sig.id,
|
|
517
|
+
"ioc_type": sig.ioc_type,
|
|
518
|
+
"value": sig.value,
|
|
519
|
+
"value_hash": sig.value_hash,
|
|
520
|
+
"family": sig.family_name,
|
|
521
|
+
"severity": sig.severity,
|
|
522
|
+
"confidence": sig.confidence,
|
|
523
|
+
"first_seen": sig.first_seen,
|
|
524
|
+
"last_seen": sig.last_seen,
|
|
525
|
+
"detection_count": sig.detection_count,
|
|
526
|
+
"false_positive_votes": sig.false_positive_votes,
|
|
527
|
+
"tags": sig.tag_list,
|
|
528
|
+
"source_agent": sig.source_agent_id,
|
|
529
|
+
"is_likely_fp": sig.is_likely_fp,
|
|
530
|
+
}, True)
|
|
531
|
+
else:
|
|
532
|
+
sev_label = _severity_label(sig.severity)
|
|
533
|
+
fp_note = " [LIKELY FALSE POSITIVE]" if sig.is_likely_fp else ""
|
|
534
|
+
click.echo(f" id: {sig.id}")
|
|
535
|
+
click.echo(f" type: {sig.ioc_type}")
|
|
536
|
+
click.echo(f" value: {sig.value}")
|
|
537
|
+
click.echo(f" family: {sig.family_name or '(unknown)'}")
|
|
538
|
+
click.echo(f" severity: {sig.severity}/10 ({sev_label}){fp_note}")
|
|
539
|
+
click.echo(f" confidence: {sig.confidence}%")
|
|
540
|
+
click.echo(f" detections: {sig.detection_count}")
|
|
541
|
+
click.echo(f" first_seen: {sig.first_seen}")
|
|
542
|
+
click.echo(f" last_seen: {sig.last_seen}")
|
|
543
|
+
if sig.tag_list:
|
|
544
|
+
click.echo(f" tags: {', '.join(sig.tag_list)}")
|
|
545
|
+
click.echo(f" source: {sig.source_agent_id}")
|
|
546
|
+
click.echo(f" value_hash: {sig.value_hash}")
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
# ---------------------------------------------------------------------------
|
|
550
|
+
# threats
|
|
551
|
+
# ---------------------------------------------------------------------------
|
|
552
|
+
|
|
553
|
+
@cli.command()
|
|
554
|
+
@click.option("-l", "--limit", default=20, show_default=True, help="Max results to return")
|
|
555
|
+
@click.option("-m", "--min-severity", default=0, show_default=True, help="Minimum severity (0-10)")
|
|
556
|
+
@click.pass_context
|
|
557
|
+
def threats(ctx: click.Context, limit: int, min_severity: int) -> None:
|
|
558
|
+
"""List recent threat signatures."""
|
|
559
|
+
as_json = ctx.obj["as_json"]
|
|
560
|
+
agent, _ = _make_agent(
|
|
561
|
+
ctx.obj["url"], ctx.obj["database"], ctx.obj["agent_id"], ctx.obj["token"]
|
|
562
|
+
)
|
|
563
|
+
try:
|
|
564
|
+
sigs = agent.recent_threats(limit=limit, min_severity=min_severity)
|
|
565
|
+
except Exception as exc:
|
|
566
|
+
_err(str(exc), as_json)
|
|
567
|
+
return
|
|
568
|
+
|
|
569
|
+
if as_json:
|
|
570
|
+
_out([{
|
|
571
|
+
"id": s.id,
|
|
572
|
+
"ioc_type": s.ioc_type,
|
|
573
|
+
"value": s.value,
|
|
574
|
+
"family": s.family_name,
|
|
575
|
+
"severity": s.severity,
|
|
576
|
+
"confidence": s.confidence,
|
|
577
|
+
"detection_count": s.detection_count,
|
|
578
|
+
"last_seen": s.last_seen,
|
|
579
|
+
"tags": s.tag_list,
|
|
580
|
+
"is_likely_fp": s.is_likely_fp,
|
|
581
|
+
} for s in sigs], True)
|
|
582
|
+
else:
|
|
583
|
+
if not sigs:
|
|
584
|
+
click.echo("No threats found.")
|
|
585
|
+
return
|
|
586
|
+
click.echo(f"{'ID':>8} {'SEV':>4} {'TYPE':<12} {'FAMILY':<20} VALUE")
|
|
587
|
+
click.echo("-" * 80)
|
|
588
|
+
for s in sigs:
|
|
589
|
+
sev_label = _severity_label(s.severity)
|
|
590
|
+
family = (s.family_name[:18] + "..") if len(s.family_name) > 20 else s.family_name or "(unknown)"
|
|
591
|
+
value_display = (s.value[:40] + "..") if len(s.value) > 42 else s.value
|
|
592
|
+
click.echo(f"{s.id:>8} {sev_label:>4} {s.ioc_type:<12} {family:<20} {value_display}")
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
# ---------------------------------------------------------------------------
|
|
596
|
+
# stats
|
|
597
|
+
# ---------------------------------------------------------------------------
|
|
598
|
+
|
|
599
|
+
@cli.command()
|
|
600
|
+
@click.pass_context
|
|
601
|
+
def stats(ctx: click.Context) -> None:
|
|
602
|
+
"""Show aggregate database statistics."""
|
|
603
|
+
as_json = ctx.obj["as_json"]
|
|
604
|
+
agent, _ = _make_agent(
|
|
605
|
+
ctx.obj["url"], ctx.obj["database"], ctx.obj["agent_id"], ctx.obj["token"]
|
|
606
|
+
)
|
|
607
|
+
try:
|
|
608
|
+
data = agent.stats()
|
|
609
|
+
except Exception as exc:
|
|
610
|
+
_err(str(exc), as_json)
|
|
611
|
+
return
|
|
612
|
+
|
|
613
|
+
if as_json:
|
|
614
|
+
_out(data, True)
|
|
615
|
+
else:
|
|
616
|
+
for k, v in data.items():
|
|
617
|
+
click.echo(f" {k}: {v}")
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
# ---------------------------------------------------------------------------
|
|
621
|
+
# poll
|
|
622
|
+
# ---------------------------------------------------------------------------
|
|
623
|
+
|
|
624
|
+
@cli.command()
|
|
625
|
+
@click.option("--since", default=0, show_default=True, help="Fetch IOCs with id > SINCE (use 0 for all)")
|
|
626
|
+
@click.option("--batch-size", default=1000, show_default=True, help="Max results per page")
|
|
627
|
+
@click.option("--min-severity", default=0, show_default=True, help="Minimum severity (0-10)")
|
|
628
|
+
@click.option("--watch", is_flag=True, help="Continuously poll; print new threats as they arrive")
|
|
629
|
+
@click.option("--interval", default=60, show_default=True, help="Poll interval in seconds (--watch only)")
|
|
630
|
+
@click.option("--state-file", default=None, help="File to persist high-water mark across runs")
|
|
631
|
+
@click.pass_context
|
|
632
|
+
def poll(
|
|
633
|
+
ctx: click.Context,
|
|
634
|
+
since: int,
|
|
635
|
+
batch_size: int,
|
|
636
|
+
min_severity: int,
|
|
637
|
+
watch: bool,
|
|
638
|
+
interval: int,
|
|
639
|
+
state_file: Optional[str],
|
|
640
|
+
) -> None:
|
|
641
|
+
"""Poll the database for new threat signatures since a given ID.
|
|
642
|
+
|
|
643
|
+
With --watch, runs continuously and prints new threats as they arrive.
|
|
644
|
+
The --state-file persists the high-water mark so you can resume later.
|
|
645
|
+
|
|
646
|
+
\b
|
|
647
|
+
Examples:
|
|
648
|
+
nullcone poll --since 0 --json | jq '.[-1].id' # get latest id
|
|
649
|
+
nullcone poll --watch --min-severity 7 # stream high-severity alerts
|
|
650
|
+
nullcone poll --since 591000 --state-file /tmp/nc.state
|
|
651
|
+
"""
|
|
652
|
+
as_json = ctx.obj["as_json"]
|
|
653
|
+
|
|
654
|
+
# Load persisted HWM from state file if provided
|
|
655
|
+
hwm = since
|
|
656
|
+
sf_path: Optional[Path] = None
|
|
657
|
+
if state_file:
|
|
658
|
+
sf_path = Path(state_file)
|
|
659
|
+
if sf_path.exists():
|
|
660
|
+
try:
|
|
661
|
+
saved = json.loads(sf_path.read_text())
|
|
662
|
+
hwm = int(saved.get("last_id", since))
|
|
663
|
+
except Exception:
|
|
664
|
+
pass
|
|
665
|
+
|
|
666
|
+
agent, _ = _make_agent(
|
|
667
|
+
ctx.obj["url"], ctx.obj["database"], ctx.obj["agent_id"], ctx.obj["token"]
|
|
668
|
+
)
|
|
669
|
+
|
|
670
|
+
def _do_poll(current_hwm: int) -> int:
|
|
671
|
+
sigs, new_hwm = agent.poll_since(
|
|
672
|
+
last_id=current_hwm, batch_size=batch_size, min_severity=min_severity
|
|
673
|
+
)
|
|
674
|
+
if sigs:
|
|
675
|
+
if as_json:
|
|
676
|
+
_out([{
|
|
677
|
+
"id": s.id,
|
|
678
|
+
"ioc_type": s.ioc_type,
|
|
679
|
+
"value": s.value,
|
|
680
|
+
"family": s.family_name,
|
|
681
|
+
"severity": s.severity,
|
|
682
|
+
"confidence": s.confidence,
|
|
683
|
+
"detection_count": s.detection_count,
|
|
684
|
+
"last_seen": s.last_seen,
|
|
685
|
+
"tags": s.tag_list,
|
|
686
|
+
} for s in sigs], True)
|
|
687
|
+
else:
|
|
688
|
+
for s in sigs:
|
|
689
|
+
sev_label = _severity_label(s.severity)
|
|
690
|
+
click.echo(f"[{s.id}] {sev_label:<8} {s.ioc_type:<12} {s.value[:60]}")
|
|
691
|
+
elif not watch and not as_json:
|
|
692
|
+
click.echo(f"No new threats since id={current_hwm}")
|
|
693
|
+
|
|
694
|
+
if sf_path and new_hwm > current_hwm:
|
|
695
|
+
sf_path.write_text(json.dumps({"last_id": new_hwm}))
|
|
696
|
+
return new_hwm
|
|
697
|
+
|
|
698
|
+
if not watch:
|
|
699
|
+
_do_poll(hwm)
|
|
700
|
+
return
|
|
701
|
+
|
|
702
|
+
if not as_json:
|
|
703
|
+
click.echo(f"Watching for new threats every {interval}s (Ctrl-C to stop)...", err=True)
|
|
704
|
+
|
|
705
|
+
try:
|
|
706
|
+
while True:
|
|
707
|
+
hwm = _do_poll(hwm)
|
|
708
|
+
time.sleep(interval)
|
|
709
|
+
except KeyboardInterrupt:
|
|
710
|
+
if not as_json:
|
|
711
|
+
click.echo("\nStopped.", err=True)
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
# ---------------------------------------------------------------------------
|
|
715
|
+
# detect
|
|
716
|
+
# ---------------------------------------------------------------------------
|
|
717
|
+
|
|
718
|
+
@cli.command()
|
|
719
|
+
@click.argument("signature_id", type=int)
|
|
720
|
+
@click.option("-a", "--action", required=True,
|
|
721
|
+
help="Action taken: logged, alerted, blocked, quarantined, eradicated")
|
|
722
|
+
@click.option("--context", "ctx_json", default=None, help="Optional JSON context blob")
|
|
723
|
+
@click.pass_context
|
|
724
|
+
def detect(ctx: click.Context, signature_id: int, action: str, ctx_json: Optional[str]) -> None:
|
|
725
|
+
"""Report that this agent detected a known threat signature.
|
|
726
|
+
|
|
727
|
+
\b
|
|
728
|
+
Examples:
|
|
729
|
+
nullcone detect 12345 --action blocked
|
|
730
|
+
nullcone detect 12345 --action quarantined --context '{"process":"malware.exe"}'
|
|
731
|
+
"""
|
|
732
|
+
as_json = ctx.obj["as_json"]
|
|
733
|
+
try:
|
|
734
|
+
parsed_action = _parse_action(action)
|
|
735
|
+
except click.BadParameter as e:
|
|
736
|
+
_err(str(e), as_json)
|
|
737
|
+
return
|
|
738
|
+
|
|
739
|
+
context_dict: dict[str, Any] = {}
|
|
740
|
+
if ctx_json:
|
|
741
|
+
try:
|
|
742
|
+
context_dict = json.loads(ctx_json)
|
|
743
|
+
except json.JSONDecodeError:
|
|
744
|
+
_err("--context must be valid JSON", as_json)
|
|
745
|
+
return
|
|
746
|
+
|
|
747
|
+
agent, _ = _make_agent(
|
|
748
|
+
ctx.obj["url"], ctx.obj["database"], ctx.obj["agent_id"], ctx.obj["token"]
|
|
749
|
+
)
|
|
750
|
+
try:
|
|
751
|
+
agent.report_detection(signature_id, parsed_action, context_dict or None)
|
|
752
|
+
if as_json:
|
|
753
|
+
_out({"status": "ok", "signature_id": signature_id, "action": action}, True)
|
|
754
|
+
else:
|
|
755
|
+
click.echo(f"Detection reported: id={signature_id}, action={action}")
|
|
756
|
+
except Exception as exc:
|
|
757
|
+
_err(str(exc), as_json)
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
# ---------------------------------------------------------------------------
|
|
761
|
+
# vote-fp
|
|
762
|
+
# ---------------------------------------------------------------------------
|
|
763
|
+
|
|
764
|
+
@cli.command("vote-fp")
|
|
765
|
+
@click.argument("signature_id", type=int)
|
|
766
|
+
@click.option("--reason", default="", help="Optional reason for false positive vote")
|
|
767
|
+
@click.pass_context
|
|
768
|
+
def vote_fp(ctx: click.Context, signature_id: int, reason: str) -> None:
|
|
769
|
+
"""Vote that a threat signature is a false positive.
|
|
770
|
+
|
|
771
|
+
If >20% of reporting agents vote FP, the signature is flagged.
|
|
772
|
+
"""
|
|
773
|
+
as_json = ctx.obj["as_json"]
|
|
774
|
+
agent, _ = _make_agent(
|
|
775
|
+
ctx.obj["url"], ctx.obj["database"], ctx.obj["agent_id"], ctx.obj["token"]
|
|
776
|
+
)
|
|
777
|
+
try:
|
|
778
|
+
agent.vote_false_positive(signature_id, reason)
|
|
779
|
+
if as_json:
|
|
780
|
+
_out({"status": "voted", "signature_id": signature_id}, True)
|
|
781
|
+
else:
|
|
782
|
+
click.echo(f"False positive vote recorded for id={signature_id}")
|
|
783
|
+
except Exception as exc:
|
|
784
|
+
_err(str(exc), as_json)
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
# ---------------------------------------------------------------------------
|
|
788
|
+
# Entry point
|
|
789
|
+
# ---------------------------------------------------------------------------
|
|
790
|
+
|
|
791
|
+
def main() -> None:
|
|
792
|
+
cli(obj={})
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
if __name__ == "__main__":
|
|
796
|
+
main()
|