Api Key Exposure with Saml
How API Key Exposure Manifests in SAML
API key exposure in SAML environments creates unique attack vectors that stem from the token-based authentication flow. When SAML assertions are improperly handled, API keys can leak through multiple channels, creating persistent security vulnerabilities.
The most common SAML API key exposure occurs during the assertion exchange process. When a SAML response is processed by a service provider, the temporary session tokens or API keys generated to maintain the authenticated state can be exposed in several ways:
- URL parameters containing SAML assertions with embedded API keys
- Client-side JavaScript that logs or exposes SAML response data
- Improper session management that stores API keys in browser storage
- Debug endpoints that echo SAML assertion content
A critical SAML-specific exposure pattern involves the Artifact Resolution Service (ARS). When SAML artifacts are used instead of full assertions, the ARS endpoint often requires API keys for validation. If these keys are transmitted in plaintext or logged without proper sanitization, attackers can intercept them through network monitoring or log analysis.
Consider this vulnerable SAML implementation:
@GetMapping("/saml/acs")
public String handleSAMLResponse(@RequestParam("SAMLResponse") String samlResponse) {
// Vulnerable: SAML response logged in plaintext
logger.info("Received SAML response: " + samlResponse);
// Vulnerable: API key exposed in URL parameters
String apiKey = extractApiKeyFromSAML(samlResponse);
return "redirect:/dashboard?apiKey=" + apiKey;
}
This code exposes the API key in two ways: through server logs (where it could be accessed by anyone with log access) and through URL parameters (vulnerable to browser history, referrer headers, and server logs).
Another SAML-specific exposure occurs with metadata exchange. SAML metadata files often contain entity IDs and assertion consumer service URLs that, when improperly secured, can reveal API keys used for metadata validation:
<EntityDescriptor entityID="https://api.example.com/metadata">
<SPSSODescriptor>
<KeyDescriptor use="signing">
<KeyInfo>
<KeyName>API_KEY_1234</KeyName>
</KeyInfo>
</KeyDescriptor>
</SPSSODescriptor>
</EntityDescriptor>
While this example shows a key name rather than a functional API key, it demonstrates how SAML metadata can inadvertently expose authentication credentials if not properly managed.
SAML-Specific Detection
Detecting API key exposure in SAML environments requires specialized scanning that understands the SAML protocol's unique characteristics. Traditional API security scanners often miss SAML-specific vulnerabilities because they don't parse SAML assertions or understand the artifact resolution flow.
middleBrick's SAML-aware scanning identifies exposure through several targeted checks:
- Assertion Content Analysis: Scans SAML responses for embedded API keys, tokens, or sensitive identifiers using pattern matching and entropy analysis
- Artifact Resolution Testing: Simulates artifact resolution requests to identify API key exposure in ARS endpoints
- Metadata Security Assessment: Analyzes SAML metadata files for exposed credentials or insecure configurations
- Redirect URI Validation: Tests assertion consumer service URLs for API key leakage through URL parameters
Here's how middleBrick detects SAML API key exposure:
middlebrick scan https://idp.example.com/saml/metadata \
--saml-checks \
--api-key-patterns "API_[A-Z0-9]{8,}" \
--artifact-resolution \
--metadata-analysis
The scanner performs active testing by submitting crafted SAML requests and analyzing the responses for key exposure patterns. It specifically looks for:
- Base64-encoded SAML assertions containing API keys
- URL parameters with API keys after SAML processing
- HTTP response headers that expose session tokens
- JavaScript console logs containing SAML data
For organizations using SAML with microservices, middleBrick can scan the entire authentication chain:
{
"saml_checks": {
"assertion_analysis": {
"status": "completed",
"findings": [
{
"severity": "high",
"category": "API Key Exposure",
"description": "API key found in SAML assertion URL parameter",
"location": "https://sp.example.com/saml/acs",
"remediation": "Remove API keys from URL parameters, use secure headers instead"
}
]
}
}
}
Manual detection techniques complement automated scanning. Security teams should examine SAML logs for patterns like:
grep -E "(API_KEY|Bearer [A-Za-z0-9-_.]{10,}|sk-[a-fA-F0-9]{20,})" saml_logs/*
This command searches for common API key patterns in SAML log files, helping identify exposure points that automated scanners might miss.
SAML-Specific Remediation
Remediating API key exposure in SAML environments requires understanding both SAML's security model and API key management best practices. The goal is to eliminate exposure points while maintaining SAML's single sign-on benefits.
1. Secure Assertion Processing
The foundation of SAML security is proper assertion handling. Never log SAML responses in plaintext, and avoid exposing assertion content in client-side code:
@PostMapping("/saml/acs")
public ResponseEntity<String> handleSAMLResponse(@RequestParam("SAMLResponse") String samlResponse) {
// Parse assertion without logging sensitive content
SAMLAssertion assertion = SAMLParser.parse(samlResponse);
// Generate secure session token instead of exposing API keys
String sessionToken = secureTokenGenerator.generate();
sessionStore.createSession(sessionToken, assertion.getSubject());
// Return only the session token, not the API key
return ResponseEntity.ok()
.header("X-Session-Token", sessionToken)
.body("/dashboard");
}
2. Artifact Resolution Service Security
ARS endpoints are critical for SAML security. Implement proper authentication and rate limiting:
@PostMapping("/saml/ars")
public SAMLArtifactResponse handleArtifact(@RequestBody SAMLArtifactRequest request) {
// Validate request signature
if (!samlValidator.validate(request)) {
throw new InvalidSAMLException("Invalid signature");
}
// Authenticate using secure API key (never expose in response)
String apiKey = request.getApiKey();
if (!apiKeyService.isValid(apiKey)) {
throw new AuthenticationException("Invalid API key");
}
// Process artifact without exposing API key in logs
SAMLArtifact artifact = request.getArtifact();
SAMLAssertion assertion = artifactResolver.resolve(artifact);
return SAMLArtifactResponse.builder()
.assertion(assertion)
.build();
}
3. Metadata Security Hardening
Secure SAML metadata files by removing sensitive information and implementing access controls:
<EntityDescriptor entityID="https://sp.example.com/saml/metadata">
<SPSSODescriptor authnRequestsSigned="true" wantAssertionsSigned="true">
<KeyDescriptor use="signing">
<KeyInfo>
<X509Data>
<X509Certificate>MIIC...</X509Certificate>
</X509Data>
</KeyInfo>
</KeyDescriptor>
<AssertionConsumerService
Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
Location="https://sp.example.com/saml/acs"
index="1"
isDefault="true"/>
</SPSSODescriptor>
</EntityDescriptor>
4. Secure Redirect Handling
Never pass API keys through URL parameters in SAML redirects. Use secure headers or POST bindings instead:
@PostMapping("/saml/acs")
public String handleSAMLResponse(@RequestParam("SAMLResponse") String samlResponse,
Model model) {
// Parse and validate SAML response
SAMLAssertion assertion = SAMLParser.parse(samlResponse);
// Generate secure session token
String sessionToken = secureTokenGenerator.generate();
sessionStore.createSession(sessionToken, assertion.getSubject());
// Store API key server-side, reference by token
String apiKey = extractApiKeyFromAssertion(assertion);
apiStore.storeApiKey(sessionToken, apiKey);
// Pass only session token to client
model.addAttribute("sessionToken", sessionToken);
return "redirect:/dashboard";
}
5. Runtime Protection with middleBrick
Integrate middleBrick into your CI/CD pipeline to catch SAML API key exposure before deployment:
name: SAML Security Scan
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run middleBrick SAML Scan
run: |
npx middlebrick scan https://idp.example.com/saml/metadata \
--saml-checks \
--fail-on-high-severity \
--output json > saml-scan.json
- name: Upload Scan Results
uses: actions/upload-artifact@v3
with:
name: saml-security-scan
path: saml-scan.json
This GitHub Action runs middleBrick's SAML-specific checks on every code change, ensuring API key exposure vulnerabilities are caught early in the development lifecycle.