File size: 21,841 Bytes
4bfe235 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 | #!/usr/bin/env python3
"""Build a 100%-Shodan-covered, 100%-vendor-labeled validation set."""
from __future__ import annotations
import argparse
import asyncio
import csv
import json
import math
import sys
import time
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any
import httpx
import pipeline as p
def pool_rows() -> dict[str, list[dict[str, Any]]]:
return {
device_type: p.read_jsonl(
p.DATA / "censys_raw" / f"{device_type}.jsonl.gz"
)
for device_type in p.device_types()
}
def snapshot_pool() -> None:
p.ensure_dirs()
rows_by_type = pool_rows()
manifest = []
for device_type, rows in rows_by_type.items():
features = []
for rank, row in enumerate(rows, start=1):
resource = row.get("resource") or {}
ip = p.clean(resource.get("ip"))
features.append(p.extract_features(resource))
manifest.append(
{
"sample_id": f"{device_type}:{ip}",
"device_type": device_type,
"ip": ip,
"query_rank": rank,
"collected_at": row.get("collected_at") or "",
}
)
p.atomic_csv(
p.DATA / f"candidate_ipraw_{device_type}.csv",
features,
p.CSV_FIELDS,
)
p.atomic_csv(
p.DATA / "candidate_manifest.csv",
manifest,
["sample_id", "device_type", "ip", "query_rank", "collected_at"],
)
p.atomic_json(
p.DATA / "candidate_pool_metadata.json",
{
"updated_at": p.utc_now(),
"counts": {
device_type: len(rows)
for device_type, rows in rows_by_type.items()
},
"unique_ips": len({row["ip"] for row in manifest}),
"initial_pool_per_type": 200,
},
)
print(
"[pool] "
+ ", ".join(
f"{device_type}={len(rows)}"
for device_type, rows in rows_by_type.items()
)
)
def search_with_retry(sdk: Any, body: dict[str, Any]) -> dict[str, Any]:
for attempt in range(6):
try:
return sdk.global_data.search(
search_query_input_body=body,
timeout_ms=120000,
).model_dump()
except Exception:
if attempt == 5:
raise
time.sleep(min(30, 2 ** (attempt + 1)))
raise RuntimeError("unreachable")
def hydrate_with_retry(sdk: Any, ips: list[str]) -> list[dict[str, Any]]:
for attempt in range(6):
try:
response = sdk.global_data.get_hosts(
asset_host_list_input_body={"host_ids": ips},
timeout_ms=120000,
).model_dump()
return response.get("result", {}).get("result", [])
except Exception:
if attempt == 5:
raise
time.sleep(min(30, 2 ** (attempt + 1)))
return []
def expand_pool(target: int, selected_types: list[str] | None) -> None:
from censys_platform import SDK
p.ensure_dirs()
types = selected_types or p.device_types()
unknown = set(types) - set(p.device_types())
if unknown:
raise ValueError(f"unknown device types: {sorted(unknown)}")
config = json.loads(p.SEARCH_CONFIG.read_text())["censys"]["platform"]
sdk = SDK(
organization_id=config["org_id"],
personal_access_token=config["personal_access_token"],
)
rows_by_type = pool_rows()
globally_seen = {
p.clean((row.get("resource") or {}).get("ip"))
for rows in rows_by_type.values()
for row in rows
if p.clean((row.get("resource") or {}).get("ip"))
}
for device_type in types:
rows = rows_by_type[device_type]
own_ips = {
p.clean((row.get("resource") or {}).get("ip")) for row in rows
}
globally_seen.difference_update(own_ips)
query = p.censys_query(device_type)
token = ""
pages = 0
exhausted = False
while len(rows) < target and not exhausted:
body: dict[str, Any] = {
"fields": ["host.ip"],
"page_size": 100,
"query": query,
}
if token:
body["page_token"] = token
response = search_with_retry(sdk, body)
result = response.get("result", {}).get("result", {})
pages += 1
candidates = []
for hit in result.get("hits") or []:
ip = p.clean(p.host_resource(hit).get("ip"))
if not ip or ip in globally_seen or ip in own_ips:
continue
candidates.append(ip)
if len(candidates) >= min(100, target - len(rows)):
break
hydrated = hydrate_with_retry(sdk, candidates) if candidates else []
resources = {
p.clean((item.get("resource") or {}).get("ip")): (
item.get("resource") or {}
)
for item in hydrated
}
for ip in candidates:
resource = resources.get(ip)
if not resource:
continue
rows.append(
{
"device_type": device_type,
"query": query,
"query_rank": len(rows) + 1,
"collected_at": p.utc_now(),
"resource": resource,
}
)
own_ips.add(ip)
globally_seen.add(ip)
p.atomic_jsonl_gz(
p.DATA / "censys_raw" / f"{device_type}.jsonl.gz",
rows,
)
print(
f"[expand] {device_type}: {len(rows)}/{target} "
f"after page {pages}",
flush=True,
)
token = p.clean(result.get("next_page_token"))
exhausted = not token
if pages >= 100:
raise RuntimeError(f"{device_type}: page safety limit reached")
globally_seen.update(own_ips)
if len(rows) < target:
print(
f"[expand] {device_type}: exhausted at {len(rows)} records",
flush=True,
)
snapshot_pool()
async def collect_candidate_shodan() -> None:
p.ensure_dirs()
manifest = p.read_csv(p.DATA / "candidate_manifest.csv")
path = p.DATA / "shodan_hosts.jsonl.gz"
cache = {row["ip"]: row for row in p.read_jsonl(path)}
pending = [
row["ip"]
for row in manifest
if row["ip"] not in cache or cache[row["ip"]].get("status") == "error"
]
api_key = json.loads(p.SEARCH_CONFIG.read_text())["shodan"]["api_key"]
rate_lock = asyncio.Lock()
next_request_at = 0.0
semaphore = asyncio.Semaphore(32)
async with httpx.AsyncClient(
timeout=httpx.Timeout(12, connect=8)
) as client:
async def request(ip: str, minified: bool) -> httpx.Response:
nonlocal next_request_at
async with rate_lock:
loop = asyncio.get_running_loop()
delay = next_request_at - loop.time()
if delay > 0:
await asyncio.sleep(delay)
next_request_at = loop.time() + 1.05
return await asyncio.wait_for(
client.get(
p.SHODAN_HOST_URL.format(ip=ip),
params={
"key": api_key,
"minify": str(minified).lower(),
},
),
timeout=10 if minified else 15,
)
async def fetch(ip: str) -> dict[str, Any]:
async with semaphore:
for attempt in range(2):
minified = attempt == 1
try:
response = await request(ip, minified)
except (httpx.RequestError, asyncio.TimeoutError) as exc:
if attempt == 0:
continue
return {
"ip": ip,
"status": "error",
"error": f"{type(exc).__name__}: {exc}",
"collected_at": p.utc_now(),
}
if response.status_code == 200:
return {
"ip": ip,
"status": "ok",
"collected_at": p.utc_now(),
"resource": p.compact_shodan(
response.json(),
minified,
),
}
if response.status_code == 404:
return {
"ip": ip,
"status": "not_found",
"collected_at": p.utc_now(),
}
if response.status_code == 429:
await asyncio.sleep(3)
continue
if response.status_code >= 500 and attempt == 0:
continue
return {
"ip": ip,
"status": "error",
"error": (
f"HTTP {response.status_code}: "
f"{response.text[:300]}"
),
"collected_at": p.utc_now(),
}
return {"ip": ip, "status": "error", "error": "retry exhausted"}
for offset in range(0, len(pending), 50):
chunk = pending[offset : offset + 50]
rows = await asyncio.gather(*(fetch(ip) for ip in chunk))
for row in rows:
cache[row["ip"]] = row
ordered = [
cache[row["ip"]]
for row in manifest
if row["ip"] in cache
]
p.atomic_jsonl_gz(path, ordered)
print(
f"[shodan-pool] {offset + len(chunk)}/{len(pending)}; "
f"cached={len(cache)}",
flush=True,
)
def candidate_labels() -> dict[str, dict[str, str]]:
result = {}
for device_type in p.device_types():
path = p.LABEL / f"candidate_label_{device_type}.csv"
result[device_type] = (
{row["ip"]: row["vendor"] for row in p.read_csv(path)}
if path.exists()
else {}
)
return result
def prepare_label_round(round_name: str, batch_size: int) -> None:
p.ensure_dirs()
manifest = p.read_csv(p.DATA / "candidate_manifest.csv")
shodan = {
row["ip"]: row
for row in p.read_jsonl(p.DATA / "shodan_hosts.jsonl.gz")
}
existing = candidate_labels()
fingerprints = {
device_type: {
row["ip"]: row
for row in p.read_csv(
p.DATA / f"candidate_ipraw_{device_type}.csv"
)
}
for device_type in p.device_types()
}
eligible_unlabeled: dict[str, list[str]] = defaultdict(list)
for row in manifest:
device_type = row["device_type"]
ip = row["ip"]
if (shodan.get(ip) or {}).get("status") != "ok":
continue
if ip in existing[device_type]:
continue
eligible_unlabeled[device_type].append(ip)
batches = {}
items = []
for device_type in p.device_types():
ips = eligible_unlabeled[device_type]
for offset in range(0, len(ips), batch_size):
batch_ips = ips[offset : offset + batch_size]
item_id = f"{round_name}:{device_type}:{offset // batch_size:04d}"
sections = []
for ip in batch_ips:
row = fingerprints[device_type][ip]
evidence = [
f"{field}: {p.truncate(row.get(field))}"
for field in p.DISPLAY_FEATURES
if p.truncate(row.get(field))
]
sections.append(f"[IP: {ip}]\n" + "\n".join(evidence))
content = (
f"Device type: {device_type}\n\n"
+ "\n\n".join(sections)
)
items.append({"id": item_id, "content": content})
batches[item_id] = {
"device_type": device_type,
"ips": batch_ips,
"content": content,
}
p.LABEL.mkdir(parents=True, exist_ok=True)
input_path = p.LABEL / f"{round_name}_input.jsonl"
with input_path.open("w", encoding="utf-8") as handle:
for item in items:
handle.write(json.dumps(item, ensure_ascii=False) + "\n")
p.atomic_json(p.LABEL / f"{round_name}_manifest.json", batches)
prompt = """You are an expert in IoT and network-device vendor identification.
For every IP in the user message, identify the physical IoT device
manufacturer using the supplied device type and fingerprint evidence.
Prioritize direct hardware/software vendor fields, certificate identities,
HTTP titles/bodies/tags/favicons, operating-system evidence, and reverse DNS.
WHOIS and ASN are weak evidence and must not be treated as the device vendor
without supporting device evidence.
Return exactly one JSON object mapping every supplied IP to one canonical
manufacturer name. Use Unknown when direct evidence is insufficient. Do not
guess from country, ISP, open port, or device type. Output JSON only."""
(p.LABEL / "vendor_system_prompt.md").write_text(prompt, encoding="utf-8")
print(
f"[label-round] {round_name}: {len(items)} batches, "
f"{sum(len(value['ips']) for value in batches.values())} IPs"
)
def run_label_round(round_name: str, workers: int, model: str) -> None:
p.run_llm(
p.LABEL / f"{round_name}_input.jsonl",
p.LABEL / f"{round_name}_output.jsonl",
workers,
model,
)
def parse_label_round(round_name: str) -> None:
batches = json.loads(
(p.LABEL / f"{round_name}_manifest.json").read_text()
)
output = p.read_jsonl(p.LABEL / f"{round_name}_output.jsonl")
parsed = {}
errors = {}
for row in output:
item_id = p.clean(row.get("id"))
if row.get("error"):
errors[item_id] = row.get("error")
continue
mapping = p.normalize_llm_mapping(row.get("parsed"))
if not mapping and isinstance(row.get("response"), str):
try:
mapping = p.normalize_llm_mapping(json.loads(row["response"]))
except json.JSONDecodeError:
mapping = {}
parsed[item_id] = mapping
labels = candidate_labels()
missing = []
for item_id, batch in batches.items():
mapping = parsed.get(item_id, {})
for ip in batch["ips"]:
vendor = p.canonical_vendor(p.clean(mapping.get(ip)))
if not vendor:
missing.append({"batch": item_id, "ip": ip})
continue
labels[batch["device_type"]][ip] = vendor
for device_type in p.device_types():
rows = [
{"ip": ip, "vendor": vendor}
for ip, vendor in labels[device_type].items()
]
p.atomic_csv(
p.LABEL / f"candidate_label_{device_type}.csv",
rows,
["ip", "vendor"],
)
p.atomic_json(
p.LABEL / f"{round_name}_summary.json",
{
"label_source": "IoTProber",
"batches": len(batches),
"parsed_batches": len(parsed),
"errors": errors,
"missing": missing,
"candidate_label_counts": {
device_type: len(rows)
for device_type, rows in labels.items()
},
},
)
print(
f"[label-round] parsed={len(parsed)}/{len(batches)}, "
f"missing={len(missing)}, errors={len(errors)}"
)
def eligibility() -> dict[str, dict[str, int]]:
manifest = p.read_csv(p.DATA / "candidate_manifest.csv")
shodan = {
row["ip"]: row
for row in p.read_jsonl(p.DATA / "shodan_hosts.jsonl.gz")
}
labels = candidate_labels()
stats = {
device_type: {
"candidates": 0,
"shodan_ok": 0,
"labeled": 0,
"eligible": 0,
}
for device_type in p.device_types()
}
for row in manifest:
device_type = row["device_type"]
ip = row["ip"]
stats[device_type]["candidates"] += 1
if (shodan.get(ip) or {}).get("status") == "ok":
stats[device_type]["shodan_ok"] += 1
vendor = labels[device_type].get(ip, "")
if vendor:
stats[device_type]["labeled"] += 1
if p.is_known(vendor):
stats[device_type]["eligible"] += 1
return stats
def print_status() -> None:
stats = eligibility()
print("device_type,candidates,shodan_ok,labeled,eligible,deficit")
for device_type in p.device_types():
row = stats[device_type]
print(
f"{device_type},{row['candidates']},{row['shodan_ok']},"
f"{row['labeled']},{row['eligible']},"
f"{max(0, 200 - row['eligible'])}"
)
def select_validation() -> None:
stats = eligibility()
deficits = {
device_type: max(0, 200 - row["eligible"])
for device_type, row in stats.items()
if row["eligible"] < 200
}
if deficits:
raise RuntimeError(f"eligible samples are insufficient: {deficits}")
manifest = p.read_csv(p.DATA / "candidate_manifest.csv")
shodan = {
row["ip"]: row
for row in p.read_jsonl(p.DATA / "shodan_hosts.jsonl.gz")
}
labels = candidate_labels()
fingerprints = {
device_type: {
row["ip"]: row
for row in p.read_csv(
p.DATA / f"candidate_ipraw_{device_type}.csv"
)
}
for device_type in p.device_types()
}
selected_by_type: dict[str, list[dict[str, str]]] = defaultdict(list)
for row in manifest:
device_type = row["device_type"]
ip = row["ip"]
vendor = labels[device_type].get(ip, "")
if (shodan.get(ip) or {}).get("status") != "ok":
continue
if not p.is_known(vendor):
continue
if len(selected_by_type[device_type]) < 200:
selected_by_type[device_type].append(row)
selected_manifest = []
for device_type in p.device_types():
selected = selected_by_type[device_type]
selected_ips = [row["ip"] for row in selected]
selected_manifest.extend(selected)
p.atomic_csv(
p.DATA / f"ipraw_{device_type}.csv",
[fingerprints[device_type][ip] for ip in selected_ips],
p.CSV_FIELDS,
)
p.atomic_csv(
p.LABEL / f"label_{device_type}.csv",
[
{"ip": ip, "vendor": labels[device_type][ip]}
for ip in selected_ips
],
["ip", "vendor"],
)
p.atomic_csv(
p.DATA / "validation_manifest.csv",
selected_manifest,
["sample_id", "device_type", "ip", "query_rank", "collected_at"],
)
p.atomic_json(
p.DATA / "selection_metadata.json",
{
"selected_at": p.utc_now(),
"label_source": "IoTProber",
"selection_requirements": {
"per_device_type": 200,
"shodan_status": "ok",
"vendor_label": "non-Unknown",
},
"pool_stats": stats,
"selected_counts": {
device_type: len(rows)
for device_type, rows in selected_by_type.items()
},
},
)
print("[select] wrote 2,200 final validation samples")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
subs = parser.add_subparsers(dest="command", required=True)
expand = subs.add_parser("expand")
expand.add_argument("--target", type=int, required=True)
expand.add_argument("--devices", nargs="*")
subs.add_parser("snapshot")
subs.add_parser("collect-shodan")
prepare = subs.add_parser("prepare-label-round")
prepare.add_argument("--round", required=True)
prepare.add_argument("--batch-size", type=int, default=5)
run = subs.add_parser("run-label-round")
run.add_argument("--round", required=True)
run.add_argument("--workers", type=int, default=8)
run.add_argument("--model", required=True)
parse = subs.add_parser("parse-label-round")
parse.add_argument("--round", required=True)
subs.add_parser("status")
subs.add_parser("select")
return parser.parse_args()
def main() -> None:
args = parse_args()
if args.command == "expand":
expand_pool(args.target, args.devices)
elif args.command == "snapshot":
snapshot_pool()
elif args.command == "collect-shodan":
asyncio.run(collect_candidate_shodan())
elif args.command == "prepare-label-round":
prepare_label_round(args.round, args.batch_size)
elif args.command == "run-label-round":
run_label_round(args.round, args.workers, args.model)
elif args.command == "parse-label-round":
parse_label_round(args.round)
elif args.command == "status":
print_status()
elif args.command == "select":
select_validation()
if __name__ == "__main__":
main()
|