OpenSTANAG Authors
Claude Fable 5.2
fix(security): fail-closed guard, signer trust, payload binding and strict XMLDSIG verification
985d734 unverified Download open_stanag/cli.py from abr00kx/open-stanag: direct link, hf CLI and curl.
- Browser
- Download file 16.1 kB
-
https://huggingface.co/abr00kx/open-stanag/resolve/main/open_stanag/cli.py
- Command line
-
hf download hf://abr00kx/open-stanag/open_stanag/cli.py
-
curl -L -o cli.py https://huggingface.co/abr00kx/open-stanag/resolve/main/open_stanag/cli.py
16.1 kB
| """ | |
| Command-Line Interface (CLI) for OpenSTANAG NATO Security Labeling, Binding & Guard. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import sys | |
| import json | |
| from pathlib import Path | |
| # Ensure package directory is in sys.path when invoked directly | |
| pkg_root = str(Path(__file__).resolve().parent.parent) | |
| if pkg_root not in sys.path: | |
| sys.path.insert(0, pkg_root) | |
| from open_stanag.label import Stanag4774Label, OriginatorID | |
| from open_stanag.binding import Stanag4778Binding | |
| from open_stanag.sidecar import create_sidecar, verify_sidecar | |
| from open_stanag.crypto.certs import ( | |
| generate_rsa_key_and_cert, | |
| cert_to_pem, | |
| cert_from_pem, | |
| private_key_to_pem, | |
| private_key_from_pem, | |
| ) | |
| from open_stanag.crypto.trust import TrustStore | |
| from open_stanag.policy.pdp import StanagABACPDP | |
| from open_stanag.crypto.signer import XMLDSigSigner | |
| from open_stanag.crypto.verifier import XMLDSigVerifier | |
| from open_stanag.policy.models import SubjectAttributes, ActionContext, GuardDecision | |
| from open_stanag.policy.guard import CrossDomainGuard | |
| from open_stanag.schema_validator import validate_stanag_4774, validate_stanag_4778 | |
| def _add_signing_args(p): | |
| p.add_argument("--key", help="PEM private key to sign with (requires --cert)") | |
| p.add_argument("--cert", help="PEM certificate of the signer (requires --key)") | |
| def _add_trust_args(p): | |
| p.add_argument( | |
| "--trust-anchor", action="append", default=[], metavar="PEM", | |
| help="PEM file of a trusted signer or CA certificate (repeatable). " | |
| "Without one, signatures are checked for integrity only.", | |
| ) | |
| def _make_signer(args) -> XMLDSigSigner: | |
| if bool(args.key) != bool(args.cert): | |
| sys.exit("error: --key and --cert must be given together") | |
| if args.key: | |
| key = private_key_from_pem(Path(args.key).read_text(encoding="utf-8")) | |
| cert = cert_from_pem(Path(args.cert).read_text(encoding="utf-8")) | |
| return XMLDSigSigner(private_key=key, certificate=cert) | |
| print( | |
| "[WARNING] Signing with a throwaway self-signed key: no verifier can trust this " | |
| "signature. Use --key/--cert for a real signer.", | |
| file=sys.stderr, | |
| ) | |
| priv_key, cert = generate_rsa_key_and_cert() | |
| return XMLDSigSigner(private_key=priv_key, certificate=cert) | |
| def _make_verifier(args) -> XMLDSigVerifier: | |
| store = TrustStore.from_pem_files(args.trust_anchor) if args.trust_anchor else None | |
| return XMLDSigVerifier(trust_store=store) | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| prog="open-stanag", | |
| description="NATO STANAG 4774/4778 Cryptographic Labeling, Binding & Cross-Domain Guard CLI", | |
| ) | |
| subparsers = parser.add_subparsers(dest="command", help="Sub-commands") | |
| # 1. label | |
| label_parser = subparsers.add_parser("label", help="Manage STANAG 4774 confidentiality labels") | |
| label_subs = label_parser.add_subparsers(dest="label_cmd") | |
| l_create = label_subs.add_parser("create", help="Create a STANAG 4774 label XML") | |
| l_create.add_argument("--policy", default="NATO", help="Policy Identifier (e.g. NATO)") | |
| l_create.add_argument("--classification", required=True, help="Classification (e.g. UNCLASSIFIED, SECRET)") | |
| l_create.add_argument("--releasable-to", default="", help="Comma-separated release targets (e.g. NATO,USA,GBR)") | |
| l_create.add_argument("--handling-caveat", default="", help="Restrictive caveat (e.g. NOFORN)") | |
| l_create.add_argument("--privacy-mark", default="", help="Privacy mark (e.g. EYES ONLY, COI:CYBER)") | |
| l_create.add_argument("--originator-email", default="", help="Originator email for OriginatorID") | |
| l_create.add_argument("-o", "--output", help="Output file path (prints to stdout if omitted)") | |
| l_val = label_subs.add_parser("validate", help="Validate a STANAG 4774 XML file") | |
| l_val.add_argument("file", help="Path to label XML file") | |
| # 2. bind | |
| bind_parser = subparsers.add_parser("bind", help="Manage STANAG 4778 Binding Information") | |
| bind_subs = bind_parser.add_subparsers(dest="bind_cmd") | |
| b_create = bind_subs.add_parser("create", help="Create a STANAG 4778 BDO") | |
| b_create.add_argument("--label", required=True, help="Path to STANAG 4774 label XML file") | |
| b_create.add_argument("--data-uri", required=True, help="URI or path to target data object") | |
| b_create.add_argument("--sign", action="store_true", help="Cryptographically sign the BDO with XML-DSig") | |
| b_create.add_argument("-o", "--output", required=True, help="Output BDO file path") | |
| _add_signing_args(b_create) | |
| b_verify = bind_subs.add_parser("verify", help="Verify a STANAG 4778 BDO") | |
| b_verify.add_argument("file", help="Path to BDO XML file") | |
| _add_trust_args(b_verify) | |
| # 3. sidecar | |
| sidecar_parser = subparsers.add_parser("sidecar", help="Manage .bdo sidecar files for arbitrary data objects") | |
| sidecar_subs = sidecar_parser.add_subparsers(dest="sidecar_cmd") | |
| s_create = sidecar_subs.add_parser("create", help="Create a sidecar .bdo file for a target data object") | |
| s_create.add_argument("target", help="Path to target file (e.g. mission.pdf)") | |
| s_create.add_argument("--policy", default="NATO", help="Policy Identifier") | |
| s_create.add_argument("--classification", required=True, help="Classification") | |
| s_create.add_argument("--releasable-to", default="NATO,USA,GBR", help="Comma-separated release targets") | |
| s_create.add_argument("--handling-caveat", default="", help="Restrictive handling caveat") | |
| s_create.add_argument("--sign", action="store_true", help="Sign the sidecar file") | |
| s_create.add_argument("-o", "--output", help="Output .bdo path (defaults to <target>.bdo)") | |
| _add_signing_args(s_create) | |
| s_verify = sidecar_subs.add_parser("verify", help="Verify a sidecar .bdo file against its data object") | |
| s_verify.add_argument("bdo_file", help="Path to .bdo sidecar file") | |
| _add_trust_args(s_verify) | |
| # 4. guard | |
| guard_parser = subparsers.add_parser("guard", help="Cross-Domain Security Guard inspection") | |
| guard_subs = guard_parser.add_subparsers(dest="guard_cmd") | |
| g_inspect = guard_subs.add_parser("inspect", help="Inspect and evaluate a BDO against Subject attributes") | |
| g_inspect.add_argument("bdo", help="Path to BDO or sidecar file") | |
| g_inspect.add_argument("--subject-id", default="analyst@soc.nato.int", help="Subject identity") | |
| g_inspect.add_argument("--clearance", required=True, help="Subject clearance level") | |
| g_inspect.add_argument("--citizenship", required=True, help="Subject citizenship (e.g. USA, GBR, FRA)") | |
| g_inspect.add_argument("--affiliations", default="NATO", help="Comma-separated coalition affiliations") | |
| g_inspect.add_argument("--cois", default="", help="Comma-separated Communities of Interest") | |
| g_inspect.add_argument("--aal", type=int, default=2, help="Authenticator Assurance Level (1-3)") | |
| g_inspect.add_argument("--local-nation", help="Nation operating the guard, ISO alpha-3 (used for NOFORN)") | |
| g_inspect.add_argument( | |
| "--require-signature", action="store_true", | |
| help="Quarantine objects without a trusted signature (implied by --trust-anchor)", | |
| ) | |
| _add_trust_args(g_inspect) | |
| # 5. keygen | |
| keygen_parser = subparsers.add_parser("keygen", help="Generate RSA/EC test keys and X.509 certificates") | |
| keygen_parser.add_argument("--type", choices=["rsa", "ec"], default="rsa", help="Key type") | |
| keygen_parser.add_argument("--cn", default="guard.nato.int", help="Certificate Common Name") | |
| keygen_parser.add_argument("--out-key", default="private_key.pem", help="Output private key path") | |
| keygen_parser.add_argument("--out-cert", default="certificate.pem", help="Output certificate path") | |
| # 6. server | |
| server_parser = subparsers.add_parser("server", help="Run the FastAPI REST Guard Server") | |
| server_parser.add_argument("--host", default="127.0.0.1", help="Host address") | |
| server_parser.add_argument("--port", type=int, default=8000, help="Port number") | |
| args = parser.parse_args() | |
| if not args.command: | |
| parser.print_help() | |
| sys.exit(1) | |
| if args.command == "label": | |
| if args.label_cmd == "create": | |
| label = Stanag4774Label(policy_identifier=args.policy, classification=args.classification) | |
| if args.releasable_to: | |
| label.add_releasable_to([x.strip() for x in args.releasable_to.split(",") if x.strip()]) | |
| if args.handling_caveat: | |
| label.add_handling_caveat(args.handling_caveat) | |
| if args.privacy_mark: | |
| label.privacy_mark = args.privacy_mark | |
| if args.originator_email: | |
| label.originator_id = OriginatorID("rfc822Name", args.originator_email) | |
| xml_str = label.to_xml(validate=True, pretty_print=True) | |
| if args.output: | |
| with open(args.output, "w", encoding="utf-8") as f: | |
| f.write(xml_str) | |
| print(f"Created valid STANAG 4774 label: {args.output}") | |
| else: | |
| print(xml_str) | |
| elif args.label_cmd == "validate": | |
| with open(args.file, "rb") as f: | |
| content = f.read() | |
| valid, errors = validate_stanag_4774(content) | |
| if valid: | |
| print(f"[SUCCESS] {args.file} validated 100% against NATO STANAG 4774 schema.") | |
| else: | |
| print(f"[FAILED] Validation errors for {args.file}:") | |
| for e in errors: | |
| print(f" - {e}") | |
| sys.exit(1) | |
| elif args.command == "bind": | |
| if args.bind_cmd == "create": | |
| label = Stanag4774Label.from_xml(Path(args.label).read_text(encoding="utf-8")) | |
| bdo = Stanag4778Binding.create_simple(label=label, data_uri=args.data_uri, binding_id="mb-1") | |
| if args.sign: | |
| bdo.sign(signer=_make_signer(args), target_binding_id="mb-1") | |
| xml_str = bdo.to_xml(validate=True, pretty_print=False) | |
| with open(args.output, "w", encoding="utf-8") as f: | |
| f.write(xml_str) | |
| print(f"Created valid STANAG 4778 BDO: {args.output} (Signed: {args.sign})") | |
| elif args.bind_cmd == "verify": | |
| with open(args.file, "rb") as f: | |
| content = f.read() | |
| schema_valid, schema_errors = validate_stanag_4778(content) | |
| if not schema_valid: | |
| print(f"[FAILED] Schema validation failed: {schema_errors}") | |
| sys.exit(1) | |
| bdo = Stanag4778Binding.from_xml(content, validate=False) | |
| sig_results = bdo.verify_signatures(verifier=_make_verifier(args)) | |
| print(f"[SUCCESS] Schema validated 100% against NATO STANAG 4778.") | |
| print(f"Found {len(sig_results)} cryptographic signature(s):") | |
| if not sig_results: | |
| print("[WARNING] BDO is unsigned: the binding is NOT cryptographically verified.") | |
| all_crypto_ok = True | |
| for i, res in enumerate(sig_results): | |
| status_str = "VALID" if res.is_valid else "INVALID" | |
| print(f" Signature #{i+1}: {status_str}") | |
| if res.signer_dn: | |
| print(f" Signer DN: {res.signer_dn}") | |
| print(f" Signer trusted: {res.signer_trusted}") | |
| for terr in ([] if res.signer_trusted else res.trust_errors): | |
| print(f" Note: {terr}") | |
| if res.timestamp: | |
| print(f" Timestamp: {res.timestamp.isoformat()}") | |
| if not res.is_valid: | |
| all_crypto_ok = False | |
| for err in res.errors: | |
| print(f" Error: {err}") | |
| if not all_crypto_ok: | |
| sys.exit(1) | |
| elif args.command == "sidecar": | |
| if args.sidecar_cmd == "create": | |
| label = Stanag4774Label(policy_identifier=args.policy, classification=args.classification) | |
| if args.releasable_to: | |
| label.add_releasable_to([x.strip() for x in args.releasable_to.split(",") if x.strip()]) | |
| if args.handling_caveat: | |
| label.add_handling_caveat(args.handling_caveat) | |
| signer = None | |
| if args.sign: | |
| signer = _make_signer(args) | |
| out_path = create_sidecar( | |
| target_file_path=args.target, | |
| label=label, | |
| signer=signer, | |
| output_bdo_path=args.output, | |
| ) | |
| print(f"Created sidecar BDO: {out_path} (Signed: {args.sign})") | |
| elif args.sidecar_cmd == "verify": | |
| res = verify_sidecar(args.bdo_file, verifier=_make_verifier(args)) | |
| print(f"Sidecar Verification: {'[VALID]' if res.is_valid else '[INVALID]'}") | |
| print(f" Target File: {res.target_file_path} (Exists: {res.target_file_exists})") | |
| print(f" Schema Valid: {res.schema_valid}") | |
| print(f" Signatures: {res.signature_count}") | |
| print(f" Cryptographic Valid: {res.crypto_valid}") | |
| print(f" Signer Trusted: {res.signer_trusted}") | |
| payload_state = {True: "matches signed digest", False: "MISMATCH", None: "not covered by a signature"} | |
| print(f" Payload Content: {payload_state[res.payload_hash_valid]}") | |
| if res.errors: | |
| print(" Errors:") | |
| for err in res.errors: | |
| print(f" - {err}") | |
| sys.exit(1) | |
| elif args.command == "guard": | |
| if args.guard_cmd == "inspect": | |
| subject = SubjectAttributes( | |
| subject_id=args.subject_id, | |
| clearance=args.clearance, | |
| citizenship=args.citizenship, | |
| coalition_affiliations={x.strip() for x in args.affiliations.split(",") if x.strip()}, | |
| cois={x.strip() for x in args.cois.split(",") if x.strip()}, | |
| aal=args.aal, | |
| ) | |
| store = TrustStore.from_pem_files(args.trust_anchor) if args.trust_anchor else None | |
| guard = CrossDomainGuard( | |
| pdp=StanagABACPDP(local_nation=args.local_nation), | |
| trust_store=store, | |
| require_signature=args.require_signature or store is not None, | |
| ) | |
| if not guard.require_signature: | |
| print( | |
| "[WARNING] No --trust-anchor given: signatures are not required and the " | |
| "label's origin is not authenticated.", | |
| file=sys.stderr, | |
| ) | |
| report = guard.inspect_and_filter(bdo_xml_or_path=Path(args.bdo), subject=subject) | |
| print(f"=== CROSS-DOMAIN GUARD DECISION: [{report.decision.value}] ===") | |
| print(f" Authorized: {report.authorized}") | |
| print(f" Pipeline Stage: {report.pipeline_stage_reached}") | |
| print(f" Audit ID: {report.audit_id}") | |
| print(" Reasons:") | |
| for r in report.reasons: | |
| print(f" * {r}") | |
| print(" Obligations:") | |
| for o in report.obligations: | |
| print(f" + {o}") | |
| if report.decision != GuardDecision.PERMIT: | |
| sys.exit(1) | |
| elif args.command == "keygen": | |
| if args.type == "rsa": | |
| priv, cert = generate_rsa_key_and_cert(common_name=args.cn) | |
| else: | |
| from open_stanag.crypto.certs import generate_ec_key_and_cert | |
| priv, cert = generate_ec_key_and_cert(common_name=args.cn) | |
| Path(args.out_key).write_text(private_key_to_pem(priv), encoding="utf-8") | |
| Path(args.out_cert).write_text(cert_to_pem(cert), encoding="utf-8") | |
| print(f"Generated {args.type.upper()} Key: {args.out_key}") | |
| print(f"Generated Certificate: {args.out_cert}") | |
| elif args.command == "server": | |
| import uvicorn | |
| from open_stanag.server.app import app | |
| print(f"Starting OpenSTANAG Guard API Server on {args.host}:{args.port}...") | |
| uvicorn.run(app, host=args.host, port=args.port) | |
| if __name__ == "__main__": | |
| main() | |