SAML Concept and Security - rinku191/AppSec_Topics_for_Interview GitHub Wiki
SAML (Security Assertion Markup Language) is an open standard used for secure authentication and authorization. It enables Single Sign-On (SSO) by allowing one system (the Identity Provider) to securely share user identity and access rights with another system (the Service Provider).
- User (Client): The person trying to access a service (e.g., employee logging into a corporate app).
- Service Provider (SP): The system or application the user wants to access (e.g., Salesforce, Gmail).
- Identity Provider (IdP): The system that verifies the user’s identity (e.g., Okta, OneLogin).
- SAML Assertion: The XML-based token containing user authentication and authorization data.
-
User Requests Access:
- The user tries to log in to the Service Provider (SP).
- If the user is not authenticated, the SP redirects them to the Identity Provider (IdP).
-
Authentication at IdP:
- The IdP prompts the user for credentials (e.g., username/password, MFA).
- Once validated, the IdP generates a SAML Assertion.
-
SAML Assertion Sent to SP:
- The IdP sends the SAML Assertion to the user's browser.
- The user’s browser forwards this assertion to the SP.
-
SP Validates Assertion:
- The SP verifies the assertion (using the IdP’s public key).
- If valid, the SP grants the user access.
-
Single Sign-On (SSO):
- Users can access multiple applications with a single login.
-
Improved Security:
- Reduces password fatigue and phishing risks by centralizing authentication.
-
Interoperability:
- Works across platforms, organizations, and technology stacks.
-
Enhanced User Experience:
- Eliminates the need for repeated logins across applications.
- A user logs into Salesforce (SP) using their Okta credentials (IdP).
- The IdP authenticates the user and sends a SAML Assertion to Salesforce.
- Salesforce validates the assertion and grants access.
| Feature | SAML | OAuth | OpenID Connect (OIDC) |
|---|---|---|---|
| Purpose | SSO and federated identity | Delegated access | Authentication with OAuth support |
| Use Case | Enterprise apps (e.g., HR portals) | API access (e.g., 3rd-party apps) | Modern web and mobile apps |
| Token Type | XML-based SAML Assertion | JSON-based access token | JSON Web Token (JWT) |
Vulnerabilities in SAML
1. XML Signature Wrapping
The Issue: SAML messages are digitally signed to ensure integrity. But, attackers can sometimes exploit flexibility in XML parsing to reorder elements or insert unsigned content without breaking the signature. This can lead to impersonation or unauthorized attribute changes.
Example: Imagine the Assertion contains user. An attacker might wrap this in a new, unsigned element admin. A poorly coded SP might process the last role value it finds, granting admin rights.
2. XML External Entity (XXE) Injection
The Issue: If the IdP or SP's XML parser is outdated/misconfigured, it may allow external entity references within SAML messages. This can lead to reading server-side files, making SSRF-like requests, or even, in severe cases, executing code.
Example: Attacker injects ]> into the SAMLRequest. If the IdP's parser expands this, the xxe entity will contain the file's content, potentially leaked in the response.
3. Insecure RelayState Handling
The Issue: RelayState is meant to store the URL the user was originally trying to access before being sent to the IdP. If the SP blindly uses this upon return, an attacker can set it to a malicious site, leading to open redirect or phishing.
Example: Attacker crafts a SAMLRequest with RelayState=http://evil.com. If the SP doesn't validate this, the user gets sent there after login, potentially tricked into giving credentials again.
4. Improper Attribute Handling
The Issue: The IdP sends attributes (user data) in the Assertion. If the SP directly uses these without sanitization in its output, it's a classic injection risk, most commonly leading to XSS.
Example: Assertion has alert('XSS'). If the SP naively puts this into the page, the script executes.
5. Session Management Issues
The Issue: Both IdP and SP have sessions. If these aren't managed securely (e.g., predictable IDs, no timeout), attacks like session fixation or hijacking are possible, letting the attacker take over the user's access.
6. Logout Functionality Flaws
The Issue: SAML has logout requests, but if not implemented correctly on both sides, sessions might remain active. This can lead to someone else using the same browser later inadvertently logging in as the previous user.
These are just a few examples. The key is that SAML, while robust, relies on proper implementation and secure configurations on BOTH the IdP and SP sides. Pentesting needs to assess not just the protocol itself, but also how each party handles the data it receives.
Note: https://secops.group/xml-signature-wrapping/
- User (Client): The person trying to access a service (e.g., employee logging into a corporate app).
- Service Provider (SP): The system or application the user wants to access (e.g., Salesforce, Gmail).
- Identity Provider (IdP): The system that verifies the user’s identity (e.g., Okta, OneLogin).
- SAML Assertion: The XML-based token containing user authentication and authorization data.
-
User Requests Access:
- The user tries to log in to the Service Provider (SP).
- If the user is not authenticated, the SP redirects them to the Identity Provider (IdP).
-
Authentication at IdP:
- The IdP prompts the user for credentials (e.g., username/password, MFA).
- Once validated, the IdP generates a SAML Assertion.
-
SAML Assertion Sent to SP:
- The IdP sends the SAML Assertion to the user's browser.
- The user’s browser forwards this assertion to the SP.
-
SP Validates Assertion:
- The SP verifies the assertion (using the IdP’s public key).
- If valid, the SP grants the user access.
-
Single Sign-On (SSO):
- Users can access multiple applications with a single login.
-
Improved Security:
- Reduces password fatigue and phishing risks by centralizing authentication.
-
Interoperability:
- Works across platforms, organizations, and technology stacks.
-
Enhanced User Experience:
- Eliminates the need for repeated logins across applications.
- A user logs into Salesforce (SP) using their Okta credentials (IdP).
- The IdP authenticates the user and sends a SAML Assertion to Salesforce.
- Salesforce validates the assertion and grants access.
| Feature | SAML | OAuth | OpenID Connect (OIDC) |
|---|---|---|---|
| Purpose | SSO and federated identity | Delegated access | Authentication with OAuth support |
| Use Case | Enterprise apps (e.g., HR portals) | API access (e.g., 3rd-party apps) | Modern web and mobile apps |
| Token Type | XML-based SAML Assertion | JSON-based access token | JSON Web Token (JWT) |
SAML request payload example
OK, here's a simplified example of a SAML AuthnRequest payload (Service Provider -> Identity Provider):

