SlideShare a Scribd company logo
The Token Menace
SSO Wars
This Photo by Unknown Author is licensed under CC BY
> whoarewe
▪ Alvaro Muñoz
Security Researcher with Micro Focus Fortify team
@Pwntester
▪ Oleksandr Mirosh
Security Researcher with Micro Focus Fortify team
@OlekMirosh
Agenda
• Introduction
• Authentication Tokens
• Delegated Authentication
• Arbitrary Constructor Invocation
• Potential attack vectors
• Dupe Key Confusion
• Windows Communication Foundation (WCF)
• Windows Identity Foundation (WIF)
• Conclusions
Introduction
This Photo by Unknown Author is licensed under CC BY
Delegated Authentication
Service Provider Identity ProviderUser Agent
1
6
Access protected resource
Redirect to SSO service
Forward Auth token
Redirect to resource
Access resource
Resource
Login into SSO service
Respond with Auth token
2 3
45
7
8
Delegated Authentication
Service Provider Identity ProviderUser Agent
1
6
Access protected resource
Redirect to SSO service
Forward Auth token
Redirect to resource
Access resource
Resource
Login into SSO service
Respond with Auth token
2 3
45
7
8
Issuer
Audience
Expire Date
Claims
Signature
Delegated Authentication
Service Provider Identity ProviderUser Agent
1
6
Access protected resource
Redirect to SSO service
Forward Auth token
Redirect to resource
Access resource
Resource
Login into SSO service
Respond with Auth token
2 3
45
7
8
Issuer
Audience
Expire Date
Claims
Signature
Potential attack vectors
Token parsing vulnerabilities
Normally before signature verification
Attack Token parsing process
Eg: CVE-2019-1083
Signature verification bypasses
The holy grail
Enable us to tamper claims in the token
Eg: CVE-2019-1006
Arbitrary Constructor
Invocation
CVE-2019-1083
This Photo by Unknown Author is licensed under CC BY
JWT token
Source: http://jwt.io
System.IdentityModel.Tokens.Jwt library
// System.IdentityModel.Tokens.X509AsymmetricSecurityKey
public override HashAlgorithm GetHashAlgorithmForSignature(string algorithm) {
...
object algorithmFromConfig = CryptoHelper.GetAlgorithmFromConfig(algorithm);
...
}
// System.IdentityModel.CryptoHelper
internal static object GetAlgorithmFromConfig(string algorithm) {
...
obj = CryptoConfig.CreateFromName(algorithm);
...
}
// System.Security.Cryptography.CryptoConfig
public static object CreateFromName(string name, params object[] args) {
...
if (type == null) {
type = Type.GetType(name, false, false);
if (type != null && !type.IsVisible) type = null;
}
...
RuntimeType runtimeType = type as RuntimeType;
...
MethodBase[] array = runtimeType.GetConstructors(BindingFlags.Instance | BindingFlags.Public |
BindingFlags.CreateInstance);
...
object obj;
RuntimeConstructorInfo runtimeConstructorInfo = Type.DefaultBinder.BindToMethod(BindingFlags.Instance |
BindingFlags.Public | BindingFlags.CreateInstance, array, ref args, null, null, null, out obj)
...
object result = runtimeConstructorInfo.Invoke(BindingFlags.Instance | BindingFlags.Public |
BindingFlags.CreateInstance, Type.DefaultBinder, args, null);
Similar code for SAML
// System.IdentityModel.SignedXml
public void StartSignatureVerification(SecurityKey verificationKey) {
string signatureMethod = this.Signature.SignedInfo.SignatureMethod;
...
using (HashAlgorithm hash = asymmetricKey.GetHashAlgorithmForSignature(signatureMethod))
...
<saml:Assertion ...>
...
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
...
</ds:SignedInfo>
<ds:SignatureValue>WNKeaE3R....SLMRLfIN/zI=</ds:SignatureValue>
...
</ds:Signature>
</saml:Assertion>
•YAY! We can call public parameterless constructor
•Doesn’t sound too exciting or does it?
•We actually control some data:
• The name of the type to be resolved
• Request’s parameters, cookies, headers, etc.
• In .NET the request is accessed through a static property. E.g.:
// System.Web.Mobile.CookielessData
public CookielessData() {
string formsCookieName = FormsAuthentication.FormsCookieName;
string text = HttpContext.Current.Request.QueryString[formsCookieName];
...
{
FormsAuthenticationTicket tOld = FormsAuthentication.Decrypt(text);
Potential Attack Vectors (1/2)
•Information Leakage
• For example: SharePoint server returns different results when Type resolution
and instantiation was successful or not. These results may enable an attacker to
collect information about available libraries and products on the target server.
•Denial of Service
• We found gadgets that trigger an Unhandled Exception. They enable an
attacker to leave SharePoint server unresponsive for a period of time.
Potential Attack Vectors (2/2)
•Arbitrary Code Execution
• We can search for a gadget that installs an insecure assembly resolver on its
static constructor
• We can then send full-qualified type name (including assembly name) which:
• Not available in the GAC, the system will fall back to resolving it using insecure
assembly resolver
• Insecure assembly resolver will load the assembly and then instantiate the type
• Downside:
• May depend on server configurations, e.g. already enabled AssemblyResolvers
• May require ability to upload malicious dll to the server ☹
// Microsoft.Exchange.Search.Fast.FastManagementClient
static FastManagementClient() {
...
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(OnAssemblyResolveEvent);
}
// Microsoft.Exchange.Search.Fast.FastManagementClient
private static Assembly OnAssemblyResolveEvent(object sender, ResolveEventArgs args) {
string name = args.Name.Split(new char[]{','})[0];
string path1 = Path.Combine(FastManagementClient.fsisInstallPath, "InstallerBin");
string path2 = Path.Combine(FastManagementClient.fsisInstallPath, "HostController");
string[] paths = new string[] {path1,path2};
for (int i = 0; i < paths.Length; i++) {
string full_path = paths[i] + Path.DirectorySeparatorChar.ToString() + name + ".dll";
if (File.Exists(full_path)) return Assembly.LoadFrom(full_path);
...
First payload: Microsoft.Exchange.Search.Fast.FastManagementClient
Second payload: ..............tmpmalicious
Demo
Exchange RCE
Dupe Key Confusion
CVE-2019-1006
This Photo by Unknown Author is licensed under CC BY
Authentication Tokens - SAML
•The Security Assertion Markup Language, SAML:
• Popular standard used in single sign-on systems
• XML-based format
• Uses XML Signature (aka XMLDSig) standard
•XMLDSig standard (RFC 3275):
• Used to provide payload security in SAML, SOAP, WS-Security, etc.
<Assertion>
<Subject> … </Subject>
<AttributeStatement>
…
</AttributeStatement>
<Signature>
<SignedInfo>
...
</SignedInfo>
<SignatureValue />
<KeyInfo>
key info elements
</KeyInfo>
</Signature>
</Assertion>
Simplified SAML Token
The data to be integrity-checked
Information how to verify signature
Signature
Key(s) used for signature calculation
Previous vulnerabilities in SAML
SAML Assertion
•XML Signature Wrapping (XSW):
• Discovered in 2012 by Juraj Somorovsky, Andreas Mayer and others
• Many implementations in different languages were affected
• The attacker needs access to a valid token
• The attacker modifies the contents of the token by injecting malicious data
without invalidating the signature
•Attacks with XML comments:
• Discovered in 2018 by Kelby Ludwig
• The attacker needs access to a valid token
• Uses XML comments to modify values without invalidating the signature
SAML Signature Verification in .NET
1.Resolve the signing key
• Obtain key from <KeyInfo /> or create it from embedded data
2.Use key to verify signature
3.Identify the signing party
• Derive SecurityToken from <KeyInfo />
4.Authenticate the signing party
• Verify trust on SecurityToken
SAML Signature Verification in .NET
1.Resolve the signing key
• Obtain key from <KeyInfo /> or create it from embedded data
2.Use key to verify signature
3.Identify the signing party
• Derive SecurityToken from <KeyInfo />
4.Authenticate the signing party
• Verify trust on SecurityToken
• System.IdentityModel.Selectors.SecurityTokenResolver
SecurityTokenResolver
•<KeyInfo/> section is processed twice by different methods!
•Premise:
• If we can get each method to return different keys, we may be able to bypass
validation
<KeyInfo>
<element/>
<element/>
</KeyInfo>
A tale of two resolvers
Key Identifier
Clause
Clause
ResolveSecurityKey(kId)
ResolveSecurityToken(kId)
Microsoft terminology
Signature verification
Authentication of signing party
1. Method A supports a key type that is not supported by Method B
2. Both methods support same key types, but in different order
3. Methods check for different subsets of keys within the <KeyInfo/> section
Possible scenarios for different key resolution
•Used in Web Services
•Eg: Exchange server
Windows Communication Foundation (WCF)
•Used in claim-aware applications
•Eg: MVC application authenticating users with ADFS or Azure Active Directory
Windows Identity Foundation (WIF)
•Uses custom configuration such as a custom resolver or custom certificate store
•Eg: SharePoint
Windows Identity Foundation (WIF) + Custom configuration
Examples of affected frameworks
Windows Communication
Foundation (WCF)
This Photo by Unknown Author is licensed under CC BY
Windows Communication Foundation (WCF)
• Framework for building service-oriented applications (SOA)
• Interaction between WCF endpoint and client is done using SOAP
envelopes (XML documents)
• WCF accepts SAML tokens as Client credentials
• May use Windows Identity Foundation (WIF) or not
• XML Signature also used for proof tokens and other usages
// System.IdentityModel.Tokens.SamlAssertion
SecurityKeyIdentifier keyIdentifier = signedXml.Signature.KeyIdentifier;
this.verificationKey = SamlSerializer.ResolveSecurityKey(keyIdentifier, outOfBandTokenResolver);
if (this.verificationKey == null) throw ...
this.signature = signedXml;
this.signingToken = SamlSerializer.ResolveSecurityToken(keyIdentifier, outOfBandTokenResolver);
Key & Token Resolution
Same <keyInfo/> block is processed twice
// System.IdentityModel.Tokens.SamlSerializer
internal static SecurityKey ResolveSecurityKey(SecurityKeyIdentifier ski, SecurityTokenResolver
tokenResolver)
{
if (ski == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ski");
if (tokenResolver != null) {
for (int i = 0; i < ski.Count; i++) {
SecurityKey result = null;
if (tokenResolver.TryResolveSecurityKey(ski[i], out result)) {
return result;
}
}
}
...
Security Key resolution – Depth First
For each <KeyInfo/> element, try ALL resolvers, until one is successful
// System.ServiceModel.Security.AggregateSecurityHeaderTokenResolver
bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key) {
...
resolved = this.tokenResolver.TryResolveSecurityKey(keyIdentifierClause, false, out key);
if (!resolved)
resolved = base.TryResolveSecurityKeyCore(keyIdentifierClause, out key);
if (!resolved)
resolved = SecurityUtils.TryCreateKeyFromIntrinsicKeyClause(keyIdentifierClause, this, out key);
Security Key resolution – Depth First
Remember, one key at a time!
// System.ServiceModel.Security.AggregateSecurityHeaderTokenResolver
override bool TryResolveTokenCore(SecurityKeyIdentifier keyIdentifier, out SecurityToken token) {
bool resolved = false;
token = null;
resolved = this.tokenResolver.TryResolveToken(keyIdentifier, false, false, out token);
if (!resolved) resolved = base.TryResolveTokenCore(keyIdentifier, out token);
if (!resolved) {
for (int i = 0; i < keyIdentifier.Count; ++i) {
if (this.TryResolveTokenFromIntrinsicKeyClause(keyIdentifier[i], out token)) {
resolved = true;
break;
}
Token resolution – Breadth First
Remember, ALL keys are passed here!
For each token resolver, try ALL <keyInfo/> elements, until one is successful
<KeyInfo>
<attacker symmetric Key/>
<expected key identifier/>
</KeyInfo>
Dupe Key Confusion
ResolveSecurityKey(KeyInfo)
ResolveSecurityToken(KeyInfo)
Symmetric Key
Expected X509 Cert
Signature verification
Authentication of signing party
1. Modify token at will or create token from scratch
2. Sign SAML assertion with attacker’s symmetric key
3. Include symmetric key as first element in <KeyInfo/>
4. Include original certificate as second element in <KeyInfo/>
Dupe Key Confusion
<ds:KeyInfo>
<trust:BinarySecret >rV4k60..Oww==</trust:BinarySecret>
<ds:X509Data>
<ds:X509Certificate>MIIDBTCCAe2gAw….rzCf6zzzWh</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
Injected Key
Original Cert
Demo
Exchange Account Takeover
Windows Identity
Foundation (WIF)
This Photo by Unknown Author is licensed under CC BY
WIF in a Nutshell
• WIF 4.5 is a framework for building identity-aware applications.
• Applications can use WIF to process tokens issued from STSs (eg: AD
FS, Azure AD, ACS, etc.) and make identity-based decisions
Security Token
Service
Application
WIF
Auth
Token
User Identity
Key and Token resolutions
• Key resolution is only attempted with first Key Identifier!
• Security Token resolution is attempted for all Key Identifiers
foreach (SecurityKeyIdentifierClause securityKeyIdentifierClause in keyIdentifier) {
…
}
if (!tokenResolver.TryResolveSecurityKey(_signedXml.Signature.KeyIdentifier[0], out
key)) {
...
}
Key and Token resolutions
• Uses System.IdentityModel.Tokens.IssuerTokenResolver
• Secure resolver: It handles key and security token resolution in the same way
• Falls back to X509CertificateStoreTokenResolver in case of a miss
• ResolveSecurityKey() supports EncryptedKeyIdentifierClause
• ResolveToken() only knows about resolving X509 certificates
Attack limitations
• Symmetric key is decrypted using Private key from certificate stored in
specific storage
• By default this storage is LocalMachine/Trusted People
• Attacker needs to obtain public key of such certificate
• Perhaps used for server SSL?
<KeyInfo>
<attacker encrypted key/>
<expected key identifier />
</KeyInfo>
Dupe Key Confusion
ResolveSecurityKey(KeyInfo)
ResolveSecurityToken(KeyInfo)
1. Re-Sign SAML assertion with attacker’s symmetric key
2. Encrypt symmetric key using public key from server certificate
3. Include encrypted symmetric key as first element in <KeyInfo/>
4. Include original certificate as second element in <KeyInfo/>
Symmetric Key
Expected X509 Cert
Signature verification
Authentication of signing party
X509
Certificate
StorePublic Key Private Key
<ds:KeyInfo>
<xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
<xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:X509Data>
<ds:X509Certificate>….</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
<xenc:CipherData>
<xenc:CipherValue>e++….</xenc:CipherValue>
</xenc:CipherData>
</xenc:EncryptedKey>
<ds:X509Data>
<ds:X509Certificate>MIIDBTCCAe...f6zzzWh</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
Dupe Key Confusion
Injected Key
Original Cert
SharePoint Server (WIF)
This Photo by Unknown Author is licensed under CC BY
SharePoint (WIF + Custom resolver)
•SharePoint uses WIF to process tokens and create user identities
•However, it uses a custom security token resolver:
• Microsoft.SharePoint.IdentityModel.SPIssuerTokenResolver
•Key resolution supports Intrinsic keys (eg: RSA Key, BinarySecret, …)
•Token resolution does not know how to resolve Intrinsic keys
Dupe Key Confusion
ResolveSecurityKey(KeyInfo)
ResolveSecurityToken(KeyInfo)
1. Modify token at will or create token from scratch
2. Sign SAML assertion with attacker’s own private RSA key
3. Include attacker’s RSA public key as first element in <KeyInfo/>
4. Include original certificate as second element in <KeyInfo/>
<KeyInfo>
<attacker RSA Key/>
<expected key identifier />
</KeyInfo>
RSA Key
Expected X509 Cert
Signature verification
Authentication of signing party
Dupe Key Confusion
<ds:KeyInfo>
<ds:KeyValue>
<ds:RSAKeyValue>
<ds:Modulus>irXhaxafoUZ...77kw==</ds:Modulus>
<ds:Exponent>AQAB</ds:Exponent>
</ds:RSAKeyValue>
</ds:KeyValue>
<ds:X509Data>
<ds:X509Certificate>MIIDBTCCAe2...zzWh</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
Injected Key
Original Cert
SharePoint Authentication Flow
User Agent Sharepoint STSSharepoint
Send IdP Token
Respond with FedAuth cookie
Request Session Token
Respond with Session token
Validate token (SP issuer resolver)
Validate token
(WIF token resolver)
Cache Session
Token
1 2
3 4
5
67
• Issuer: IdP
• Victim UPN
SharePoint Attack Flow
User Agent Sharepoint
Send Malicious Token to
WS
Invalid FedAuth cookie Poison Session Token Cache
Validate token (SP issuer resolver)
Authenticate with attacker account
Send original FedAuth cookie to authenticate as victim
Issued by SharePoint so no STS
exchange is needed
Gets a valid FedAuth cookie
Original FedAuth cookie now
points to poisoned Session
Token
1 2
34
• Issuer: SharePoint
• Victim UPN
• Attacker cache key
Demo
Privilege escalation on SharePoint
Burp Plugin
This Photo by Unknown Author is licensed under CC BY
https://github.com/pwntester/DupeKeyInjector
Conclusions & Takeaways
This Photo by Unknown Author is licensed under CC BY
Conclusions
• Even if protocols are considered secure, the devil is in the
implementations
• Processing same data with inconsistent code may lead to
vulnerabilities
• Here be dragons:
• Research focused on .NET, similar flaws can exist in other languages
• Even in .NET, XML Signature is used in other potentially insecure places
• Patch ASAP :)
Questions?
This Photo by Unknown Author is licensed under CC BY
@Pwntester
@OlekMirosh

More Related Content

DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menace

  • 1. The Token Menace SSO Wars This Photo by Unknown Author is licensed under CC BY
  • 2. > whoarewe ▪ Alvaro Muñoz Security Researcher with Micro Focus Fortify team @Pwntester ▪ Oleksandr Mirosh Security Researcher with Micro Focus Fortify team @OlekMirosh
  • 3. Agenda • Introduction • Authentication Tokens • Delegated Authentication • Arbitrary Constructor Invocation • Potential attack vectors • Dupe Key Confusion • Windows Communication Foundation (WCF) • Windows Identity Foundation (WIF) • Conclusions
  • 4. Introduction This Photo by Unknown Author is licensed under CC BY
  • 5. Delegated Authentication Service Provider Identity ProviderUser Agent 1 6 Access protected resource Redirect to SSO service Forward Auth token Redirect to resource Access resource Resource Login into SSO service Respond with Auth token 2 3 45 7 8
  • 6. Delegated Authentication Service Provider Identity ProviderUser Agent 1 6 Access protected resource Redirect to SSO service Forward Auth token Redirect to resource Access resource Resource Login into SSO service Respond with Auth token 2 3 45 7 8 Issuer Audience Expire Date Claims Signature
  • 7. Delegated Authentication Service Provider Identity ProviderUser Agent 1 6 Access protected resource Redirect to SSO service Forward Auth token Redirect to resource Access resource Resource Login into SSO service Respond with Auth token 2 3 45 7 8 Issuer Audience Expire Date Claims Signature
  • 8. Potential attack vectors Token parsing vulnerabilities Normally before signature verification Attack Token parsing process Eg: CVE-2019-1083 Signature verification bypasses The holy grail Enable us to tamper claims in the token Eg: CVE-2019-1006
  • 9. Arbitrary Constructor Invocation CVE-2019-1083 This Photo by Unknown Author is licensed under CC BY
  • 11. System.IdentityModel.Tokens.Jwt library // System.IdentityModel.Tokens.X509AsymmetricSecurityKey public override HashAlgorithm GetHashAlgorithmForSignature(string algorithm) { ... object algorithmFromConfig = CryptoHelper.GetAlgorithmFromConfig(algorithm); ... } // System.IdentityModel.CryptoHelper internal static object GetAlgorithmFromConfig(string algorithm) { ... obj = CryptoConfig.CreateFromName(algorithm); ... }
  • 12. // System.Security.Cryptography.CryptoConfig public static object CreateFromName(string name, params object[] args) { ... if (type == null) { type = Type.GetType(name, false, false); if (type != null && !type.IsVisible) type = null; } ... RuntimeType runtimeType = type as RuntimeType; ... MethodBase[] array = runtimeType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance); ... object obj; RuntimeConstructorInfo runtimeConstructorInfo = Type.DefaultBinder.BindToMethod(BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, array, ref args, null, null, null, out obj) ... object result = runtimeConstructorInfo.Invoke(BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, Type.DefaultBinder, args, null);
  • 13. Similar code for SAML // System.IdentityModel.SignedXml public void StartSignatureVerification(SecurityKey verificationKey) { string signatureMethod = this.Signature.SignedInfo.SignatureMethod; ... using (HashAlgorithm hash = asymmetricKey.GetHashAlgorithmForSignature(signatureMethod)) ... <saml:Assertion ...> ... <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:SignedInfo> <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> ... </ds:SignedInfo> <ds:SignatureValue>WNKeaE3R....SLMRLfIN/zI=</ds:SignatureValue> ... </ds:Signature> </saml:Assertion>
  • 14. •YAY! We can call public parameterless constructor •Doesn’t sound too exciting or does it? •We actually control some data: • The name of the type to be resolved • Request’s parameters, cookies, headers, etc. • In .NET the request is accessed through a static property. E.g.: // System.Web.Mobile.CookielessData public CookielessData() { string formsCookieName = FormsAuthentication.FormsCookieName; string text = HttpContext.Current.Request.QueryString[formsCookieName]; ... { FormsAuthenticationTicket tOld = FormsAuthentication.Decrypt(text);
  • 15. Potential Attack Vectors (1/2) •Information Leakage • For example: SharePoint server returns different results when Type resolution and instantiation was successful or not. These results may enable an attacker to collect information about available libraries and products on the target server. •Denial of Service • We found gadgets that trigger an Unhandled Exception. They enable an attacker to leave SharePoint server unresponsive for a period of time.
  • 16. Potential Attack Vectors (2/2) •Arbitrary Code Execution • We can search for a gadget that installs an insecure assembly resolver on its static constructor • We can then send full-qualified type name (including assembly name) which: • Not available in the GAC, the system will fall back to resolving it using insecure assembly resolver • Insecure assembly resolver will load the assembly and then instantiate the type • Downside: • May depend on server configurations, e.g. already enabled AssemblyResolvers • May require ability to upload malicious dll to the server ☹
  • 17. // Microsoft.Exchange.Search.Fast.FastManagementClient static FastManagementClient() { ... AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(OnAssemblyResolveEvent); } // Microsoft.Exchange.Search.Fast.FastManagementClient private static Assembly OnAssemblyResolveEvent(object sender, ResolveEventArgs args) { string name = args.Name.Split(new char[]{','})[0]; string path1 = Path.Combine(FastManagementClient.fsisInstallPath, "InstallerBin"); string path2 = Path.Combine(FastManagementClient.fsisInstallPath, "HostController"); string[] paths = new string[] {path1,path2}; for (int i = 0; i < paths.Length; i++) { string full_path = paths[i] + Path.DirectorySeparatorChar.ToString() + name + ".dll"; if (File.Exists(full_path)) return Assembly.LoadFrom(full_path); ... First payload: Microsoft.Exchange.Search.Fast.FastManagementClient Second payload: ..............tmpmalicious
  • 19. Dupe Key Confusion CVE-2019-1006 This Photo by Unknown Author is licensed under CC BY
  • 20. Authentication Tokens - SAML •The Security Assertion Markup Language, SAML: • Popular standard used in single sign-on systems • XML-based format • Uses XML Signature (aka XMLDSig) standard •XMLDSig standard (RFC 3275): • Used to provide payload security in SAML, SOAP, WS-Security, etc.
  • 21. <Assertion> <Subject> … </Subject> <AttributeStatement> … </AttributeStatement> <Signature> <SignedInfo> ... </SignedInfo> <SignatureValue /> <KeyInfo> key info elements </KeyInfo> </Signature> </Assertion> Simplified SAML Token The data to be integrity-checked Information how to verify signature Signature Key(s) used for signature calculation
  • 22. Previous vulnerabilities in SAML SAML Assertion •XML Signature Wrapping (XSW): • Discovered in 2012 by Juraj Somorovsky, Andreas Mayer and others • Many implementations in different languages were affected • The attacker needs access to a valid token • The attacker modifies the contents of the token by injecting malicious data without invalidating the signature •Attacks with XML comments: • Discovered in 2018 by Kelby Ludwig • The attacker needs access to a valid token • Uses XML comments to modify values without invalidating the signature
  • 23. SAML Signature Verification in .NET 1.Resolve the signing key • Obtain key from <KeyInfo /> or create it from embedded data 2.Use key to verify signature 3.Identify the signing party • Derive SecurityToken from <KeyInfo /> 4.Authenticate the signing party • Verify trust on SecurityToken
  • 24. SAML Signature Verification in .NET 1.Resolve the signing key • Obtain key from <KeyInfo /> or create it from embedded data 2.Use key to verify signature 3.Identify the signing party • Derive SecurityToken from <KeyInfo /> 4.Authenticate the signing party • Verify trust on SecurityToken
  • 26. •<KeyInfo/> section is processed twice by different methods! •Premise: • If we can get each method to return different keys, we may be able to bypass validation <KeyInfo> <element/> <element/> </KeyInfo> A tale of two resolvers Key Identifier Clause Clause ResolveSecurityKey(kId) ResolveSecurityToken(kId) Microsoft terminology Signature verification Authentication of signing party
  • 27. 1. Method A supports a key type that is not supported by Method B 2. Both methods support same key types, but in different order 3. Methods check for different subsets of keys within the <KeyInfo/> section Possible scenarios for different key resolution
  • 28. •Used in Web Services •Eg: Exchange server Windows Communication Foundation (WCF) •Used in claim-aware applications •Eg: MVC application authenticating users with ADFS or Azure Active Directory Windows Identity Foundation (WIF) •Uses custom configuration such as a custom resolver or custom certificate store •Eg: SharePoint Windows Identity Foundation (WIF) + Custom configuration Examples of affected frameworks
  • 29. Windows Communication Foundation (WCF) This Photo by Unknown Author is licensed under CC BY
  • 30. Windows Communication Foundation (WCF) • Framework for building service-oriented applications (SOA) • Interaction between WCF endpoint and client is done using SOAP envelopes (XML documents) • WCF accepts SAML tokens as Client credentials • May use Windows Identity Foundation (WIF) or not • XML Signature also used for proof tokens and other usages
  • 31. // System.IdentityModel.Tokens.SamlAssertion SecurityKeyIdentifier keyIdentifier = signedXml.Signature.KeyIdentifier; this.verificationKey = SamlSerializer.ResolveSecurityKey(keyIdentifier, outOfBandTokenResolver); if (this.verificationKey == null) throw ... this.signature = signedXml; this.signingToken = SamlSerializer.ResolveSecurityToken(keyIdentifier, outOfBandTokenResolver); Key & Token Resolution Same <keyInfo/> block is processed twice
  • 32. // System.IdentityModel.Tokens.SamlSerializer internal static SecurityKey ResolveSecurityKey(SecurityKeyIdentifier ski, SecurityTokenResolver tokenResolver) { if (ski == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ski"); if (tokenResolver != null) { for (int i = 0; i < ski.Count; i++) { SecurityKey result = null; if (tokenResolver.TryResolveSecurityKey(ski[i], out result)) { return result; } } } ... Security Key resolution – Depth First For each <KeyInfo/> element, try ALL resolvers, until one is successful
  • 33. // System.ServiceModel.Security.AggregateSecurityHeaderTokenResolver bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key) { ... resolved = this.tokenResolver.TryResolveSecurityKey(keyIdentifierClause, false, out key); if (!resolved) resolved = base.TryResolveSecurityKeyCore(keyIdentifierClause, out key); if (!resolved) resolved = SecurityUtils.TryCreateKeyFromIntrinsicKeyClause(keyIdentifierClause, this, out key); Security Key resolution – Depth First Remember, one key at a time!
  • 34. // System.ServiceModel.Security.AggregateSecurityHeaderTokenResolver override bool TryResolveTokenCore(SecurityKeyIdentifier keyIdentifier, out SecurityToken token) { bool resolved = false; token = null; resolved = this.tokenResolver.TryResolveToken(keyIdentifier, false, false, out token); if (!resolved) resolved = base.TryResolveTokenCore(keyIdentifier, out token); if (!resolved) { for (int i = 0; i < keyIdentifier.Count; ++i) { if (this.TryResolveTokenFromIntrinsicKeyClause(keyIdentifier[i], out token)) { resolved = true; break; } Token resolution – Breadth First Remember, ALL keys are passed here! For each token resolver, try ALL <keyInfo/> elements, until one is successful
  • 35. <KeyInfo> <attacker symmetric Key/> <expected key identifier/> </KeyInfo> Dupe Key Confusion ResolveSecurityKey(KeyInfo) ResolveSecurityToken(KeyInfo) Symmetric Key Expected X509 Cert Signature verification Authentication of signing party 1. Modify token at will or create token from scratch 2. Sign SAML assertion with attacker’s symmetric key 3. Include symmetric key as first element in <KeyInfo/> 4. Include original certificate as second element in <KeyInfo/>
  • 36. Dupe Key Confusion <ds:KeyInfo> <trust:BinarySecret >rV4k60..Oww==</trust:BinarySecret> <ds:X509Data> <ds:X509Certificate>MIIDBTCCAe2gAw….rzCf6zzzWh</ds:X509Certificate> </ds:X509Data> </ds:KeyInfo> Injected Key Original Cert
  • 38. Windows Identity Foundation (WIF) This Photo by Unknown Author is licensed under CC BY
  • 39. WIF in a Nutshell • WIF 4.5 is a framework for building identity-aware applications. • Applications can use WIF to process tokens issued from STSs (eg: AD FS, Azure AD, ACS, etc.) and make identity-based decisions Security Token Service Application WIF Auth Token User Identity
  • 40. Key and Token resolutions • Key resolution is only attempted with first Key Identifier! • Security Token resolution is attempted for all Key Identifiers foreach (SecurityKeyIdentifierClause securityKeyIdentifierClause in keyIdentifier) { … } if (!tokenResolver.TryResolveSecurityKey(_signedXml.Signature.KeyIdentifier[0], out key)) { ... }
  • 41. Key and Token resolutions • Uses System.IdentityModel.Tokens.IssuerTokenResolver • Secure resolver: It handles key and security token resolution in the same way • Falls back to X509CertificateStoreTokenResolver in case of a miss • ResolveSecurityKey() supports EncryptedKeyIdentifierClause • ResolveToken() only knows about resolving X509 certificates
  • 42. Attack limitations • Symmetric key is decrypted using Private key from certificate stored in specific storage • By default this storage is LocalMachine/Trusted People • Attacker needs to obtain public key of such certificate • Perhaps used for server SSL?
  • 43. <KeyInfo> <attacker encrypted key/> <expected key identifier /> </KeyInfo> Dupe Key Confusion ResolveSecurityKey(KeyInfo) ResolveSecurityToken(KeyInfo) 1. Re-Sign SAML assertion with attacker’s symmetric key 2. Encrypt symmetric key using public key from server certificate 3. Include encrypted symmetric key as first element in <KeyInfo/> 4. Include original certificate as second element in <KeyInfo/> Symmetric Key Expected X509 Cert Signature verification Authentication of signing party X509 Certificate StorePublic Key Private Key
  • 44. <ds:KeyInfo> <xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"> <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/> <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:X509Data> <ds:X509Certificate>….</ds:X509Certificate> </ds:X509Data> </ds:KeyInfo> <xenc:CipherData> <xenc:CipherValue>e++….</xenc:CipherValue> </xenc:CipherData> </xenc:EncryptedKey> <ds:X509Data> <ds:X509Certificate>MIIDBTCCAe...f6zzzWh</ds:X509Certificate> </ds:X509Data> </ds:KeyInfo> Dupe Key Confusion Injected Key Original Cert
  • 45. SharePoint Server (WIF) This Photo by Unknown Author is licensed under CC BY
  • 46. SharePoint (WIF + Custom resolver) •SharePoint uses WIF to process tokens and create user identities •However, it uses a custom security token resolver: • Microsoft.SharePoint.IdentityModel.SPIssuerTokenResolver •Key resolution supports Intrinsic keys (eg: RSA Key, BinarySecret, …) •Token resolution does not know how to resolve Intrinsic keys
  • 47. Dupe Key Confusion ResolveSecurityKey(KeyInfo) ResolveSecurityToken(KeyInfo) 1. Modify token at will or create token from scratch 2. Sign SAML assertion with attacker’s own private RSA key 3. Include attacker’s RSA public key as first element in <KeyInfo/> 4. Include original certificate as second element in <KeyInfo/> <KeyInfo> <attacker RSA Key/> <expected key identifier /> </KeyInfo> RSA Key Expected X509 Cert Signature verification Authentication of signing party
  • 49. SharePoint Authentication Flow User Agent Sharepoint STSSharepoint Send IdP Token Respond with FedAuth cookie Request Session Token Respond with Session token Validate token (SP issuer resolver) Validate token (WIF token resolver) Cache Session Token 1 2 3 4 5 67 • Issuer: IdP • Victim UPN
  • 50. SharePoint Attack Flow User Agent Sharepoint Send Malicious Token to WS Invalid FedAuth cookie Poison Session Token Cache Validate token (SP issuer resolver) Authenticate with attacker account Send original FedAuth cookie to authenticate as victim Issued by SharePoint so no STS exchange is needed Gets a valid FedAuth cookie Original FedAuth cookie now points to poisoned Session Token 1 2 34 • Issuer: SharePoint • Victim UPN • Attacker cache key
  • 52. Burp Plugin This Photo by Unknown Author is licensed under CC BY
  • 54. Conclusions & Takeaways This Photo by Unknown Author is licensed under CC BY
  • 55. Conclusions • Even if protocols are considered secure, the devil is in the implementations • Processing same data with inconsistent code may lead to vulnerabilities • Here be dragons: • Research focused on .NET, similar flaws can exist in other languages • Even in .NET, XML Signature is used in other potentially insecure places • Patch ASAP :)
  • 56. Questions? This Photo by Unknown Author is licensed under CC BY @Pwntester @OlekMirosh