#!/usr/bin/env python3
"""QuantSec Advisory (v55.0) — Air-Gapped Zero-Binary-Custody Metadata Collector.

Runs 100% offline on Customer/Defense/M&A workstations using Python 3 stdlib only.
Extracts ONLY non-IP structural metadata across:
  - ELF 32/64 (machine, endianness, PIE/ET_DYN vs ET_EXEC)
  - Windows PE/COFF (.exe/.dll/.sys machine + ASLR/DEP/CFG DllCharacteristics)
  - Apple Mach-O / Universal Fat headers
  - MCUboot / U-Boot embedded bootloader image headers
  - AI Model Safe-Metadata (.safetensors tensor count & dtypes; ONNX magic — ZERO weights read)
  - Classical & NIST FIPS 203/204/205 Post-Quantum Cryptography (ML-KEM, ML-DSA, SLH-DSA) OIDs

ZERO raw firmware instructions, proprietary source code, or AI tensor weights are exported.

Usage:
 python qsa_collect_fingerprint.py <target_dir_or_firmware_file> -o qsa_airgap_fingerprint.json
"""
from __future__ import annotations

import argparse
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import re
import struct
from typing import Any, Dict, List

PUBLIC_CRYPTO_MARKERS = {
 "RSA_PKCS1_OID": b"\x2a\x86\x48\x86\xf7\x0d\x01\x01",
 "ECDSA_P256_OID": b"\x2a\x86\x48\xce\x3d\x03\x01\x07",
 "ED25519_OID": b"\x2b\x65\x70",
 "NIST_PQC_HASH_SIG_ARC_OID": b"\x60\x86\x48\x01\x65\x03\x04\x03",
 "NIST_PQC_KEM_ARC_OID": b"\x60\x86\x48\x01\x65\x03\x04\x04",
 "SHA256_K0": b"\x42\x8a\x2f\x98",
 "AES_SBOX_HEAD": b"\x63\x7c\x77\x7b\xf2\x6b\x6f\xc5",
 "ML_KEM_FIPS203": b"ML-KEM",
 "ML_DSA_FIPS204": b"ML-DSA",
 "SLH_DSA_FIPS205": b"SLH-DSA",
 "KYBER_HYBRID": b"Kyber",
 "DILITHIUM_HYBRID": b"Dilithium",
 "SROS2_ENCLAVE": b"enclaves",
 "MAVLINK_V2_MAGIC": b"\xfd",
}

NDAA_889_STRINGS = (
 "hisilicon", "hi3516", "hi3519", "hi3559", "hikvision", "dahua",
 "quectel", "fibocom", "hytera", "zte", "huawei", "dji_sdk"
)
SONAME_RE = re.compile(rb"lib[a-zA-Z0-9_+.-]+\.so(?:\.[0-9]+)*")
DLL_RE = re.compile(rb"[a-zA-Z0-9_.-]+\.dll", re.IGNORECASE)


def parse_elf_sizes_only(blob: bytes) -> Dict[str, Any] | None:
 if len(blob) < 64 or blob[:4] != b"\x7fELF":
 return None
 ei_class = blob[4]
 endian = "<" if blob[5] == 1 else ">"
 if ei_class not in (1, 2):
 return None
 e_type, e_machine = struct.unpack_from(endian + "HH", blob, 16)
 return {
 "elf_bits": 32 if ei_class == 1 else 64,
 "endianness": "LE" if endian == "<" else "BE",
 "e_type": "ET_DYN_PIE_OR_SO" if e_type == 3 else ("ET_EXEC_NO_PIE" if e_type == 2 else e_type),
 "e_machine_id": e_machine,
 }


def parse_pe_headers_only(blob: bytes) -> Dict[str, Any] | None:
 if len(blob) < 128 or blob[:2] != b"MZ":
 return None
 pe_off = struct.unpack_from("<I", blob, 0x3C)[0]
 if pe_off + 96 > len(blob) or blob[pe_off:pe_off + 4] != b"PE\x00\x00":
 return None
 machine, num_sections = struct.unpack_from("<HH", blob, pe_off + 4)
 opt_magic = struct.unpack_from("<H", blob, pe_off + 24)[0]
 dll_chars = struct.unpack_from("<H", blob, pe_off + 24 + 70)[0] if pe_off + 96 <= len(blob) else 0
 return {
 "pe_format": "PE32+" if opt_magic == 0x20B else "PE32",
 "machine_hex": hex(machine),
 "section_count": num_sections,
 "aslr_dynamic_base": bool(dll_chars & 0x0040),
 "dep_nx_compat": bool(dll_chars & 0x0100),
 "control_flow_guard": bool(dll_chars & 0x4000),
 }