- This is the main element that starts the SAML authentication request.
-
Attributes:
-
xmlns:samlp: Namespace for the SAML protocol. -
xmlns:saml: Namespace for SAML assertions. -
ID: A unique identifier for the request, used for tracking and validation. -
Version: Specifies the SAML version being used (e.g.,2.0). -
IssueInstant: The timestamp indicating when the request was generated. -
Destination: The URL of the Identity Provider (IdP) where the request is sent. -
ProtocolBinding: Specifies how the response will be returned (e.g.,HTTP-POST). -
AssertionConsumerServiceURL: The URL where the IdP should send the authentication response (usually a URL on the Service Provider).
-
- Identifies the entity making the request, typically the Service Provider (SP).
- Example:
"https://sp.example.com".
- Specifies how the NameID (user identifier) should be formatted in the SAML response.
-
Attributes:
-
Format: Defines the format for the user identifier (e.g., email address, persistent, or transient).- Example:
urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress(email address).
- Example:
-
AllowCreate: Allows the IdP to create a new identifier for the user if one doesn't exist.
-
- Requests the level of assurance for user authentication.
-
Attributes:
-
Comparison: Specifies how the requested authentication context should be compared.- Example:
"exact"(authentication must match the requested context exactly).
- Example:
-
-
Nested Element:
-
<saml:AuthnContextClassRef>: Specifies the authentication method.- Example:
urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport(username/password over HTTPS).
- Example:
-
Potential Security Considerations
-
Signature: This example lacks a digital signature. In real-world scenarios, the
AuthnRequestshould be signed by the SP for integrity and authenticity. -
AssertionConsumerServiceURL: An attacker might try to manipulate this URL to redirect the SAML Response to a malicious endpoint. -
NameIDPolicy: TheAllowCreate="true"attribute might allow an attacker to create a new user account at the IdP under certain conditions.
Penetration Testing Focus
- Try modifying the
AssertionConsumerServiceURLto see if the IdP accepts it and redirects the response to a controlled endpoint. - Analyze the IdP's handling of the
NameIDPolicyto identify potential account creation vulnerabilities. - If the request is signed, attempt to bypass the signature validation or tamper with the signed content.
SAML Response

