#!/usr/bin/env python3
"""Push Threat Brief BIOCs into your own Cortex XDR / XSIAM tenant.

Usage:
  export CORTEX_API_URL=https://api-<your-tenant>.xdr.<region>.paloaltonetworks.com
  export CORTEX_API_KEY_ID=<key id>
  export CORTEX_API_KEY=<standard API key>        # never put the key in a file or on the command line
  python3 push_bioc.py bioc-2026-11-12.json        # dry run: shows what would be sent
  python3 push_bioc.py bioc-2026-11-12.json --yes  # sends to POST /public_api/v1/bioc/insert

The file is a Threat Brief bioc.json (https://tlpclear.fr/detections). Every BIOC is forced to "disabled" before
sending: review and test each one in Detection Rules > BIOC before enabling it. Standard API keys only (not
Advanced). The key needs the BIOC rules RBAC permission. Python 3.8+, standard library only. DRL 1.1, no warranty.
"""
import json
import os
import sys
import urllib.error
import urllib.request


def main() -> int:
    args = [a for a in sys.argv[1:] if not a.startswith("--")]
    send = "--yes" in sys.argv
    if len(args) != 1:
        print(__doc__)
        return 2
    with open(args[0], encoding="utf-8") as f:
        body = json.load(f)
    items = body.get("request_data") if isinstance(body, dict) else None
    if not isinstance(items, list) or not items:
        print("No BIOC in this file (expected {\"request_data\": [...]}).")
        return 1
    for b in items:
        b["status"] = "disabled"
        b.pop("rule_id", None)  # new rules: never overwrite an existing BIOC of your tenant
        print(f"- {b.get('severity', '?'):<15} {b.get('type', '?'):<20} {b.get('name')}")
    if not send:
        print(f"\nDry run: {len(items)} BIOC, nothing sent. Add --yes to push them (disabled).")
        return 0
    url, kid, key = (os.environ.get(k, "").strip() for k in ("CORTEX_API_URL", "CORTEX_API_KEY_ID", "CORTEX_API_KEY"))
    if not (url and kid and key):
        print("Set CORTEX_API_URL, CORTEX_API_KEY_ID and CORTEX_API_KEY in your environment.")
        return 2
    if not url.startswith("https://"):
        print("CORTEX_API_URL must start with https://")
        return 2
    req = urllib.request.Request(url.rstrip("/") + "/public_api/v1/bioc/insert",
                                 data=json.dumps({"request_data": items}).encode(), method="POST",
                                 headers={"Authorization": key, "x-xdr-auth-id": kid,
                                          "Content-Type": "application/json", "Accept": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=60) as r:
            reply = json.loads(r.read() or b"{}")
    except urllib.error.HTTPError as e:
        print(f"HTTP {e.code}: {e.read()[:500].decode(errors='replace')}")
        return 1
    reply = reply.get("reply", reply)
    print(f"\nadded: {len(reply.get('added_objects') or [])}, updated: {len(reply.get('updated_objects') or [])}")
    for err in reply.get("errors") or []:
        print("error:", err)
    return 1 if reply.get("errors") else 0


if __name__ == "__main__":
    sys.exit(main())
