crewjam/saml - IdP XSS Via Missing Binding Syntax Validation In ACS Location
Published on doyensec.com
crewjam/saml IdP XSS Via Missing Binding Syntax Validation In ACS Location Created by Francesco Lacerenza 10/17/2023
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
The target is the Go library crewjam/saml, an implementation of the SAML identity federation standard. In SAML, an Identity Provider (IdP) authenticates users, and a Service Provider (SP) delegates authentication to an IdP. The library implements the most commonly used subset of features required to provide a single sign on flow, and supports at least the subset of SAML known as interoperable SAML for both service providers and identity providers.
The Assertion Consumer Service (ACS) is the endpoint where a third-party service provider receives and processes SAML assertions from an IdP as part of the SAML-based single sign-on (SSO) process. The vulnerability was found while performing a security audit for one of Doyensec's customers. The audit was not meant to be comprehensive in terms of attack and code coverage, but it identified a stored cross-site scripting pattern within the service providers registration, allowing a malicious SP to execute JavaScript within the identity provider's context in SAML flows.
The advisory lists the vendor as Crewjam, severity High, vulnerability class Cross Site Scripting (XSS), with the affected components at samlsp/fetch_metadata.go:25 and crewjam/saml/identity_provider.go:927. The status is Closed and the CVE is CVE-2023-45683. The credit goes to Francesco Lacerenza.
Setup
The finding came out of a customer engagement, and the issue was reported to the client during that engagement. The proof of concept is a small Go program that imports github.com/crewjam/saml/samlsp, parses an attacker-controlled entity descriptor, and prints the parsed ACS location. To demonstrate the second half of the issue, the advisory says to use the testing IdP implemented with crewjam/saml and serve the malicious SP defined in the test. No specific Go version, library version or deployment configuration is given beyond the released fix version, 0.4.14.
The precondition that makes the issue serious is that SP registration is commonly an unrestricted operation in IdPs, hence not requiring particular permissions or being publicly accessible to ease IdP interoperability. The advisory rates the severity High for exactly this reason.
Finding it
The starting point is the SAML standard itself. The complex type EndpointType describes a SAML protocol binding endpoint at which a SAML entity can be sent protocol messages. The Metadata for the OASIS Security Assertion Markup Language (SAML) V2.0 2.2.2 defines the location of an endpoint type as follows:
Location [Required] A required URI attribute that specifies the location of the endpoint. The allowable syntax of this URI depends on the protocol binding.
Chapter 3.5.4 Message Encoding of the OASIS SAML Bindings 2.0 specification further defines the action attribute of the SAML response form:
The action attribute of the form MUST be the recipient's HTTP endpoint for the protocol or profile using this binding to which the SAML message is to be delivered. The method attribute MUST be "POST"
Against that requirement, the library does not validate the ACS Location URI according to the SAML binding being parsed. The advisory identifies two operations where the check is missing:
- Entity Descriptors Parsing: Service Providers are declared with Entity Descriptors parseable with the function
ParseMetadatadefined atsamlsp/fetch_metadata.go:25. - Response Form Construction: SAML Responses are constructed as auto-submitted forms according to the SP metadata at
crewjam/saml/identity_provider.go:927.
Exploitation
Step 1: parse a malicious entity descriptor
The library does not verify that the parsed location follows the syntax required for the binding being declared. The ParseMetadata function is defined at samlsp/fetch_metadata.go:25:
func ParseMetadata(data []byte) (*saml.EntityDescriptor, error) {
entity := &saml.EntityDescriptor{}
if err := xrv.Validate(bytes.NewBuffer(data)); err != nil {
return nil, err
}
err := xml.Unmarshal(data, entity)
// this comparison is ugly, but it is how the error is generated in encoding/xml
if err != nil && err.Error() == "expected element type <EntityDescriptor> but have <EntitiesDescriptor>" {
entities := &saml.EntitiesDescriptor{}
if err := xml.Unmarshal(data, entities); err != nil {
return nil, err
}
for i, e := range entities.EntityDescriptors {
if len(e.IDPSSODescriptors) > 0 {
return &entities.EntityDescriptors[i], nil
}
}
return nil, errors.New("no entity found with IDPSSODescriptor")
}
if err != nil {
return nil, err
}
return entity, nil
}
The function executes xml.Unmarshal on the user-supplied data without performing further checks on the contents.
The proof of concept is a test file, PoC.go, that declares an entity descriptor with two AssertionConsumerService elements whose Location is a javascript: URI, one for HTTP-POST and one for HTTPArtifact:
package main
import (
"fmt"
"github.com/crewjam/saml/samlsp"
)
func main() {
entityDescr := `
<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" validUntil="2023-07-06T12:21:21.317Z" entityID="http://localhost:8000/saml/metadata">
<SPSSODescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" validUntil="2023-07-06T12:21:21.317018Z" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol" AuthnRequestsSigned="false" WantAssertionsSigned="true">
<SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="http://localhost:8000/saml/slo" ResponseLocation="http://localhost:8000/saml/slo"></SingleLogoutService>
<NameIDFormat></NameIDFormat>
<AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location='javascript:alert("Hello Doyensec!")' index="1"></AssertionConsumerService>
<AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTPArtifact" Location='javascript:alert("Hello Doyensec!")' index="2"></AssertionConsumerService>
</SPSSODescriptor>
</EntityDescriptor>
`
ed, err := samlsp.ParseMetadata([]byte(entityDescr))
if err != nil {
fmt.Print(err)
}
fmt.Print(ed.SPSSODescriptors[0].AssertionConsumerServices[0].Location)
}
The descriptor declares the SP with entityID http://localhost:8000/saml/metadata and two ACS entries. The first uses Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" with Location='javascript:alert("Hello Doyensec!")' and index="1"; the second uses Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTPArtifact" with the same location and index="2". The program parses the descriptor and prints the location of the first ACS.
Compile and execute:
❯ ./testcrewjamlib
javascript:alert("Hello Doyensec!”)%
The output shows the javascript: scheme surviving parsing unchanged.
Step 2: build the SAML response form
Whenever a binding is handled, a basic template logic is used to directly add the parsed information to the resulting HTML form. The PostBinding function at crewjam/saml/identity_provider.go:896 creates the HTTP POST form information for the IdpAuthnRequest:
// PostBinding creates the HTTP POST form information for this
// `IdpAuthnRequest`. If `Response` is not already set, it calls MakeResponse
// to produce it.
func (req *IdpAuthnRequest) PostBinding() (IdpAuthnRequestForm, error) {
var form IdpAuthnRequestForm
if req.ResponseEl == nil {
if err := req.MakeResponse(); err != nil {
return form, err
}
}
doc := etree.NewDocument()
doc.SetRoot(req.ResponseEl)
responseBuf, err := doc.WriteToBytes()
if err != nil {
return form, err
}
if req.ACSEndpoint.Binding != HTTPPostBinding {
return form, fmt.Errorf("%s: unsupported binding %s", req.ServiceProviderMetadata.EntityID, req.ACSEndpoint.Binding)
}
form.URL = req.ACSEndpoint.Location
form.SAMLResponse = base64.StdEncoding.EncodeToString(responseBuf)
form.RelayState = req.RelayState
return form, nil
}
The form.URL value is taken from the ACSEndpoint.Location. The code continues with the templating at line 927, where WriteResponse is responsible for the final SAML response form creation:
// WriteResponse writes the `Response` to the http.ResponseWriter. If
// `Response` is not already set, it calls MakeResponse to produce it.
func (req *IdpAuthnRequest) WriteResponse(w http.ResponseWriter) error {
form, err := req.PostBinding()
if err != nil {
return err
}
tmpl := template.Must(template.New("saml-post-form").Parse(`<html>` +
`<form method="post" action="{{.URL}}" id="SAMLResponseForm">` +
`<input type="hidden" name="SAMLResponse" value="{{.SAMLResponse}}" />` +
`<input type="hidden" name="RelayState" value="{{.RelayState}}" />` +
`<input id="SAMLSubmitButton" type="submit" value="Continue" />` +
`</form>` +
`<script>document.getElementById('SAMLSubmitButton').style.visibility='hidden';</script>` +
`<script>document.getElementById('SAMLResponseForm').submit();</script>` +
`</html>`))
buf := bytes.NewBuffer(nil)
if err := tmpl.Execute(buf, form); err != nil {
return err
}
if _, err := io.Copy(w, buf); err != nil {
return err
}
return nil
}
The action attribute is blindly trusted and added to the form even if it did not respect the binding specification. In particular, the exposed pattern allows the creation of malicious SPs with a JavaScript based ACS. The advisory's malicious ACS example is:
javascript:alert(“Doyensec”)
As a result, any use of the library in which the attacker is able to register service providers could result in a Stored Cross-Site-Scripting (XSS) against the IdP.
Step 3: trigger the flow against the IdP
To demonstrate the missing validation during SAML response form construction, the advisory says to use the testing IdP implemented with crewjam/saml and serve the malicious SP defined during the test above. The SAML flow with the SP ends with an alert box spawned within the IdP context, which allows full control of the authenticated user's session.
The SAML Response form below was generated by crewjam/saml from an SP with a long JavaScript function as ACS. The function allowed the execution of actions in the IdP with the victim's authenticated session:
The action attribute carries the attacker's JavaScript instead of an HTTP endpoint. The function allowed actions to be executed in the IdP with the victim's authenticated session.
Root cause
The mistake is that the library never checks the ACS Location URI against the syntax required by the declared binding. The SAML metadata specification makes the allowable syntax of the location depend on the protocol binding, and the bindings specification requires the form action to be the recipient's HTTP endpoint. ParseMetadata runs xml.Unmarshal on user-supplied data without further checks on the contents, so a javascript: URI is accepted as an ACS location for both HTTP-POST and HTTPArtifact. Later, PostBinding copies req.ACSEndpoint.Location into form.URL, and WriteResponse interpolates it into the action attribute of the auto-submitted form.
Impact
If abused, the flaw allows attackers to register malicious Service Providers at the IdP and inject JavaScript in the ACS endpoint definition, achieving Cross-Site-Scripting in the IdP context during the redirection at the end of a SAML SSO flow. Consequently, an attacker may perform any authenticated action as the victim once the victim's browser loaded the SAML IdP initiated SSO link for the malicious service provider.
The severity is considered High because SP registration is commonly an unrestricted operation in IdPs, hence not requiring particular permissions or being publicly accessible to ease IdP interoperability. The advisory does not state which specific deployments are affected beyond that condition: any use of the library in which the attacker is able to register service providers could result in a stored XSS against the IdP.
Fix
The issue was fixed and merged in the master branch, and version 0.4.14 was released. CVE-2023-45683 was assigned and the official advisory published. The advisory recommends applying changes in the core steps involved with SP registration:
- Validate the Service Provider defined in the entity descriptor parsed by the
ParseMetadatafunction atsamlsp/fetch_metadata.go:25. Users should be able to trust the SP parsed by the function. Alternatively, adjust the documentation to warn users about the need to implement further checks. - Align the response form construction to the SAML standard. The basic IdP implementation should not serve Service Providers without preventing injections inside the resulting responses. In order to protect the IdP against Cross-Site Scripting, validate the SP attributes before using them inside the SAML response form, at
crewjam/saml/identity_provider.go:927.
Disclosure timeline:
| Date | Event |
|---|---|
| 08/11/2023 | Issue reported to the client during an engagement |
| 09/20/2023 | Doyensec got authorization from the client to disclose the issue to the maintainers |
| 10/14/2023 | Issue fixed and merged in master branch |
| 10/14/2023 | Version 0.4.14 released |
| 10/14/2023 | CVE-2023-45683 assigned and official advisory published |
Variants to test
- Other bindings on the same ACS element. Submit an entity descriptor whose
AssertionConsumerServiceuses a binding other than HTTP-POST or HTTPArtifact with ajavascript:location. A positive result isParseMetadatareturning the location unchanged, or the response form being built with that location inaction. - Other URI schemes. Try
data:,vbscript:and mixed-case variants such asJaVaScRiPt:in the ACSLocation. A positive result is the scheme surviving parsing and appearing in the generated form'sactionattribute. - Other endpoint types. Apply the same payload to
SingleLogoutServiceLocationandResponseLocation, and to other metadata endpoints that are later rendered into redirects or forms. A positive result is the value being reflected into an attribute or redirect target without a scheme check. - HTML-breaking characters in the location. Use quotes and angle brackets inside the
Locationvalue to see whether the template escaping holds. A positive result is a broken attribute or an injected element in the rendered form. - Registration paths that bypass
ParseMetadata. Feed the entity descriptor through any other import, upload or admin API the IdP exposes. A positive result is a stored SP whose ACS location is ajavascript:URI and which is later used to build a response form. - IdP-initiated flow. Load the IdP-initiated SSO link for a malicious SP while authenticated. A positive result is script execution in the IdP origin, for example an alert box or a request carrying the victim's session.
What happened, in plain words
A company called Doyensec was hired to look for security problems in a customer's software. During that work they found a bug in a free, publicly available piece of software called crewjam/saml, a library written in the Go programming language. A library is a bundle of ready-made code that other programmers reuse instead of writing everything from scratch, a bit like buying a pre-built kitchen cabinet rather than cutting the wood yourself.
This particular library implements SAML, a standard that lets one website trust another website's login. The bug means that an attacker who can register their own website with a login server built on this library can slip a small piece of JavaScript (code that runs inside a web browser) into the login server's pages. When a logged-in victim's browser reaches the end of a login flow, that code runs as if the login server itself had written it. From there the attacker can do anything the victim could do on that server.
The problem is rated High severity and was given the identifier CVE-2023-45683. A CVE is a public catalogue number for a known security flaw, so people can look it up and track the fix. The flaw was fixed and version 0.4.14 of the library was released. The person credited with the finding is Francesco Lacerenza.
The pieces you need to know
Before the details make sense, here are the main ideas, explained from zero.
SAML and single sign-on. Imagine a large company with one central login page. Employees log in there once, and then every internal tool (email, holiday booking, the wiki) accepts that login without asking for a password again. That is single sign-on, or SSO. SAML is one of the standards that makes it work. Two roles are involved:
- The Identity Provider (IdP) is the central login service. It checks who you are and hands out a signed statement saying so.
- The Service Provider (SP) is any application that trusts the IdP. It does not check passwords itself; it sends you to the IdP and waits for the signed statement.
A useful comparison is a festival. The IdP is the ticket office that checks your ID and gives you a wristband. Each SP is a tent that looks at the wristband and lets you in without asking for ID again.
The Assertion Consumer Service (ACS). When the IdP has confirmed who you are, it needs to send the signed statement back to the SP. The ACS is the address at the SP where that statement is delivered and processed. In festival terms, it is the exact door of the tent where the wristband is checked.
Metadata and entity descriptors. For the IdP to know where to send the statement, the SP publishes a small XML document describing itself: its name, its ACS address, which delivery method it wants, and so on. XML is a text format that uses tags in angle brackets, like <name>value</name>, to label pieces of data. This self-description is called an entity descriptor, and the SP's section inside it is the SPSSODescriptor.
Bindings. SAML offers several ways to deliver a message, called bindings. Two appear in this report:
- HTTP-POST: the IdP builds a web page containing a form and the browser automatically submits it to the SP, carrying the statement in a hidden field.
- HTTPArtifact: the browser carries a short reference (an artifact) and the SP fetches the full statement separately.
The important point is that the address format allowed depends on the binding. The SAML specification says so explicitly.
URI and scheme. A URI is an address string. The part before the first colon is the scheme, which tells the browser what kind of address it is: http, https, mailto, and so on. One scheme is javascript:. When a browser is asked to follow a javascript: address, it does not fetch a page; it runs the code that follows the colon. That is exactly what an attacker wants here.
Cross-Site Scripting (XSS). XSS is a class of bug where an attacker gets their own code to run inside a page belonging to someone else's website. The browser cannot tell the difference: code that arrives through a flaw runs with the same powers as the site's own code. It can read what the logged-in user sees, act on their behalf, and read data the site stored in the browser. Stored XSS means the malicious content is saved on the server first (here, in the SP registration) and served to victims later, rather than being crafted fresh in a single link.
Cookie and token. After you log in, a website usually gives your browser a small piece of data to present on every later request, so it knows you are still you. A cookie is stored by the browser and sent automatically. A token is a similar credential, often kept in the browser's localStorage (a small storage area websites can write to) and attached by the site's own code. Stealing either one usually means impersonating the user.
CSRF token. A CSRF token is a random value a site puts into its pages so that a request coming from a different site cannot easily forge a legitimate action.
Go, functions and line numbers. Go is a programming language. A function is a named block of code that does one job. When the report writes samlsp/fetch_metadata.go:25, it means the file fetch_metadata.go inside the samlsp folder, at line 25. That is simply how you point someone to the exact place in the code.
The finding
The starting point is what the SAML standard itself requires. The standard defines a data type called EndpointType, which describes an address where a SAML message can be sent. The Metadata for the OASIS Security Assertion Markup Language (SAML) V2.0, section 2.2.2, says this about the location of an endpoint:
Location [Required] A required URI attribute that specifies the location of the endpoint. The allowable syntax of this URI depends on the protocol binding.
Read that last sentence again: the format of the address is not free-form. It must match the binding. Chapter 3.5.4, Message Encoding, of the OASIS SAML Bindings 2.0 specification adds a rule for the form the IdP builds:
The action attribute of the form MUST be the recipient's HTTP endpoint for the protocol or profile using this binding to which the SAML message is to be delivered. The method attribute MUST be "POST"
In plain words: the form's action (the address the browser goes to when the form is submitted) must be an ordinary web address belonging to the SP, and the form must use the POST method (data sent in the request body rather than in the address).
Against those two rules, the library checks nothing. The advisory names two places where the check is missing:
- Entity Descriptors Parsing: when the library reads an SP's self-description, through the function
ParseMetadataatsamlsp/fetch_metadata.go:25. - Response Form Construction: when the library builds the auto-submitted form that carries the login statement, at
crewjam/saml/identity_provider.go:927.
Why does this matter in practice? Because registering an SP with an IdP is usually an open operation. IdPs want to work with many applications, so they often let anyone add an SP without special permissions, sometimes even without logging in. The advisory rates the issue High for exactly that reason: SP registration commonly requires no particular permissions or is publicly accessible.
Step 1: parsing a malicious entity descriptor
The first half of the bug is in the code that reads an SP's metadata. Here is ParseMetadata as it appears in the library:
func ParseMetadata(data []byte) (*saml.EntityDescriptor, error) {
entity := &saml.EntityDescriptor{}
if err := xrv.Validate(bytes.NewBuffer(data)); err != nil {
return nil, err
}
err := xml.Unmarshal(data, entity)
// this comparison is ugly, but it is how the error is generated in encoding/xml
if err != nil && err.Error() == "expected element type <EntityDescriptor> but have <EntitiesDescriptor>" {
entities := &saml.EntitiesDescriptor{}
if err := xml.Unmarshal(data, entities); err != nil {
return nil, err
}
for i, e := range entities.EntityDescriptors {
if len(e.IDPSSODescriptors) > 0 {
return &entities.EntityDescriptors[i], nil
}
}
return nil, errors.New("no entity found with IDPSSODescriptor")
}
if err != nil {
return nil, err
}
return entity, nil
}
Line by line, in plain words:
func ParseMetadata(data []byte) (*saml.EntityDescriptor, error)declares a function namedParseMetadata. It takesdata, a chunk of raw bytes (the XML text the SP supplied), and returns either a parsed entity descriptor or an error.entity := &saml.EntityDescriptor{}creates an empty container to hold the parsed result.if err := xrv.Validate(bytes.NewBuffer(data)); err != nil { return nil, err }runs a schema validator (xrv.Validate) over the XML. A schema is a formal description of which tags and attributes are allowed. If the XML does not match the schema, the function stops and returns the error. This is the only structural check in the function.err := xml.Unmarshal(data, entity)converts the XML text into the Go data structure.xml.Unmarshalis a general-purpose converter: it reads tags and fills fields, and it does not know or care what a SAML binding is.- The long
ifcompares the error message to a specific string. The comment explains why: the XML converter produces that exact wording when the document is a list of entities rather than a single one. The code is working around a quirk of the converter, not checking security. - Inside that branch, the code parses the document as a list (
EntitiesDescriptor), then loops over each entry looking for one that contains an IdP descriptor, and returns the first match. If none is found, it returns the errorno entity found with IDPSSODescriptor. - The final lines return the parsed entity, or the error if parsing failed.
The key sentence from the advisory is this: the function executes xml.Unmarshal on the user-supplied data without performing further checks on the contents. Nothing here asks whether the ACS address is an http or https address, or whether it suits the declared binding. Whatever the XML says is accepted.
To prove it, the advisory provides a small test program, PoC.go. PoC stands for proof of concept: the smallest program that demonstrates the bug is real.
package main
import (
"fmt"
"github.com/crewjam/saml/samlsp"
)
func main() {
entityDescr := `
<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" validUntil="2023-07-06T12:21:21.317Z" entityID="http://localhost:8000/saml/metadata">
<SPSSODescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" validUntil="2023-07-06T12:21:21.317018Z" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol" AuthnRequestsSigned="false" WantAssertionsSigned="true">
<SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="http://localhost:8000/saml/slo" ResponseLocation="http://localhost:8000/saml/slo"></SingleLogoutService>
<NameIDFormat></NameIDFormat>
<AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location='javascript:alert("Hello Doyensec!")' index="1"></AssertionConsumerService>
<AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTPArtifact" Location='javascript:alert("Hello Doyensec!")' index="2"></AssertionConsumerService>
</SPSSODescriptor>
</EntityDescriptor>
`
ed, err := samlsp.ParseMetadata([]byte(entityDescr))
if err != nil {
fmt.Print(err)
}
fmt.Print(ed.SPSSODescriptors[0].AssertionConsumerServices[0].Location)
}
What each part does:
package mainandfunc main()mark this as a complete runnable program;mainis where execution starts.importpulls in two packages:fmtfor printing text, andgithub.com/crewjam/saml/samlsp, the part of the library that handles the service provider side.entityDescr :=... `` is a long text string holding the XML document. The backticks let the string span several lines.- Inside the XML,
<EntityDescriptor ... entityID="http://localhost:8000/saml/metadata">names the SP.localhost:8000means the same computer the program runs on, port 8000, so this is a harmless local test address. <SPSSODescriptor ...>opens the SP's section. The attributes say which SAML protocol version it speaks and whether requests and assertions must be signed.<SingleLogoutService ...>describes where logout messages go. ItsLocationis an ordinaryhttp://address, which is what a well-behaved SP looks like.- The two
<AssertionConsumerService>elements are the interesting ones. The first declaresBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"and the secondBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTPArtifact". Both haveLocation='javascript:alert("Hello Doyensec!")', and they are numberedindex="1"andindex="2". Thealert(...)part is a browser instruction to pop up a message box. ed, err := samlsp.ParseMetadata([]byte(entityDescr))hands the XML to the library function we just read.[]byte(...)converts the text into raw bytes, which is what the function expects.if err != nil { fmt.Print(err) }prints any error.fmt.Print(ed.SPSSODescriptors[0].AssertionConsumerServices[0].Location)reaches into the parsed result, takes the first SP, its first ACS entry, and prints theLocationvalue.
The program is compiled and run, and produces:
❯ ./testcrewjamlib
javascript:alert("Hello Doyensec!”)%
The ❯ is the shell prompt, and ./testcrewjamlib is the compiled program being started. The output is the ACS location, printed back exactly as it was written in the XML, javascript: scheme and all. The library accepted the javascript: address unchanged.
Step 2: building the response form
The second half is what the IdP does with that address later. When the IdP is about to send a login statement to an SP, it builds an HTML form and has the browser submit it automatically. The function PostBinding at crewjam/saml/identity_provider.go:896 prepares the pieces of that form:
// PostBinding creates the HTTP POST form information for this
// `IdpAuthnRequest`. If `Response` is not already set, it calls MakeResponse
// to produce it.
func (req *IdpAuthnRequest) PostBinding() (IdpAuthnRequestForm, error) {
var form IdpAuthnRequestForm
if req.ResponseEl == nil {
if err := req.MakeResponse(); err != nil {
return form, err
}
}
doc := etree.NewDocument()
doc.SetRoot(req.ResponseEl)
responseBuf, err := doc.WriteToBytes()
if err != nil {
return form, err
}
if req.ACSEndpoint.Binding != HTTPPostBinding {
return form, fmt.Errorf("%s: unsupported binding %s", req.ServiceProviderMetadata.EntityID, req.ACSEndpoint.Binding)
}
form.URL = req.ACSEndpoint.Location
form.SAMLResponse = base64.StdEncoding.EncodeToString(responseBuf)
form.RelayState = req.RelayState
return form, nil
}
In plain words:
- The comment says the function creates the HTTP POST form information for a login request, and builds the response first if it does not exist yet.
var form IdpAuthnRequestFormcreates an empty form description.if req.ResponseEl == nil { ... req.MakeResponse() ... }builds the SAML response if it has not been built already.doc := etree.NewDocument(),doc.SetRoot(req.ResponseEl)anddoc.WriteToBytes()turn the response into XML bytes, ready to be placed in the form.if req.ACSEndpoint.Binding != HTTPPostBinding { return form, fmt.Errorf(...) }is the only check on the binding: if it is not HTTP-POST, the function refuses. Note what it does not check: the format of the address itself.form.URL = req.ACSEndpoint.Locationcopies the SP's ACS address straight into the form's target. This is the line that carries the attacker'sjavascript:string forward.form.SAMLResponse = base64.StdEncoding.EncodeToString(responseBuf)encodes the response in base64, a way of writing binary data using ordinary letters and digits so it can travel inside a web form.form.RelayState = req.RelayStatecopies the relay state, an extra value the SP can use to remember where the user wanted to go.
The code then continues at line 927, where WriteResponse turns that form description into the final HTML page:
// WriteResponse writes the `Response` to the http.ResponseWriter. If
// `Response` is not already set, it calls MakeResponse to produce it.
func (req *IdpAuthnRequest) WriteResponse(w http.ResponseWriter) error {
form, err := req.PostBinding()
if err != nil {
return err
}
tmpl := template.Must(template.New("saml-post-form").Parse(`<html>` +
`<form method="post" action="{{.URL}}" id="SAMLResponseForm">` +
`<input type="hidden" name="SAMLResponse" value="{{.SAMLResponse}}" />` +
`<input type="hidden" name="RelayState" value="{{.RelayState}}" />` +
`<input id="SAMLSubmitButton" type="submit" value="Continue" />` +
`</form>` +
`<script>document.getElementById('SAMLSubmitButton').style.visibility='hidden';</script>` +
`<script>document.getElementById('SAMLResponseForm').submit();</script>` +
`</html>`))
buf := bytes.NewBuffer(nil)
if err := tmpl.Execute(buf, form); err != nil {
return err
}
if _, err := io.Copy(w, buf); err != nil {
return err
}
return nil
}
Again, line by line:
- The comment says the function writes the response to the web response writer, which is the object that sends the page back to the browser.
form, err := req.PostBinding()calls the function above to get the form description.tmpl := template.Must(template.New("saml-post-form").Parse(...))defines an HTML template. A template is a page with blanks in it; the{{.URL}}style placeholders get filled with values from the form description.template.Muststops the program if the template itself is malformed.- Inside the template,
<form method="post" action="{{.URL}}" id="SAMLResponseForm">is the form. Itsactionis the blank that receives the ACS address. The two hidden inputs carry the base64 response and the relay state, so the user never sees them. - The first
<script>hides the Continue button, and the second<script>calls.submit()on the form. That is the auto-submit: the user does not click anything, the browser sends the form by itself. buf := bytes.NewBuffer(nil)creates an empty buffer, a temporary holding area in memory.tmpl.Execute(buf, form)fills the template with the form values and writes the result into the buffer.io.Copy(w, buf)sends the finished page to the browser.
The advisory's verdict is blunt: the action attribute is blindly trusted and added to the form even if it did not respect the binding specification. The action attribute is blindly trusted and added to the form even if it did not respect the binding specification. The problem is not broken markup; it is a valid address with a dangerous scheme. The browser sees a form whose action is javascript: and, when the form is submitted, runs the code instead of navigating.
The advisory gives a minimal malicious ACS address:
javascript:alert(“Doyensec”)
Put that in an SP's ACS location, and the IdP will build a form that runs it. Because the malicious SP is saved on the IdP, every victim who goes through the flow gets the same code: that is what makes it stored XSS. The advisory's conclusion is that any use of the library in which the attacker is able to register service providers could result in a Stored Cross-Site-Scripting (XSS) against the IdP.
Step 3: triggering the flow against the IdP
To show the second half in action, the advisory says to use the testing IdP implemented with crewjam/saml and serve the malicious SP defined in the test above. In other words: stand up a small IdP using the library, register the SP whose ACS is a javascript: address, then walk through a login. The SAML flow with the SP ends with an alert box spawned within the IdP context. The alert box is the visible proof; the real consequence is that the code runs with the victim's authenticated session, so the attacker has full control of it.
The advisory then shows a form that crewjam/saml generated from an SP whose ACS was a long JavaScript function rather than a simple alert. That function allowed actions to be performed in the IdP with the victim's authenticated session:
What is going on in that snippet:
- The
actionattribute no longer holds a web address. It holds a JavaScript function, starting withjavascript:(function(){ ... })();. The(function(){ ... })();pattern defines a function and runs it immediately. var xhttp=new XMLHttpRequest()creates a request object, the browser's built-in way of fetching another page in the background.xhttp.onreadystatechange=function(){if(this.readyState==4){ ... }}says: when the fetch finishes (state 4 means done), run the rest.const parser=new DOMParser()andparser.parseFromString(xhttp.responseText,'text/html')turn the fetched page into something the script can search through.const csrfToken=htmlDoc.querySelector(meta[name='test_csrf_token']).getAttribute('content')finds a CSRF token in that page. Reading it is what lets the script forge requests the IdP will accept as coming from the real user.const bearerToken=JSON.parse(localStorage.getItem(‘test_token’))[‘accessToken’]reads a stored login token from the browser'slocalStorageunder the keytest_token. This is the credential theft step....[REDACTED_EXPLOIT]...marks the part of the exploit that was removed from the public advisory. The report does not show what it contained.- The
SAMLResponsehidden field is also redacted, shown only asPH...[REDACTED]....
Why does this run as the IdP? Because the form is served by the IdP, from the IdP's own address, and the script that submits it is in the same page. The function allowed actions to be executed in the IdP with the victim's authenticated session. The victim only has to load the IdP-initiated SSO link for the malicious SP while logged in.
Why it happened
The root cause is a missing check, not a clever trick. The SAML metadata specification says the allowed syntax of an endpoint address depends on the protocol binding, and the bindings specification says the form action must be the recipient's HTTP endpoint. The library enforces neither. ParseMetadata runs xml.Unmarshal on user-supplied data without further checks on the contents, so a javascript: address is accepted for both HTTP-POST and HTTPArtifact. Later, PostBinding copies req.ACSEndpoint.Location into form.URL, and WriteResponse places it in the action attribute of an auto-submitted form.
It is worth being clear about why the usual defence did not catch it. Template engines escape characters that could break out of an HTML attribute, and that is a good defence against many XSS bugs. But here nothing needs to break out. The value sits neatly inside the quotes and forms valid HTML. The danger is the meaning of the address, not its characters. The advisory recommends validating the SP attributes before using them inside the SAML response form.
What an attacker could do
If abused, the flaw allows attackers to register malicious Service Providers at the IdP and inject JavaScript in the ACS endpoint definition. That achieves Cross-Site-Scripting in the IdP context during the redirection at the end of a SAML SSO flow. Consequently, an attacker may perform any authenticated action as the victim once the victim's browser loaded the SAML IdP initiated SSO link for the malicious service provider.
In everyday terms: the attacker does not need the victim's password. They need the victim to be logged in to the IdP and to open a link. From that moment the attacker's code is inside the IdP, holding the victim's session, and can do whatever the victim could do there.
The severity is High because SP registration is commonly an unrestricted operation in IdPs, hence not requiring particular permissions or being publicly accessible to ease IdP interoperability. The advisory does not list specific affected deployments beyond that condition. The general statement is that any use of the library in which the attacker is able to register service providers could result in a stored XSS against the IdP.
The fix
The issue was fixed and merged in the master branch, and version 0.4.14 was released. CVE-2023-45683 was assigned and the official advisory published. The advisory recommends changes in the core steps involved with SP registration:
- Validate the Service Provider defined in the entity descriptor parsed by the
ParseMetadatafunction atsamlsp/fetch_metadata.go:25. Users should be able to trust the SP parsed by the function. Alternatively, adjust the documentation to warn users about the need to implement further checks. - Align the response form construction to the SAML standard. The basic IdP implementation should not serve Service Providers without preventing injections inside the resulting responses. In order to protect the IdP against Cross-Site Scripting, validate the SP attributes before using them inside the SAML response form, at
crewjam/saml/identity_provider.go:927.
In plain words: check the address when you read it, and check it again when you use it. Do not assume that because a document passed a schema check, every value inside it is safe to place in a page.
The disclosure timeline:
| Date | Event |
|---|---|
| 08/11/2023 | Issue reported to the client during an engagement |
| 09/20/2023 | Doyensec got authorization from the client to disclose the issue to the maintainers |
| 10/14/2023 | Issue fixed and merged in master branch |
| 10/14/2023 | Version 0.4.14 released |
| 10/14/2023 | CVE-2023-45683 assigned and official advisory published |
Variants to test
If you are auditing a similar library, these are the follow-up checks suggested by the advisory. Each one asks: does the dangerous value survive to the place where it is used?
- Other bindings on the same ACS element. Submit an entity descriptor whose
AssertionConsumerServiceuses a binding other than HTTP-POST or HTTPArtifact with ajavascript:location. A positive result isParseMetadatareturning the location unchanged, or the response form being built with that location inaction. - Other URI schemes. Try
data:,vbscript:and mixed-case variants such asJaVaScRiPt:in the ACSLocation. A positive result is the scheme surviving parsing and appearing in the generated form'sactionattribute. - Other endpoint types. Apply the same payload to
SingleLogoutServiceLocationandResponseLocation, and to other metadata endpoints that are later rendered into redirects or forms. A positive result is the value being reflected into an attribute or redirect target without a scheme check. - HTML-breaking characters in the location. Use quotes and angle brackets inside the
Locationvalue to see whether the template escaping holds. A positive result is a broken attribute or an injected element in the rendered form. - Registration paths that bypass
ParseMetadata. Feed the entity descriptor through any other import, upload or admin API the IdP exposes. A positive result is a stored SP whose ACS location is ajavascript:URI and which is later used to build a response form. - IdP-initiated flow. Load the IdP-initiated SSO link for a malicious SP while authenticated. A positive result is script execution in the IdP origin, for example an alert box or a request carrying the victim's session.
Glossary
- ACS (Assertion Consumer Service): the address at a Service Provider where the IdP delivers the signed statement about the user.
- API: a defined way for one piece of software to ask another to do something, like a service counter with set procedures.
- Base64: a way of writing arbitrary data using ordinary letters, digits and a few symbols, so it can travel inside text such as a web form.
- Binding: in SAML, the agreed method for delivering a message, for example HTTP-POST or HTTPArtifact.
- Cookie: a small piece of data a website stores in your browser and receives back on later requests, often used to keep you logged in.
- Cross-Site Scripting (XSS): a bug that lets an attacker's code run inside another website's page, with that site's powers.
- CSRF token: a random value placed in a page so that requests forged from another site are rejected.
- CVE: a public catalogue number for a known security vulnerability, such as CVE-2023-45683.
- Entity descriptor: an XML document in which a SAML participant describes itself, including its endpoints and bindings.
- Function: a named block of code that performs one job and can be called by name.
- Go: a programming language, in which the affected library is written.
- HTML: the language of web pages, built from tags in angle brackets.
- HTTP-POST: a delivery method where data is sent in the body of a request, here via an auto-submitted form.
- HTTPArtifact: a SAML delivery method where the browser carries a short reference and the full message is fetched separately.
- IdP (Identity Provider): the central login service that checks who you are and vouches for you to other sites.
- JavaScript: the programming language that runs inside web browsers.
javascript:scheme: an address prefix that tells the browser to run the code after the colon instead of fetching a page.- Library: reusable code that programmers include in their own programs.
localStorage: a small storage area in the browser that websites can read and write.- Metadata: the XML description a SAML participant publishes about itself.
- Origin: the combination of scheme, host and port that a browser uses to decide which site a page belongs to.
- Proof of concept (PoC): a minimal program or set of steps that demonstrates a bug is real.
- SAML: a standard for single sign-on between an Identity Provider and Service Providers.
- Schema: a formal description of which tags and attributes a document may contain.
- Scheme: the part of an address before the first colon, such as
http,httpsorjavascript. - Service Provider (SP): a website that trusts an IdP's login instead of checking passwords itself.
- Single sign-on (SSO): logging in once and being accepted by many applications.
- Stored XSS: XSS where the malicious content is saved on the server and served to victims later.
- Template: a page with placeholders that get filled with values when the page is generated.
- Token: a credential, often a long random string, that proves a user is logged in.
- URI: an address string; its scheme says what kind of address it is.
- XML: a text format that labels data with tags in angle brackets.