#!/usr/bin/env python3
"""
forge_license.py - build an iDRAC7/8 license XML signed by a *self-signed*
certificate instead of Dell's signing certificate.

This tests the hypothesis that liblmpop.so loads the Dell CA into the xmlsec
keys manager but never sets XMLSEC_KEYINFO_FLAGS_X509DATA_STOP_ON_INVALID_CERT
(0x800).  With xmlsec 1.2.18, keyInfoCtx.flags defaults to 0, so a failed
chain verification is non-fatal and the signature is still checked with the
public key from the attacker-supplied certificate.

Usage:
    python forge_license.py --tag 9QYZF42 --out forged.xml
    python forge_license.py --tag 9QYZF42 --out forged_dellcn.xml --dell-subject
"""
import argparse
import base64
from datetime import datetime, timedelta, timezone

from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.x509.oid import NameOID
from lxml import etree
from signxml import XMLSigner, methods

LNS = "http://www.dell.com/2011/12G/licensing"
DS = "http://www.w3.org/2000/09/xmldsig#"


def make_cert(dell_subject: bool):
    key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
    if dell_subject:
        subject = x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, "Signing Certificate"),
            x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, "Embedded License Manager"),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Dell, Inc."),
        ])
        issuer = x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, "CA Certificate"),
            x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, "Embedded License Manager"),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Dell, Inc."),
        ])
        serial = 1
    else:
        subject = x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, "iDRAC License Signer"),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Local Lab"),
        ])
        issuer = subject
        serial = x509.random_serial_number()

    now = datetime(2010, 1, 1, tzinfo=timezone.utc)
    cert = (
        x509.CertificateBuilder()
        .subject_name(subject)
        .issuer_name(issuer)
        .public_key(key.public_key())
        .serial_number(serial)
        .not_valid_before(now)
        .not_valid_after(datetime(2035, 12, 31, tzinfo=timezone.utc))
        .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
        .add_extension(
            x509.KeyUsage(
                digital_signature=True, content_commitment=False, key_encipherment=True,
                data_encipherment=False, key_agreement=False, key_cert_sign=True,
                crl_sign=True, encipher_only=False, decipher_only=False,
            ),
            critical=True,
        )
        .sign(key, hashes.SHA256())
    )
    return key, cert


def build_license(tag: str | None) -> etree._Element:
    nsmap = {"lns": LNS, "ds": DS, "xsi": "http://www.w3.org/2001/XMLSchema-instance"}
    root = etree.Element(f"{{{LNS}}}LicenseClass", nsmap=nsmap)
    ld = etree.SubElement(root, f"{{{LNS}}}LicenseData")

    schema = etree.SubElement(ld, f"{{{LNS}}}Schema")
    schema.set(f"{{{LNS}}}Vendor", "Dell")
    schema.set(f"{{{LNS}}}ID", "iDRAC")
    schema.set(f"{{{LNS}}}maxDepth", "255")
    schema.set(f"{{{LNS}}}SchemaVersion", "2.0")

    etree.SubElement(ld, f"{{{LNS}}}TransferableLicense").text = "true"
    etree.SubElement(ld, f"{{{LNS}}}UTCdateSold").text = "2026-11-19T00:00:00Z"
    etree.SubElement(ld, f"{{{LNS}}}EntitlementID").text = "DE00000000000001"
    etree.SubElement(ld, f"{{{LNS}}}DeviceClass").set(f"{{{LNS}}}ID", "iDRAC")

    pd = etree.SubElement(ld, f"{{{LNS}}}ProductDescription")
    for lang in ("en", "es", "fr", "de", "it", "ja", "zh"):
        etree.SubElement(pd, f"{{{LNS}}}lang_{lang}").text = "iDRAC8 Enterprise License"

    lt = etree.SubElement(ld, f"{{{LNS}}}LicenseTerm")
    etree.SubElement(lt, f"{{{LNS}}}Perpetual")

    if tag is not None:
        restr = etree.SubElement(ld, f"{{{LNS}}}Restrictions")
        etree.SubElement(restr, f"{{{LNS}}}ServiceTag").text = tag

    di = etree.SubElement(ld, f"{{{LNS}}}DeviceInfo")
    di.set(f"{{{LNS}}}ID", "1")
    di.set(f"{{{LNS}}}VendorID", "0x1912")
    di.set(f"{{{LNS}}}DeviceID", "0x0011")
    di.set(f"{{{LNS}}}SubsystemVendorID", "0x1028")
    di.set(f"{{{LNS}}}SubsystemDeviceID", "0x1")

    f = etree.SubElement(ld, f"{{{LNS}}}Feature")
    f.set(f"{{{LNS}}}ID", "253")
    f.set(f"{{{LNS}}}Description", "Integrated Dell Remote Access Controller 8 Enterprise")
    f.set(f"{{{LNS}}}Enabled", "true")
    return root


