﻿#!/usr/bin/env python3
"""QuantSec Advisory (v51.2) — 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 (SHA-256 digests, file sizes, ELF header
machine/section byte counts, dynamic library names, and public OID/PQC constants).
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_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",
    "SHA256_K0": b"\x42\x8a\x2f\x98",
    "AES_SBOX_HEAD": b"\x63\x7c\x77\x7b\xf2\x6b\x6f\xc5",
    "ML_KEM_STR": b"ML-KEM",
    "ML_DSA_STR": b"ML-DSA",
    "SROS2_ENCLAVE": b"enclaves",
    "MAVLINK_V2_MAGIC": b"\xfd",
}

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


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 == 1:
        e_machine = struct.unpack_from(endian + "H", blob, 18)[0]
    elif ei_class == 2:
        e_machine = struct.unpack_from(endian + "H", blob, 18)[0]
    else:
        return None
    return {
        "elf_bits": 32 if ei_class == 1 else 64,
        "endianness": "LE" if endian == "<" else "BE",
        "e_machine_id": e_machine,
    }


def inspect_file_zero_ip(fpath: Path) -> Dict[str, Any]:
    h = hashlib.sha256()
    size = fpath.stat().st_size
    # Read bounded 8 MB window for non-IP structural markers while hashing full file
    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]
    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),
        "linked_shared_libs": sonames,
        "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()
    return {
        "schema": "quantsec.airgap.fingerprint.v1",
        "collector_version": "51.2",
        "zero_raw_ip_transmitted": True,
        "generated_utc": datetime.now(timezone.utc).isoformat(),
        "artifact_count": len(artifacts),
        "bundle_manifest_sha256": manifest_sha256,
        "artifacts": artifacts,
    }


def main() -> int:
    ap = argparse.ArgumentParser(description="QuantSec Zero-IP Air-Gapped Metadata Collector")
    ap.add_argument("target", help="Firmware image, container rootfs directory, or 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 ({manifest['artifact_count']} file(s)) -> {out} [SHA256:{manifest['bundle_manifest_sha256'][:12]}]")
    return 0


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