def parse_firmware_or_ai_header(fpath: Path, blob: bytes) -> Dict[str, Any] | None:
 ext = fpath.suffix.lower()
 if len(blob) >= 16 and blob[:4] in (b"\xfe\xed\xfa\xce", b"\xce\xfa\xed\xfe", b"\xfe\xed\xfa\xcf", b"\xcf\xfa\xed\xfe", b"\xca\xfe\xba\xbe"):
 return {"container": "APPLE_MACHO_OR_FAT", "magic_hex": blob[:4].hex()}
 if len(blob) >= 32 and blob[:4] == b"\x3d\xb8\xf3\x96":
 hdr_sz, img_sz = struct.unpack_from("<HI", blob, 8)
 return {"container": "MCUBOOT_V1_V2_IMAGE", "header_bytes": hdr_sz, "payload_bytes": img_sz}
 if len(blob) >= 64 and blob[:4] == b"\x27\x05\x19\x56":
 return {"container": "UBOOT_LEGACY_UIMAGE"}
 if ext == ".safetensors" and len(blob) >= 16:
 hdr_len = struct.unpack_from("<Q", blob, 0)[0]
 if 2 <= hdr_len <= min(len(blob) - 8, 2 * 1024 * 1024):
 try:
 meta = json.loads(blob[8:8 + hdr_len].decode("utf-8"))
 tensors = [k for k in meta.keys() if k != "__metadata__"]
 dtypes = sorted({str(meta[t].get("dtype")) for t in tensors if isinstance(meta.get(t), dict)})
 return {"container": "SAFETENSORS_AI_MODEL", "tensor_count": len(tensors), "dtypes": dtypes, "weights_exported": False}
 except Exception:
 return {"container": "SAFETENSORS_UNPARSED"}
 if ext == ".onnx":
 return {"container": "ONNX_AI_GRAPH", "weights_exported": False}
 return None


def inspect_file_zero_ip(fpath: Path) -> Dict[str, Any]:
 h = hashlib.sha256()
 size = fpath.stat().st_size
 sample = bytearray()
 with fpath.open("rb") as fp:
 while True:
 chunk = fp.read(65536)
 if not chunk:
 break
 h.update(chunk)
 if len(sample) < 8 * 1024 * 1024:
 sample.extend(chunk[: (8 * 1024 * 1024) - len(sample)])

 raw = bytes(sample)
 low = raw.lower()
 sonames = sorted({m.decode("ascii", errors="ignore") for m in SONAME_RE.findall(raw)})[:60]
 dlls = sorted({m.decode("ascii", errors="ignore").lower() for m in DLL_RE.findall(raw)})[:40]
 markers = [k for k, pat in PUBLIC_CRYPTO_MARKERS.items() if pat in raw]
 ndaa_hits = [tok for tok in NDAA_889_STRINGS if tok.encode("ascii") in low]

 return {
 "relative_name": fpath.name,
 "byte_size": size,
 "sha256": h.hexdigest(),
 "elf_header": parse_elf_sizes_only(raw),
 "pe_header": parse_pe_headers_only(raw),
 "firmware_or_ai_header": parse_firmware_or_ai_header(fpath, raw),
 "linked_shared_libs": sonames,
 "linked_pe_dlls": dlls,
 "detected_public_crypto_markers": markers,
 "ndaa_889_vendor_tokens": ndaa_hits,
 }


def collect_fingerprint(target: Path) -> Dict[str, Any]:
 files = [target] if target.is_file() else [p for p in sorted(target.rglob("*")) if p.is_file()][:250]
 artifacts: List[Dict[str, Any]] = [inspect_file_zero_ip(p) for p in files]
 bundle_seed = "|".join(f"{a['relative_name']}:{a['sha256']}" for a in artifacts)
 manifest_sha256 = hashlib.sha256(bundle_seed.encode("utf-8")).hexdigest()
 pqc_ready = any(
 any(m in a["detected_public_crypto_markers"] for m in ("ML_KEM_FIPS203", "ML_DSA_FIPS204", "SLH_DSA_FIPS205", "NIST_PQC_KEM_ARC_OID", "NIST_PQC_HASH_SIG_ARC_OID"))
 for a in artifacts
 )
 return {
 "schema": "quantsec.airgap.fingerprint.v2",
 "collector_version": "55.0",
 "zero_raw_ip_transmitted": True,
 "pqc_2030_markers_present": pqc_ready,
 "generated_utc": datetime.now(timezone.utc).isoformat(),
 "artifact_count": len(artifacts),
 "bundle_manifest_sha256": manifest_sha256,
 "recommended_order_url": f"https://vault.quantseccloud.com/order?sha256={manifest_sha256}",
 "artifacts": artifacts,
 }


def main() -> int:
 ap = argparse.ArgumentParser(description="QuantSec Zero-IP Air-Gapped Metadata Collector v55.0")
 ap.add_argument("target", help="Firmware image, container rootfs directory, PE/ELF binary, or AI model file")
 ap.add_argument("-o", "--output", default="qsa_airgap_fingerprint.json", help="Output JSON manifest path")
 args = ap.parse_args()
 manifest = collect_fingerprint(Path(args.target))
 out = Path(args.output)
 out.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
 print(f"[OK] Zero-IP Fingerprint Manifest v55.0 ({manifest['artifact_count']} file(s)) -> {out} [SHA256:{manifest['bundle_manifest_sha256'][:12]}]")
 return 0


if __name__ == "__main__":
 raise SystemExit(main())