#!/usr/bin/env python3
"""
verify_license.py - parse and cryptographically verify a Dell iDRAC7/iDRAC8
license XML (XML-DSIG, RSA-SHA1, exclusive C14N).

Checks:
  1. The <dsig:Signature> over <dsig:SignedInfo>.
  2. The reference digest over the document (enveloped-signature transform).
  3. Extracts the service-tag restriction, term, and enabled features.

Usage:
    python verify_license.py <license.xml> [...]
"""
import base64
import hashlib
import sys

from lxml import etree
from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.exceptions import InvalidSignature

DS = "http://www.w3.org/2000/09/xmldsig#"
LNS = "http://www.dell.com/2011/12G/licensing"
NS = {"ds": DS, "lns": LNS}

EXC_C14N = "http://www.w3.org/2001/10/xml-exc-c14n#"
ENVELOPED = "http://www.w3.org/2000/09/xmldsig#enveloped-signature"


def c14n(node, exclusive=True):
    return etree.tostring(node, method="c14n", exclusive=exclusive, with_comments=False)


def verify(path, host_tag=None):
    tree = etree.parse(path)
    root = tree.getroot()

    sig = root.find("ds:Signature", NS)
    if sig is None:
        raise SystemExit(f"{path}: no ds:Signature element")

    signed_info = sig.find("ds:SignedInfo", NS)
    sig_value = base64.b64decode(
        "".join(sig.find("ds:SignatureValue", NS).text.split())
    )
    cert_b64 = "".join(
        sig.find("ds:KeyInfo/ds:X509Data/ds:X509Certificate", NS).text.split()
    )
    cert = x509.load_der_x509_certificate(base64.b64decode(cert_b64))

    # --- 1. signature over SignedInfo -------------------------------------
    sig_ok = True
    try:
        cert.public_key().verify(
            sig_value, c14n(signed_info), padding.PKCS1v15(), hashes.SHA1()
        )
    except InvalidSignature:
        sig_ok = False

    # --- 2. reference digest (enveloped transform) ------------------------
    ref = signed_info.find("ds:Reference", NS)
    digest_expected = base64.b64decode(ref.find("ds:DigestValue", NS).text.strip())

    doc = etree.fromstring(etree.tostring(root))
    doc_sig = doc.find("ds:Signature", NS)
    # Enveloped-signature transform: drop the Signature element but keep its
    # tail text (whitespace) so the remaining node-set matches the signer's.
    prev = doc_sig.getprevious()
    if prev is not None:
        prev.tail = (prev.tail or "") + (doc_sig.tail or "")
    doc_sig.getparent().remove(doc_sig)
    digest_actual = hashlib.sha1(c14n(doc, exclusive=False)).digest()
    digest_ok = digest_expected == digest_actual

    # --- 3. metadata ------------------------------------------------------
    def text(xpath):
        el = root.find(xpath, NS)
        return el.text.strip() if el is not None and el.text else None

    tag = text("lns:LicenseData/lns:Restrictions/lns:ServiceTag")
    term = root.find("lns:LicenseData/lns:LicenseTerm/*", NS)
    sold = text("lns:LicenseData/lns:UTCdateSold")
    features = [
        (f.get(f"{{{LNS}}}ID"), f.get(f"{{{LNS}}}Description"))
        for f in root.findall("lns:LicenseData/lns:Feature", NS)
        if f.get(f"{{{LNS}}}Enabled") == "true"
    ]

    print(f"\n=== {path} ===")
    print(f"  product      : {text('lns:LicenseData/lns:ProductDescription/lns:lang_en')}")
    print(f"  entitlement  : {text('lns:LicenseData/lns:EntitlementID')}")
    print(f"  sold (UTC)   : {sold}")
    if term is not None:
        kind = etree.QName(term).localname
        if kind == "Evaluation":
            days = term.get(f"{{{LNS}}}Duration", "")
            n = int(days.lstrip("P").rstrip("D")) if days.startswith("P") else 0
            print(f"  term         : evaluation, {n} days from first activation")
        else:
            print(f"  term         : {kind}")
    print(f"  service tag  : {tag if tag else '(none - not tag-bound)'}")
    print(f"  features     : {', '.join(f'{i}:{d}' for i, d in features)}")
    print(f"  signature    : {'VALID' if sig_ok else 'INVALID'}")
    print(f"  digest       : {'VALID' if digest_ok else 'INVALID'}")

    if host_tag:
        if tag is None:
            print(f"  tag check    : license is not bound, will import on any iDRAC")
        elif tag.upper() == host_tag.upper():
            print(f"  tag check    : MATCH ({host_tag})")
        else:
            print(f"  tag check    : MISMATCH (license={tag}, host={host_tag})")
            print(f"                 -> set host service tag to {tag} or use an unbound license")

    return sig_ok and digest_ok


if __name__ == "__main__":
    import argparse

    ap = argparse.ArgumentParser(description="Verify Dell iDRAC7/iDRAC8 license XML")
    ap.add_argument("licenses", nargs="+", help="license XML file(s)")
    ap.add_argument("--tag", help="host service tag to compare against the license binding")
    args = ap.parse_args()

    ok = all(verify(p, args.tag) for p in args.licenses)
    print(f"\nRESULT: {'PASS - signature and reference digest are valid' if ok else 'FAIL'}")
    sys.exit(0 if ok else 1)