def sign_license(root, key, cert):
    """Sign root with XML-DSIG (enveloped, exc-c14n, RSA-SHA1, SHA1)."""
    import hashlib

    # Digest is over the document with the Signature element removed.
    # Build the signature with no tail so removal is a no-op on the rest.
    digest = hashlib.sha1(
        etree.tostring(root, method="c14n", exclusive=False, with_comments=False)
    ).digest()

    sig = etree.SubElement(root, f"{{{DS}}}Signature")
    si = etree.SubElement(sig, f"{{{DS}}}SignedInfo")

    cm = etree.SubElement(si, f"{{{DS}}}CanonicalizationMethod")
    cm.set("Algorithm", "http://www.w3.org/2001/10/xml-exc-c14n#")
    sm = etree.SubElement(si, f"{{{DS}}}SignatureMethod")
    sm.set("Algorithm", "http://www.w3.org/2000/09/xmldsig#rsa-sha1")

    ref = etree.SubElement(si, f"{{{DS}}}Reference")
    ref.set("URI", "")
    transforms = etree.SubElement(ref, f"{{{DS}}}Transforms")
    tr = etree.SubElement(transforms, f"{{{DS}}}Transform")
    tr.set("Algorithm", "http://www.w3.org/2000/09/xmldsig#enveloped-signature")
    dm = etree.SubElement(ref, f"{{{DS}}}DigestMethod")
    dm.set("Algorithm", "http://www.w3.org/2000/09/xmldsig#sha1")
    etree.SubElement(ref, f"{{{DS}}}DigestValue").text = base64.b64encode(digest).decode()

    signed_info_c14n = etree.tostring(si, method="c14n", exclusive=True, with_comments=False)
    signature = key.sign(signed_info_c14n, padding.PKCS1v15(), hashes.SHA1())

    etree.SubElement(sig, f"{{{DS}}}SignatureValue").text = base64.b64encode(signature).decode()

    ki = etree.SubElement(sig, f"{{{DS}}}KeyInfo")
    xd = etree.SubElement(ki, f"{{{DS}}}X509Data")
    cert_b64 = base64.b64encode(
        cert.public_bytes(serialization.Encoding.DER)
    ).decode()
    etree.SubElement(xd, f"{{{DS}}}X509Certificate").text = cert_b64
    return root


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--tag", help="service tag to bind to (omit or use --no-tag for unbound)")
    ap.add_argument("--no-tag", action="store_true",
                    help="omit the Restrictions element entirely (unbound license)")
    ap.add_argument("--out", required=True)
    ap.add_argument("--dell-subject", action="store_true",
                    help="use Dell's signing-cert subject name in the self-signed cert")
    args = ap.parse_args()
    if not args.tag and not args.no_tag:
        ap.error("--tag or --no-tag is required")

    key, cert = make_cert(args.dell_subject)
    root = build_license(None if args.no_tag else args.tag.upper())
    root = sign_license(root, key, cert)

    with open(args.out, "wb") as fh:
        fh.write(etree.tostring(root, xml_declaration=True, encoding="UTF-8"))
    scope = "unbound" if args.no_tag else f"tag={args.tag.upper()}"
    print(f"wrote {args.out} ({scope}, self-signed cert)")


if __name__ == "__main__":
    main()
