Download CVE/resample.py from IoTProber/raw_dataset: direct link, hf CLI and curl.
- Browser
- Download file 21.8 kB
-
https://huggingface.co/datasets/IoTProber/raw_dataset/resolve/main/CVE/resample.py
- Command line
-
hf download hf://datasets/IoTProber/raw_dataset/CVE/resample.py
-
curl -L -o resample.py https://huggingface.co/datasets/IoTProber/raw_dataset/resolve/main/CVE/resample.py
21.8 kB
| #!/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() | |