#!/usr/bin/env python3
"""
make_variants.py - build license files that isolate which check iDRAC8 performs.

Base: the genuine iDRAC8 240-day eval (no ServiceTag restriction).
We add a Restrictions/ServiceTag and then deliberately break one layer at a time:

  tampered_sigonly.xml  - original DigestValue + SignatureValue, doc changed.
                          Passes only if the reference digest is NOT checked.
  tampered_digest.xml   - DigestValue recomputed, SignatureValue untouched.
                          Passes only if the RSA signature is NOT checked.
  unsigned.xml          - Signature element removed.
                          Passes only if signature verification is optional.
"""
import base64
import copy
import hashlib
import sys

from lxml import etree

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

BASE = "idrac8/licenses/iDRAC8_Enterprise_Extended_Eval_License.xml"
TAG = "9QYZF42"


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


def doc_digest(root):
    doc = etree.fromstring(etree.tostring(root))
    sig = doc.find("ds:Signature", NS)
    prev = sig.getprevious()
    if prev is not None:
        prev.tail = (prev.tail or "") + (sig.tail or "")
    sig.getparent().remove(sig)
    return hashlib.sha1(c14n(doc, exclusive=False)).digest()


def add_tag(root, tag):
    ld = root.find("lns:LicenseData", NS)
    restr = etree.Element(f"{{{LNS}}}Restrictions")
    etree.SubElement(restr, f"{{{LNS}}}ServiceTag").text = tag
    # Restrictions must come after LicenseTerm and before DeviceInfo.
    di = ld.find("lns:DeviceInfo", NS)
    di.addprevious(restr)
    return root


def main():
    tree = etree.parse(BASE)
    root = tree.getroot()
    add_tag(root, TAG)

    # --- A: signature-only (keep both original digest and signature) ------
    a = copy.deepcopy(root)
    a.getroottree().write("idrac8/licenses/tampered_sigonly_%s.xml" % TAG,
                          xml_declaration=True, encoding="UTF-8")

    # --- B: digest-only (recompute DigestValue, keep SignatureValue) ------
    b = copy.deepcopy(root)
    d = doc_digest(b)
    b.find("ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestValue", NS).text = \
        base64.b64encode(d).decode()
    b.getroottree().write("idrac8/licenses/tampered_digest_%s.xml" % TAG,
                          xml_declaration=True, encoding="UTF-8")

    # --- C: unsigned ------------------------------------------------------
    c = copy.deepcopy(root)
    sig = c.find("ds:Signature", NS)
    prev = sig.getprevious()
    if prev is not None:
        prev.tail = (prev.tail or "") + (sig.tail or "")
    sig.getparent().remove(sig)
    c.getroottree().write("idrac8/licenses/unsigned_%s.xml" % TAG,
                          xml_declaration=True, encoding="UTF-8")

    print("wrote tampered_sigonly, tampered_digest, unsigned for tag", TAG)


if __name__ == "__main__":
    main()