- Root element for the SAML response sent by the Identity Provider (IdP).
-
Attributes:
-
ID: A unique identifier for the response. -
IssueInstant: The timestamp when the response was generated. -
Destination: The Service Provider’s (SP) Assertion Consumer Service (ACS) URL where the response is sent. -
InResponseTo: References the ID of the SAML Authentication Request from the SP.
-
- Identifies the entity issuing the response (e.g., the IdP URL).
- Example:
"https://idp.example.com".
- Indicates the status of the authentication process.
-
Status Code:
-
"urn:oasis:names:tc:SAML:2.0:status:Success": Authentication was successful.
-
- Contains the authentication information and user identity.
Attributes:
-
ID: A unique identifier for the assertion. -
IssueInstant: Timestamp when the assertion was issued.
- Represents the user being authenticated.
-
Elements:
-
<saml:NameID>:- The user's identifier (e.g., email address).
-
Format:
"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"specifies that the identifier is an email address. - Example:
"[email protected]".
-
<saml:SubjectConfirmation>:- Ensures the assertion is valid for the intended recipient (SP).
-
Attributes:
-
Recipient: The SP’s ACS URL. -
NotOnOrAfter: Expiration time for the assertion. -
InResponseTo: Matches the request ID from the SP.
-
-
- Defines the conditions under which the assertion is valid.
-
Attributes:
-
NotBefore: The assertion is not valid before this time. -
NotOnOrAfter: The assertion expires after this time.
-
-
<saml:AudienceRestriction>:- Specifies the SP (audience) that can use this assertion.
- Example:
"https://sp.example.com".
- Contains details about the authentication event.
-
Attributes:
-
AuthnInstant: Timestamp of user authentication. -
SessionIndex: A unique session identifier for the user.
-
-
<saml:AuthnContext>:- Specifies the method used to authenticate the user.
- Example:
"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"(username/password over HTTPS).
Security Considerations
-
Signature: This example lacks a signature. The
ResponseandAssertionshould be signed by the IdP. -
NotOnOrAfter: Defines the validity period. Attackers might try to exploit clock differences or manipulate this value. -
AuthnContextClassRef: Indicates the authentication method used. Is it strong enough for the SP's requirements?
Penetration Testing Focus
- Attempt to tamper with the response and bypass signature validation (if present).
- Manipulate the
NotOnOrAftervalue to see if the SP accepts expired assertions. - Analyze the
AuthnContextClassRefto determine if a weaker authentication method was used than expected. - Explore potential XML vulnerabilities, such as XXE or signature wrapping.
How Authorization happen
In SAML, authorization is typically handled through attributes and access control policies defined on the Service Provider (SP) side.
Here's a simplified explanation of how it works:
Authentication First: SAML's primary focus is authentication (proving who the user is). This happens as explained in the data flow diagram: user logs in at the IdP, the IdP sends an Assertion back to the SP, and the SP trusts this Assertion as proof of the user's identity.
Attributes in the Assertion: Along with the identity, the IdP's Assertion can also carry attributes about the user. These are key-value pairs, often representing things like:
User's role or group memberships (e.g., "admin", "employee")
Department or organization they belong to
Specific permissions they have
Any other relevant data the SP might need for its authorization logic
SP's Access Control: The SP has its own rules about which resources or actions are allowed based on these attributes. This can be:
Simple role-based access control (RBAC): "Only 'admin' users can see this page"
More complex rule engines: "Users in 'marketing' department AND with 'edit_content' permission can modify this document"
Externalized authorization services: The SP might consult another system to make access decisions based on the SAML attributes.
Enforcement: Once the SP has validated the SAML Assertion, it evaluates its access control rules against the attributes received. Based on the outcome, it either:
Grants access to the requested resource
Denies access, potentially with an error message
Redirects to a different page or flow
Key Points:
SAML itself doesn't dictate the specific authorization logic, it just provides the mechanism to carry attributes from the IdP to the SP.
The SP has full control over how it interprets and uses those attributes to make access decisions.
This separation allows for flexibility, but also puts the onus on the SP to implement secure and robust authorization mechanisms.
in case of IDP already authenticated and user is click on one of the service provider. how saml work
If the user is already authenticated with the IDP and clicks on a link to a service provider using SAML SSO, here's how the process typically works:
Initiation at SP: The user clicks a link or button on the Service Provider's (SP) website, initiating a request to access a protected resource.
SP Redirects to IdP: Even though the user is already logged in at the IdP, the SP still needs to verify their identity and obtain authorization information. It redirects the user's browser to the IdP with an AuthnRequest. This request includes a unique ID and the SP's identifier.
IdP Checks Session: Upon receiving the AuthnRequest, the IdP checks if the user has an active, valid session. Since they're already authenticated, the IdP skips the login prompt.
IdP Generates SAML Response: The IdP generates a SAML Response, including assertions about the user's identity and attributes. This Response is digitally signed by the IdP.
Redirect Back to SP: The IdP redirects the user's browser back to the SP along with the SAML Response.
SP Validates Response: The SP receives the SAML Response and validates the signature using the IdP's public key. It then parses the assertions to verify the user's identity and attributes.
Access Granted: If the SAML Response is valid and the user's attributes meet the SP's access control policies, the SP grants the user access to the requested resource.
Key Points:
Even though the user is already authenticated at the IdP, the SP still needs to communicate with the IdP to verify the user's identity and obtain relevant authorization information.
This process ensures that the SP has up-to-date information about the user and can make informed decisions about granting access to specific resources.
The SAML Response typically has a short validity period to mitigate the risk of replay attacks. If the user's session at the IdP expires or changes, the SP will need to re-initiate the SAML flow to obtain a fresh Response.
This seamless login experience, where the user is not prompted to re-authenticate at the IDP, is one of the primary benefits of SAML SSO.
IDP & SP both session are same for the user?
No, the IDP (Identity Provider) and SP (Service Provider) sessions are not inherently the same for a user. However, they are linked through the SAML authentication process.
-
IDP Session:
- The IDP session is created when the user authenticates with the Identity Provider (e.g., logging into Okta or Google).
- The session is managed by the IDP and usually includes:
- User identity.
- Authentication validity (e.g., time-out duration).
- Details like MFA (if used).
- This session allows the user to authenticate with multiple SPs (Single Sign-On or SSO).
-
SP Session:
- The SP session is created after the Service Provider validates the SAML Assertion received from the IDP.
- This session is independent of the IDP session and is managed by the SP.
- The SP session stores information about the user's access to specific resources or applications.
Is IDP provide SAML assertion and session both the user?
Yes, the IDP (Identity Provider) provides both a SAML Assertion and maintains a session for the user, but these serve different purposes.
| Aspect | IDP Session | SP Session |
|---|---|---|
| Ownership | Managed by the Identity Provider | Managed by the Service Provider |
| Purpose | Authenticates the user for SSO | Maintains the user's state within the application |
| Session Duration | Typically longer to enable SSO across apps | Can be shorter, depending on app security policies |
| Scope | Cross-application (multiple SPs) | Specific to a single SP |
| Creation Trigger | User logs into the IDP | SP validates a SAML Assertion from the IDP |
Vulnerabilities in SAML
1. XML Signature Wrapping
The Issue: SAML messages are digitally signed to ensure integrity. But, attackers can sometimes exploit flexibility in XML parsing to reorder elements or insert unsigned content without breaking the signature. This can lead to impersonation or unauthorized attribute changes.
Example: Imagine the Assertion contains user. An attacker might wrap this in a new, unsigned element admin. A poorly coded SP might process the last role value it finds, granting admin rights.
2. XML External Entity (XXE) Injection
The Issue: If the IdP or SP's XML parser is outdated/misconfigured, it may allow external entity references within SAML messages. This can lead to reading server-side files, making SSRF-like requests, or even, in severe cases, executing code.
Example: Attacker injects ]> into the SAMLRequest. If the IdP's parser expands this, the xxe entity will contain the file's content, potentially leaked in the response.
3. Insecure RelayState Handling
The Issue: RelayState is meant to store the URL the user was originally trying to access before being sent to the IdP. If the SP blindly uses this upon return, an attacker can set it to a malicious site, leading to open redirect or phishing.
Example: Attacker crafts a SAMLRequest with RelayState=http://evil.com/. If the SP doesn't validate this, the user gets sent there after login, potentially tricked into giving credentials again.
4. Improper Attribute Handling
The Issue: The IdP sends attributes (user data) in the Assertion. If the SP directly uses these without sanitization in its output, it's a classic injection risk, most commonly leading to XSS.
Example: Assertion has alert('XSS'). If the SP naively puts this into the page, the script executes.
5. Session Management Issues
The Issue: Both IdP and SP have sessions. If these aren't managed securely (e.g., predictable IDs, no timeout), attacks like session fixation or hijacking are possible, letting the attacker take over the user's access.
6. Logout Functionality Flaws
The Issue: SAML has logout requests, but if not implemented correctly on both sides, sessions might remain active. This can lead to someone else using the same browser later inadvertently logging in as the previous user.
These are just a few examples. The key is that SAML, while robust, relies on proper implementation and secure configurations on BOTH the IdP and SP sides. Pentesting needs to assess not just the protocol itself, but also how each party handles the data it receives.
Note: https://secops.group/xml-signature-wrapping/