Skip to content
Memory corruption Write-up Advanced

Remote Deserialization Bug in Microsoft's RDP Client through Smart Card Extension (CVE-2021-38666)

The RDP client deserialises smart card extension data using the RPC NDR engine without properly validating the input buffer length or the array counts inside the serialised structure. An attacker controlling a malicious RDP server could cause out-of-bounds reads and heap corruption in the client, potentially leading to remote code execution.

Valentino Ricotta Follow

Published on thalium.github.io

Bounty$5,000 View original

This is the third installment in my three-part series of articles on fuzzing Microsoft’s RDP client, where I explain a bug I found by fuzzing the smart card extension.

Thalium Team, on thalium.github.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. 11 min read.

Context

This is the third article in a series on fuzzing Microsoft's RDP client. The target is Microsoft's official Remote Desktop Protocol client on Windows 10. The executable is mstsc.exe in system32, but most of the client logic lives in mstscax.dll.

RDP is a proprietary protocol that lets an RDP client connect to a remote computer over the network with a graphical interface. Most vulnerability research concentrates on the RDP server, but critical bugs have also been found in the client, where a compromised or malicious server attacks the client that connects to it. At Blackhat Europe 2019 a team of researchers presented an RCE in the RDP client, motivated by the idea that attackers carrying out attacks through RDP servers acting as proxies could be hacked back with a malicious RDP server.

RDP uses virtual channels as a transport layer. RDPSND carries audio redirection, CLIPRDR carries clipboard synchronisation, and each channel has its own protocol, usually documented in Microsoft's specifications. Virtual channels are a good entry point for fuzzing.

The bug described here is in RDPDR, the static virtual channel that redirects access from the server to the client file system. RDPDR is also the base channel hosting sub-extensions such as the smart card extension, the printing extension and the serial/parallel ports extension. It is opened by default in the RDP client, alongside RDPSND, CLIPRDR and DRDYNVC, which makes it interesting from a risk perspective. The channel is documented in MS-RDPEFS, which lists PDU types, their structures and dozens of example PDUs that are useful for seeding a fuzzer.

Setup

The researcher fuzzed virtual channels with a modified version of WinAFL and a network-level harness, during an internship at Thalium. No accounts, roles or specific versions beyond Windows 10 and the client binaries are described. The only precondition for the bug is that a victim client connects to a server controlled by the attacker, since the malicious data arrives over the RDPDR channel from the server side.

Fuzzing RDPDR had already yielded a few small bugs and another CVE, the ASLR leak through the printer cache registry covered in the previous article. That earlier vulnerability had no crash associated with it, so crash triage was not a given.

Finding it

The crashes appeared while fuzzing the smart card sub-protocol and were enigmatic: a lot of crashes, in many different modules, and also in mstscax.dll. There were far too many crashes at random places for all of it to make sense, so the first suspicion was that something was broken in the fuzzing setup.

RDPDR enigmatic crashes
Perplexing logs of crashes while fuzzing RDPDR From the original on thalium.github.io

The logs show the perplexing crash output from fuzzing RDPDR. One crash nevertheless recurred more frequently inside RPCRT4.DLL, which is where the investigation focused.

Exploitation

Step 1: identify the crashing instruction

The crashes in RPCRT4.DLL arise in NdrSimpleTypeConvert+0x307:

ASM
mov     eax, [rdx] ; crash
bswap   eax
mov     [rdx], eax

This is a classic out-of-bounds read on what appears to be the byteswap of a DWORD in the heap. The associated payload was found and the bug reproduces instantly.

Step 2: read the call stack

The call stack at the time of the crash looks like this:

RPC bug call stack
Call stack at time of the crash in RPCRT4.DLL From the original on thalium.github.io

Before entering RPCRT4.DLL, execution was in mstscax!W32SCard::LocateCardsByATRA. Analysing other payloads that lead to the same crash points to other functions in mstscax.dll as well:

  • W32SCard::HandleContextAndTwoStringCallWithLongReturn
  • W32SCard::WriteCache
  • W32SCard::DecodeContextAndStringCallW

All of these functions share the following snippet of code:

C
v6 = MesDecodeBufferHandleCreate(
  &PDU->InputBuffer,
  PDU->InputBufferLength,
  &pHandle
);
// ...
NdrMesTypeDecode3(
  pHandle,
  &pPicklingInfo,
  &pProxyInfo,
  (const unsigned int **)&ArrTypeOffset,
  0xEu,
  &pObject
); // Crash here

The only thing that varies across these functions is the fifth parameter of NdrMesTypeDecode3 (the 0xE). The PDU->InputBufferLength field is a DWORD and can be arbitrarily large.

Step 3: dissect the payloads

Two of the guilty payloads are Device I/O Request PDUs, more specifically of sub-type Device Control Request. The first one:

Text
rpc-crash-1

72 44 52 49 01 00 00 00 f8 01 02 00 08 00 00 00 0e 00 00 00 00 00 00 00 DeviceIoRequest
00 40 00 00 OutputBufferLength
00 80 2d 00 InputBufferLength
e8 00 09 00 IoControlCode
00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 02 00 08 00 Padding
InputBuffer
01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00
00 00 00 00 00 00 00 00 00 03 00 08 00 01 40 00
00 16 00 00 00 01 00 00 00

The second one:

Text
rpc-crash-2

72 44 52 49 01 00 00 00 f8 00 00 00 04 10 00 00 0e 00 00 00 00 00 00 00 DeviceIoRequest
00 40 00 00 OutputBufferLength
6f 63 06 00 InputBufferLength
64 00 09 00 IoControlCode
00 00 ff 00 00 00 00 40 00 20 00 66 00 00 77 66 64 63 08 00 Padding
InputBuffer
01 00 00 00 00 00 00 00 00 00 00 04 00 00 00 0e
00 00 00 00 00 00 00 00 40 00 00 6f 63 06 00 64
00 09 00 00 00 ff 00 00 00 00 40 00 00 00 00 00
00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 6c 00 00 05

Both carry an IoControlCode, an InputBufferLength and an InputBuffer. The specification describes IoControlCode as a 32-bit unsigned integer specific to the redirected device. A dedicated specification exists for the smart card sub-protocol, MS-RDPESC, and its section 3.1.4 contains a long table mapping IoControlCode values to types of IRP_MJ_DEVICE_CONTROL requests and their associated structures.

IoControlCode table
IoControlCode table From the original on thalium.github.io

Around 60 functions contain the same pattern of code using MesDecodeBufferHandleCreate followed by NdrMesTypeDecode3. They are all called the same way with the supplied InputBuffer and InputBufferLength, and only a certain offset parameter varies each time.

For IoControlCode set to 0x000900E8, the specification gives the following LocateCardsByATRA_Call structure:

C
typedef struct _LocateCardsByATRA_Call {
  REDIR_SCARDCONTEXT Context;
  [range(0,1000)] unsigned long cAtrs;
  [size_is(cAtrs)] LocateCards_ATRMask* rgAtrMasks;
  [range(0,10)] unsigned long cReaders;
  [size_is(cReaders)] ReaderStateA* rgReaderStates;
} LocateCardsByATRA_Call;

Based on IoControlCode, the input buffer is decoded according to a certain structure.

Step 4: understand the decoding engine

MesDecodeBufferHandleCreate is documented by Microsoft as creating a decoding handle and initialising it for a fixed buffer style of serialisation. RPC has its own serialisation engine, the NDR marshaling engine (Network Data Representation), with documentation on headers, format strings and types. The RDP client makes manual use of this engine to decode structures from the PDUs.

After the decoding handle is initialised with the input buffer and length, the data is deserialised with NdrMesTypeDecode3. That function is not documented, because developers are not supposed to call it directly: structures are described in Microsoft's IDL, and the MIDL compiler generates stubs that encode and decode data using the NdrMes functions underneath.

Header files still contain information about the parameters and their types.

NdrMesTypeDecode3
Interesting fields inside NdrMesTypeDecode3's arguments... (pProxyInfo) From the original on thalium.github.io

The pProxyInfo argument eventually leads to a Format field, which appears to contain a compiled description of all the types that exist and are used within the smart card extension. The ArrTypeOffset array, which starts like this: 0x02, 0x1e, 0x1e, 0x54, ..., lists the offsets of all the structures of interest inside the compiled format string. The next argument (0xE) is the offset, in the ArrTypeOffset array, of the structure to consider.

For LocateCardsByATRA, 0xE gives an offset of 0x220 in the ArrTypeOffset array, which points to the compiled format associated with the structure from the specification. The specification releases the full IDL in appendix; without it, the format would have had to be decompiled, and not only the format pointed to by the offset found, because there are also many references to other previously defined structures such as LocateCards_ATRMask.

Step 5: reconstruct the root cause

The picture so far:

  • We can send an IoControlCode, InputBuffer and InputBufferLength.
  • The InputBufferLength (DWORD) can be greater than the actual length of InputBuffer.
  • The input buffer is deserialised through the RPC NDR marshaling engine according to a structure that varies with IoControlCode.
  • There are around 60 possible IoControlCode values, and thus decoding structures.
  • There is an OOB read during deserialisation, in NdrSimpleTypeConvert.

The convert operations appeared to take place before any real decoding, as if a first pass over the whole buffer converted things. A Windows XP source leak shed light on this:

C++
void NdrSimpleTypeConvert(PMIDL_STUB_MESSAGE pStubMsg, uchar FormatChar) {
  switch (FormatChar) {
    // ...
    case FC_ULONG:
      ALIGN(pStubMsg->Buffer,3);
      CHECK_EOB_RAISE_BSD( pStubMsg->Buffer + 4 );

      if ((pStubMsg->RpcMsg->DataRepresentation & NDR_INT_REP_MASK) != NDR_LOCAL_ENDIAN) {
        *((ulong *)pStubMsg->Buffer) = RtlUlongByteSwap(*(ulong *)pStubMsg->Buffer);
      }

      pStubMsg->Buffer += 4;
      break;
    // ...
  }
}

The magic happens when the endianness of the serialised data does not match the local endianness. A pass on the buffer switches the endianness of, in particular, all the FC_ULONG type fields, the unsigned long fields in the structure.

In _LocateCardsByATRA_Call, the fields cAtrs and cReaders are byteswapped. More importantly, any unsigned long inside the nested rgAtrMasks or rgReaderStates fields is byteswapped too, and these fields are arrays of structs whose size we control.

There are two kinds of overrun:

  1. The user-supplied PDU->InputBufferLength is not properly checked, so the conversion pass in the RPC NDR deserialisation goes way beyond the end of the PDU in the heap.
  2. The user-supplied cAtrs (or cReaders) coded inside the serialised data can be large enough to make the deserialisation structure overflow the actual length of the buffer, along with the input buffer length provided.

Combined, these overruns result in an out-of-bounds read in the heap and a crash.

Step 6: explain the other crashes

The LocateCards_ATRMask structure nested inside LocateCardsByATRA_Call is:

C
typedef struct _LocateCards_ATRMask {
  [range(0, 36)] unsigned long cbAtr;
  byte rgbAtr[36];
  byte rgbMask[36];
} LocateCards_ATRMask;

There is an unsigned long field (cbAtr) at the beginning of this struct of total size 76 bytes, so DWORDs in the heap can be byteswapped every 76 bytes. Setting a breakpoint where the byteswap occurs shows the heap progressively getting disfigured.

Because PDU->InputBufferLength is arbitrarily large, the end of the heap segment can eventually be reached, causing an OOB read crash. More interestingly, if the input buffer length is large enough to allow out-of-bounds operations but small enough not to exceed the heap segment, the deserialisation process returns with a damaged heap. That produces the numerous odd crashes seen earlier:

  • Heap Corruption exceptions during heap management calls
  • Random pointers being damaged and causing access violations
  • Damaged vtable pointers causing access violations
  • Damaged vtable pointers that still successfully resolve and redirect the execution flow, crashing directly after (illegal instruction), which are the unknown module crashes found earlier

Step 7: assess exploitation

Some of these behaviours could be exploited to achieve unexpected harmful results such as remote code execution. For instance, with some heap spray one might hijack a vtable through a well-aligned byteswap and redirect the execution flow, but it seemed quite tricky and the researcher did not manage to exploit it. Other kinds of conversions could be performed, such as float conversions and EBCDIC to ASCII, but it is not certain whether they can actually be triggered.

Root cause

The client trusts two length values that come from the server. PDU->InputBufferLength is passed to MesDecodeBufferHandleCreate without being checked against the real size of InputBuffer, and the count fields cAtrs and cReaders inside the serialised data drive the size of the nested arrays. The NDR conversion pass that byteswaps FC_ULONG fields walks the buffer according to those values, so it reads and writes past the end of the PDU in the heap. The CHECK_EOB_RAISE_BSD check in NdrSimpleTypeConvert is meant to catch end-of-buffer conditions. The report does not state which specific check was missing or changed in the fix.

Impact

A malicious RDP server can send crafted RDPDR Device Control Request PDUs to a client that connects to it, causing out-of-bounds reads and heap corruption in the client process. In practice this yields crashes in many modules, and the researcher suspects it could be exploited for remote code execution, though no proof of concept was produced. Microsoft assessed the vulnerability as Remote Code Execution with Important severity and awarded a $5,000 bounty; the severity was revised to Critical when the CVE was published. The CVE is CVE-2021-38666, and the MSRC entry is titled RDP Client Information Disclosure Vulnerability, with CVSS 8.8.

Fix

Microsoft released the security patch on 2021-11-09. The report does not describe the code change itself.

Variants to test

  • Other IoControlCode values from the MS-RDPESC table: send a Device Control Request with a mismatched InputBufferLength and a buffer whose endianness differs from the local one, and watch for crashes in NdrSimpleTypeConvert or other NdrMes functions. A positive result is a crash in RPCRT4.DLL with a call stack through mstscax smart card functions.
  • Other virtual channels that use MesDecodeBufferHandleCreate and NdrMesTypeDecode3: fuzz their PDUs with declared lengths larger than the actual buffer. A positive result is an out-of-bounds read or heap corruption in the RPC runtime.
  • Structures with nested arrays whose counts are attacker-controlled: vary the count fields (cAtrs, cReaders and similar) while keeping the buffer short. A positive result is a byteswap pattern in the heap at a fixed stride, visible at a breakpoint on the byteswap.
  • Other conversion types mentioned in the report (float conversions, EBCDIC to ASCII): craft serialised data that forces those conversions and check whether they can be triggered. A positive result is a conversion pass over attacker-influenced data outside the intended buffer.
  • Heap spray followed by a well-aligned byteswap: attempt to overwrite a vtable pointer and redirect execution. A positive result is control of the instruction pointer rather than a plain access violation.

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

What happened, in plain words

Microsoft makes a program called Remote Desktop, which lets you use another computer over the internet as if you were sitting in front of it. Your computer runs a small piece of software called the client, and the computer you connect to runs the server. Normally people worry about the server being attacked, because that is the machine holding the data. This article is about the opposite direction: a malicious server attacking the client that connects to it.

A researcher spent an internship at a company called Thalium studying Microsoft's Remote Desktop client, learning how to fuzz it (throw huge amounts of slightly mutated data at it and watch for crashes), and looking for bugs. He found one in a part of the client that handles smart cards (the chip cards used for badges and secure logins). The bug makes the client read memory it should not touch, which can crash it and, the researcher suspects, could in principle let the attacker run their own code on the victim's machine. Microsoft rated it Remote Code Execution, Critical, and paid a $5,000 bounty. The bug is tracked as CVE-2021-38666.

This is the third article in a series. The first covered the overall method for fuzzing the client, the second covered a different bug that leaked memory addresses. This one is the hardest of the three to follow, so this version explains every piece from scratch.

Background: what Remote Desktop is and why the client matters

Remote Desktop Protocol (RDP) is a proprietary protocol designed by Microsoft. A protocol is simply an agreed set of rules for two programs to exchange messages, like the rules of a postal service: what an envelope looks like, where the address goes, what happens if a parcel is too big. RDP lets an RDP client connect to a remote computer over the network and see its graphical desktop.

RDP is used very widely, for example for remote work and administration. Most vulnerability research concentrates on the RDP server, because that is the valuable target. But critical vulnerabilities have also been found in the RDP client: if you can trick a victim into connecting to a server you control, that server can attack the client.

At Blackhat Europe 2019, a team of researchers presented an RCE (remote code execution, meaning running your own commands on someone else's machine) in the RDP client. Their motivation was that North Korean hackers would allegedly carry out attacks through RDP servers acting as proxies, and that you could hack them back by setting up a malicious RDP server to which they would connect.

The target here is Microsoft's official RDP client on Windows 10. The executable is mstsc.exe (in system32), but the main DLL for most of the client logic is mstscax.dll. An executable is a program file you can run; a DLL (dynamic link library) is a file full of code that programs load and share, a bit like a toolbox that several programs can open at once.

Virtual channels

RDP uses the abstraction of virtual channels, a layer for transporting data. Think of a motorway with several marked lanes: all the traffic goes the same way, but each lane carries a different kind of cargo. For instance, the channel RDPSND is used for audio redirection (playing the remote computer's sound on your speakers), and the channel CLIPRDR is used for clipboard synchronisation (copy on one machine, paste on the other).

Each channel behaves according to separate logic and its own protocol, whose official specification can often be found in Microsoft's documentation. Virtual channels are a great attack surface and a good entrypoint for fuzzing, because each channel is a separate little conversation the server can drive.

The researcher fuzzed virtual channels with a modified version of WinAFL and a network-level harness. WinAFL is a fuzzer: a tool that generates many variations of an input and feeds them to a program to see which ones make it crash. A harness is the small piece of glue code that delivers those inputs to the right place in the program, here at the network level, as if they came from a real server.

Fuzzing RDPDR, the File System Virtual Channel Extension

RDPDR is the name of the static virtual channel whose purpose is to redirect access from the server to the client file system. In plain terms: when you are connected to a remote desktop, the server can ask your local computer for files, printers and similar devices, and RDPDR is the lane that carries those requests. It is also the base channel that hosts several sub-extensions, such as the smart card extension, the printing extension and the serial/parallel ports extension.

RDPDR is one of the few channels opened by default in the RDP client, alongside the other static channels RDPSND, CLIPRDR and DRDYNVC. That makes it more interesting from a risk perspective: the attacker does not need the victim to enable anything special.

Microsoft documents this channel in a specification called MS-RDPEFS. It contains the different PDU types, their structures, and even dozens of examples of PDUs, which is great for seeding the fuzzer. A PDU (protocol data unit) is one message in the conversation, like one letter in a correspondence. Seeding means giving the fuzzer realistic starting examples so that its random mutations stay close to valid messages instead of being pure noise.

Fuzzing RDPDR yielded a few small bugs, as well as another bug for which the researcher got a CVE (the previous article's ASLR leak through the printer cache registry). The bug detailed in this article is one of the denser ones he had to deal with among his RDP findings. It was found by analysing crashes obtained during fuzzing. That may sound obvious, but it is not: the previous vulnerability had no crash associated with it at all.

Analysing crashes

The crashes happened while fuzzing the Smart Card sub-protocol, and were quite enigmatic.

RDPDR enigmatic crashes
Perplexing logs of crashes while fuzzing RDPDR From the original on thalium.github.io

The image shows the perplexing logs of crashes while fuzzing RDPDR. There were a lot of crashes, in many different modules, and also (not shown on the screenshot) in mstscax.dll. A module here means a loaded program file such as a DLL. There were far too many crashes at random places for all of this to make sense, so the first thought was that something was broken with the fuzzing setup.

One crash nevertheless seemed to reoccur more frequently inside RPCRT4.DLL. RPC (Remote Procedure Call) is a way for one program to ask another program, possibly on another machine, to run a function for it, as if calling a local function. RPCRT4.DLL is the Windows library that implements RPC. The first article had already glimpsed RPC while investigating DRDYNVC, but here it gets more serious.

Smart Cards and RPC

Step 1: the crashing instruction

The crashes in RPCRT4.DLL arise in NdrSimpleTypeConvert+0x307:

ASM
mov     eax, [rdx] ; crash
bswap   eax
mov     [rdx], eax

Line by line:

  • mov eax, [rdx] copies four bytes from the memory address held in the register rdx into the register eax. The square brackets mean "the memory at this address". This is the instruction that crashes.
  • bswap eax reverses the order of the four bytes inside eax. This is a byteswap: turning the value 01 02 03 04 into 04 03 02 01. It is how a computer converts between the two common ways of storing numbers (big-endian and little-endian).
  • mov [rdx], eax writes the swapped value back to the same memory address.

A register is a tiny, very fast storage slot inside the processor. This is a classic out-of-bounds read on what seems to be the byteswap of a DWORD in the heap. An out-of-bounds read means the program reads memory outside the area it was given, like reading past the end of a page in a book and picking up whatever is printed on the next sheet. A DWORD is a 32-bit (four-byte) integer. The heap is the region of memory a program uses for data it creates while running, as opposed to its fixed code and its stack of function calls.

Fortunately, the associated payload was found and the bug reproduces instantly. A payload here is the exact malicious message that triggers the crash.

Step 2: the call stack

Here is what the call stack looks like when the crash occurs:

RPC bug call stack
Call stack at time of the crash in RPCRT4.DLL From the original on thalium.github.io

The image shows the call stack at the time of the crash in RPCRT4.DLL. A call stack is the list of functions currently in progress, newest on top: function A called function B, which called function C, and so on. Reading it tells you the path the program took to reach the crash.

So before entering RPCRT4.DLL, execution was in mstscax!W32SCard::LocateCardsByATRA. The ! separates the module name from the function name inside it. Analysing other payloads that lead to the same crash points to other functions in mstscax.dll as well:

  • W32SCard::HandleContextAndTwoStringCallWithLongReturn
  • W32SCard::WriteCache
  • W32SCard::DecodeContextAndStringCallW

What do all these functions have in common? The following snippet of code:

C
v6 = MesDecodeBufferHandleCreate(
  &PDU->InputBuffer,
  PDU->InputBufferLength,
  &pHandle
);
// ...
NdrMesTypeDecode3(
  pHandle,
  &pPicklingInfo,
  &pProxyInfo,
  (const unsigned int **)&ArrTypeOffset,
  0xEu,
  &pObject
); // Crash here

Line by line:

  • v6 = MesDecodeBufferHandleCreate(...) calls a Windows function that prepares a decoding handle: a small object that remembers where the data is and how long it is, so that later calls can read from it. The result is stored in a variable v6.
  • &PDU->InputBuffer passes the address of the buffer inside the PDU, that is, the bytes the server sent as the message body. The & means "address of".
  • PDU->InputBufferLength passes the length the server claims the buffer has. This is a number supplied by the attacker.
  • &pHandle receives the handle that was just created.
  • // ... marks code omitted for brevity.
  • NdrMesTypeDecode3(...) is the call that actually deserialises the data. Deserialisation is turning a flat sequence of bytes back into structured data, like unpacking a flat-pack furniture box into a table. The comment // Crash here marks where the crash happens.
  • pHandle is the handle from before.
  • &pPicklingInfo and &pProxyInfo are pointers to internal description tables. Pickling is Microsoft's word for serialising data into a flat form.
  • (const unsigned int **)&ArrTypeOffset passes the address of an array of offsets, which says where each structure's description lives.
  • 0xEu is the number 14 written in hexadecimal (base 16). It selects which entry of that array to use, that is, which structure to decode.
  • &pObject receives the decoded object.

The only thing that varies across these functions is the fifth parameter of NdrMesTypeDecode3 (the 0xE). It is also immediately noticeable that PDU->InputBufferLength (a DWORD) can be arbitrarily large, because the server chooses it.

Step 3: dissecting the payloads

Two of the guilty payloads are Device I/O Request PDUs, more specifically of sub-type Device Control Request. A Device I/O Request is a message asking the client to perform an input/output operation on a redirected device, such as a smart card reader. The first one:

Text
rpc-crash-1

72 44 52 49 01 00 00 00 f8 01 02 00 08 00 00 00 0e 00 00 00 00 00 00 00 DeviceIoRequest
00 40 00 00 OutputBufferLength
00 80 2d 00 InputBufferLength
e8 00 09 00 IoControlCode
00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 02 00 08 00 Padding
InputBuffer
01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00
00 00 00 00 00 00 00 00 00 03 00 08 00 01 40 00
00 16 00 00 00 01 00 00 00

This is a hex dump: each pair of characters is one byte, written in hexadecimal. The labels on the right name the fields. The first line is the header of the Device I/O Request. The next lines give OutputBufferLength (how much room the client should reserve for a reply), InputBufferLength (how long the incoming data claims to be), IoControlCode (which operation is requested), some Padding, and then the InputBuffer itself, the actual data.

The second one:

Text
rpc-crash-2

72 44 52 49 01 00 00 00 f8 00 00 00 04 10 00 00 0e 00 00 00 00 00 00 00 DeviceIoRequest
00 40 00 00 OutputBufferLength
6f 63 06 00 InputBufferLength
64 00 09 00 IoControlCode
00 00 ff 00 00 00 00 40 00 20 00 66 00 00 77 66 64 63 08 00 Padding
InputBuffer
01 00 00 00 00 00 00 00 00 00 00 04 00 00 00 0e
00 00 00 00 00 00 00 00 40 00 00 6f 63 06 00 64
00 09 00 00 00 ff 00 00 00 00 40 00 00 00 00 00
00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 6c 00 00 05

Same layout, different values. Both carry an IoControlCode, an InputBufferLength and an InputBuffer. The first article already met one of these PDUs, in the arbitrary malloc bug.

What is this IoControlCode field exactly? According to the specification:

IoControlCode (4 bytes): A 32-bit unsigned integer. This field is specific to the redirected device.

Specific to the redirected device. For some reason it took a long time to realise there was actually a dedicated specification for the Smart Card sub-protocol (as well as the others), called MS-RDPESC.

Section 3.1.4 of the Smart Card specification answers the suspicion. It contains a long table that maps IoControlCode values with types of IRP_MJ_DEVICE_CONTROL requests and associated structures. An IRP is an I/O request packet, the internal Windows object representing a request to a device driver; IRP_MJ_DEVICE_CONTROL is the kind used for device control operations.

IoControlCode table
IoControlCode table From the original on thalium.github.io

The image shows the table of IoControlCode values from the specification. Therefore, there are around 60 functions that contain the same pattern of code using MesDecodeBufferHandleCreate followed by NdrMesTypeDecode3. They are all called the same way with the supplied InputBuffer and InputBufferLength, and only a certain offset parameter varies each time.

According to the specification, for IoControlCode set to 0x000900E8, we get the following LocateCardsByATRA_Call structure:

C
typedef struct _LocateCardsByATRA_Call {
  REDIR_SCARDCONTEXT Context;
  [range(0,1000)] unsigned long cAtrs;
  [size_is(cAtrs)] LocateCards_ATRMask* rgAtrMasks;
  [range(0,10)] unsigned long cReaders;
  [size_is(cReaders)] ReaderStateA* rgReaderStates;
} LocateCardsByATRA_Call;

Line by line:

  • typedef struct _LocateCardsByATRA_Call { starts the definition of a structure: a named bundle of fields, like a form with several boxes. typedef gives the bundle a name you can use later.
  • REDIR_SCARDCONTEXT Context; is a field holding a smart card context, an identifier for a session with the card subsystem.
  • [range(0,1000)] unsigned long cAtrs; is a count of ATR masks. The [range(0,1000)] annotation says the value is supposed to be between 0 and 1000. An ATR (Answer To Reset) is the short byte sequence a smart card sends when it is powered up, identifying it.
  • [size_is(cAtrs)] LocateCards_ATRMask* rgAtrMasks; is a pointer to an array of ATR masks, whose length is given by cAtrs. The [size_is(...)] annotation ties the array length to that count field. A pointer is a number that says where in memory something lives.
  • [range(0,10)] unsigned long cReaders; is a count of readers, supposed to be between 0 and 10.
  • [size_is(cReaders)] ReaderStateA* rgReaderStates; is a pointer to an array of reader states, whose length is given by cReaders.
  • } LocateCardsByATRA_Call; closes the definition.

It seems then that based on IoControlCode, the input buffer will be decoded according to a certain structure. In other words, the server picks a number, and the client picks a form to fill in from the bytes that follow.

Step 4: the RPC NDR marshaling engine

Back to the decoding piece of code:

C
v6 = MesDecodeBufferHandleCreate(
  &PDU->InputBuffer,
  PDU->InputBufferLength,
  &pHandle
);

This function from RPCRT4 is documented by Microsoft:

The MesDecodeBufferHandleCreate function creates a decoding handle and initializes it for a (fixed) buffer style of serialisation.

So this is what it is all about. RPC has its own serialisation engine, called the NDR marshaling engine (Network Data Representation). Marshaling is the process of packing function arguments or structures into a flat byte stream so they can be sent over a network, and unmarshaling (or decoding) is the reverse. There is documentation on how data serialisation works: header, format strings, types, and so on.

The RDP client makes "manual" use of the RPC NDR serialisation engine to decode structures from the PDUs. "Manual" means it calls the low-level functions itself instead of using generated helper code.

After the decoding handle is initialised with the input buffer and length, the data is effectively deserialised:

C
NdrMesTypeDecode3(
  pHandle,
  &pPicklingInfo,
  &pProxyInfo,
  (const unsigned int **)&ArrTypeOffset,
  0xEu,
  &pObject
);

To our surprise, the function NdrMesTypeDecode3 is nowhere to be documented. The reason is that developers are not supposed to use this function directly. Instead, one should describe structures using Microsoft's IDL (Interface Description Language). Next, the MIDL compiler should be used to generate stubs that can encode and decode data (using the NdrMes functions underneath).

An IDL is a small language for describing the shape of data and the functions that exchange it, a bit like a form template that says which boxes exist and what type each one holds. A compiler turns that description into real code. A stub is the generated helper code that does the packing and unpacking for you.

Nonetheless, header files contain information about the parameters and their types that can help understand a bit more. A header file is a file that declares what functions and structures exist, without their full implementation.

NdrMesTypeDecode3
Interesting fields inside NdrMesTypeDecode3's arguments... (pProxyInfo) From the original on thalium.github.io

The image shows interesting fields inside NdrMesTypeDecode3's arguments, in particular pProxyInfo. The pProxyInfo argument eventually leads to a Format field. It seems to contain a compiled description of all the types that exist and are used within the Smart Card extension.

Then the ArrTypeOffset array, which starts like this: 0x02, 0x1e, 0x1e, 0x54, ..., lists the offsets of all the structures of interest inside the compiled format string. An offset is a distance from a starting point, like a page number in a book. The next argument (0xE) is the offset, in the ArrTypeOffset array, of the structure to consider.

For LocateCardsByATRA, 0xE gives an offset of 0x220 in the ArrTypeOffset array, which points to the compiled format associated with the structure found earlier in the specification:

C
typedef struct _LocateCardsByATRA_Call {
  REDIR_SCARDCONTEXT Context;
  [range(0,1000)] unsigned long cAtrs;
  [size_is(cAtrs)] LocateCards_ATRMask* rgAtrMasks;
  [range(0,10)] unsigned long cReaders;
  [size_is(cReaders)] ReaderStateA* rgReaderStates;
} LocateCardsByATRA_Call;

We are lucky the specification tells us everything about the type structures, and even releases the full IDL in appendix. Without it, the format would have had to be decompiled, and not only the format pointed to by the offset found: there are also many references to other previously defined structures, such as LocateCards_ATRMask. Decompiling means turning compiled machine code back into something readable.

Step 5: root cause

This may be getting a bit hard to follow, so let's summarise what is understood so far:

  • We can send an IoControlCode, InputBuffer and InputBufferLength.
  • The InputBufferLength (DWORD) can be greater than the actual length of InputBuffer.
  • The input buffer will be deserialised (through the RPC NDR marshaling engine) according to a structure that varies with IoControlCode.
  • There are around 60 possible IoControlCode values, and thus decoding structures.
  • There is an OOB read during the deserialisation process, in a certain function NdrSimpleTypeConvert.

While reversing and debugging, it seemed that these "convert" operations actually took place before any real decoding per se. It was as if, before deserialising, there was a first pass on the whole buffer to convert stuff. Reversing means studying a compiled program to understand what it does; debugging means running it under a tool that lets you pause it and inspect memory.

A Windows XP source leak helped shed light on all of this:

C++
void NdrSimpleTypeConvert(PMIDL_STUB_MESSAGE pStubMsg, uchar FormatChar) {
  switch (FormatChar) {
    // ...
    case FC_ULONG:
      ALIGN(pStubMsg->Buffer,3);
      CHECK_EOB_RAISE_BSD( pStubMsg->Buffer + 4 );

      if ((pStubMsg->RpcMsg->DataRepresentation & NDR_INT_REP_MASK) != NDR_LOCAL_ENDIAN) {
        *((ulong *)pStubMsg->Buffer) = RtlUlongByteSwap(*(ulong *)pStubMsg->Buffer);
      }

      pStubMsg->Buffer += 4;
      break;
    // ...
  }
}

Line by line:

  • void NdrSimpleTypeConvert(PMIDL_STUB_MESSAGE pStubMsg, uchar FormatChar) { defines a function that takes a pointer to a stub message (the state of the decoding) and a format character (the type of the next field).
  • switch (FormatChar) { chooses what to do based on that type.
  • case FC_ULONG: handles the type FC_ULONG, which means a 32-bit unsigned integer (unsigned long in the structure).
  • ALIGN(pStubMsg->Buffer,3); moves the buffer pointer forward to the next multiple of 4 bytes, because 32-bit values must start on a 4-byte boundary. This is called alignment.
  • CHECK_EOB_RAISE_BSD( pStubMsg->Buffer + 4 ); is a check meant to raise an error if reading four more bytes would go past the end of the buffer. EOB stands for end of buffer.
  • if ((pStubMsg->RpcMsg->DataRepresentation & NDR_INT_REP_MASK) != NDR_LOCAL_ENDIAN) { checks whether the byte order declared in the message differs from the local machine's byte order. Endianness is the order in which the bytes of a number are stored; the two common orders are big-endian and little-endian.
  • *((ulong *)pStubMsg->Buffer) = RtlUlongByteSwap(*(ulong *)pStubMsg->Buffer); reads the four bytes, swaps their order, and writes them back. This is the byteswap.
  • pStubMsg->Buffer += 4; moves the pointer forward by four bytes, ready for the next field.
  • break; ends this case.

The magic happens when the endianness of the serialised data does not match the local endianness. A pass on the buffer is performed to switch the endianness of (in particular) all the FC_ULONG type fields, the unsigned long fields in the structure.

Therefore, in the _LocateCardsByATRA_Call structure, the fields cAtrs and cReaders are byteswapped. But also, and more importantly, any unsigned long that lies inside the nested rgAtrMasks or rgReaderStates fields will be byteswapped. And these fields are arrays of structs whose size we control.

So there are actually two kinds of overruns here:

  1. The user-supplied PDU->InputBufferLength is not properly checked, so the conversion pass in the RPC NDR deserialisation will go way beyond the end of the PDU in the heap.
  2. The user-supplied cAtrs (or cReaders) coded inside the serialised data can be large enough to make the deserialisation structure overflow the actual length of the buffer, along with the input buffer length provided.

Combined, these overruns result in an out-of-bounds read in the heap, and thus a crash. An overrun is reading or writing past the end of a buffer, like walking past the edge of a pier.

Step 6: heap corruption

Why were there crashes in RPCRT4.DLL, and which payloads triggered them? That is now clear. But there is still no explanation for the tons of other nonsensical crashes.

Let's check the LocateCards_ATRMask structure, which is nested inside LocateCardsByATRA_Call:

C
typedef struct _LocateCards_ATRMask {
  [range(0, 36)] unsigned long cbAtr;
  byte rgbAtr[36];
  byte rgbMask[36];
} LocateCards_ATRMask;

Line by line:

  • typedef struct _LocateCards_ATRMask { starts the definition of the nested structure.
  • [range(0, 36)] unsigned long cbAtr; is a count of ATR bytes, supposed to be between 0 and 36.
  • byte rgbAtr[36]; is a fixed array of 36 bytes holding the ATR itself.
  • byte rgbMask[36]; is a fixed array of 36 bytes holding a mask, used to compare ATRs while ignoring some bits.
  • } LocateCards_ATRMask; closes the definition.

There is an unsigned long field (cbAtr) at the beginning of this struct of total size 76 bytes. Therefore, DWORDs in the heap can be byteswapped every 76 bytes. Setting a breakpoint where the byteswap occurs and watching the heap shows it progressively getting disfigured. A breakpoint is a marker that pauses the program at a chosen instruction so you can look around.

Since PDU->InputBufferLength is arbitrarily large, the end of the heap segment can eventually be reached, causing an OOB read crash. But that is not the interesting thing here.

By byteswapping DWORDs in the heap, a lot of objects are corrupted. If the input buffer length is large enough to allow out-of-bounds operations, but small enough not to exceed the heap segment, the deserialisation process will return with a damaged heap. This leads to numerous types of crashes, all the odd unexplained crashes encountered earlier:

  • Heap Corruption exceptions during heap management calls
  • Random pointers being damaged and causing access violations
  • Damaged vtable pointers causing access violations
  • Damaged vtable pointers that still successfully resolve and redirect the execution flow, of course directly crashing after (illegal instruction), which are the "unknown module" crashes found earlier

A vtable (virtual method table) is a list of function addresses that a program uses to decide which code to run for an object. If an attacker can change a vtable pointer, they can make the program jump to code of their choosing. An access violation is the operating system stopping a program that tried to touch memory it is not allowed to. An illegal instruction is a crash caused by the processor being asked to execute bytes that are not a valid instruction.

Step 7: exploitation

Some of these behaviours could be exploited to achieve unexpected harmful results such as remote code execution. For instance, with some heap spray, one might manage to hijack a vtable through a well-aligned byteswap and redirect the execution flow. But it seemed quite tricky to carry out and the researcher did not manage to exploit it himself. Heap spray means filling the heap with many copies of a chosen pattern so that a random jump is likely to land on it.

There may also be other repercussions of this deserialisation bug. Other kinds of conversions could be performed: float conversions, EBCDIC to ASCII, and so on, but it is not sure whether it is actually possible to trigger them. EBCDIC is an old character encoding used on IBM mainframes, different from the ASCII encoding used on most modern systems.

Reporting to Microsoft

At first the researcher was hesitant about whether to report this to MSRC or not. MSRC is the Microsoft Security Response Center, the team that receives vulnerability reports. He was very unsure about the bug's exploitability, which seemed like it would be very intricate and rely on a lot of luck.

Moreover, by submitting it he would have to tag it as Remote Code Execution, which he thought would be a bold move without any proof of concept. A proof of concept is a working demonstration that the bug can actually be exploited.

He still reported it to MSRC, and rightfully so, as it was assessed Remote Code Execution with Important severity and awarded a $5,000 bounty; the severity was later revised to Critical when the CVE was published. A bounty is a payment a company makes for a useful security report.

In conclusion, do not be afraid to submit bugs even if you lack proof of exploitation. As long as you have a very detailed explanation of the bug, a good understanding of the root cause and a decent analysis of the risks that come with it, it can be acknowledged and awarded. The exploitation process can sometimes require a lot of skill and creativity, and you can always tell yourself that even if you cannot exploit your own bug, there may be an evil super hacker out there who would manage to exploit it. Better be safe than sorry.

Disclosure Timeline

  • 2021-07-22: Sent vulnerability report to MSRC (Microsoft Security Response Center)
  • 2021-07-23: Microsoft started reviewing and reproducing
  • 2021-07-31: Microsoft acknowledged the vulnerability and started developing a fix. They also started reviewing this case for a potential bounty award.
  • 2021-08-04: Microsoft assessed the vulnerability as Remote Code Execution with Important severity. Bounty award: $5,000.
  • 2021-08-13: The vulnerability was assigned CVE-2021-38666.
  • 2021-11-09: Microsoft released the security patch. For some reason, the severity was revised to Critical when the CVE was published.

A CVE (Common Vulnerabilities and Exposures) is a public identifier for a known vulnerability, so that everyone can refer to the same bug unambiguously. A patch is an update that fixes the bug.

Glossary

  • Access violation: an error raised by the operating system when a program tries to read or write memory it is not allowed to touch.
  • Alignment: arranging data so that it starts at an address that is a multiple of its size, which some processors require.
  • API: an agreed set of functions one program offers to another so they can talk to each other.
  • ASLR: Address Space Layout Randomisation, a defence that randomises where things sit in memory so attackers cannot predict addresses.
  • ATR (Answer To Reset): the short byte sequence a smart card sends when powered up, identifying it.
  • Big-endian / little-endian: the two common orders for storing the bytes of a number in memory.
  • Bounty: a payment a company makes for a useful security report.
  • Breakpoint: a marker that pauses a program at a chosen instruction so you can inspect it.
  • Byteswap: reversing the order of the bytes of a number, used to convert between endiannesses.
  • Call stack: the list of functions currently in progress, newest on top.
  • Compiler: a program that turns source code into an executable program.
  • CVE: Common Vulnerabilities and Exposures, a public identifier for a known vulnerability.
  • Debugging: running a program under a tool that lets you pause it and inspect its memory and state.
  • Decompiling: turning compiled machine code back into something readable.
  • Deserialisation: turning a flat sequence of bytes back into structured data.
  • DLL: dynamic link library, a file of shared code that programs load at runtime.
  • DWORD: a 32-bit (four-byte) integer.
  • EBCDIC: an old character encoding used on IBM mainframes, different from ASCII.
  • Endianness: the order in which the bytes of a number are stored.
  • Executable: a program file that can be run.
  • Fuzzing: feeding a program huge amounts of slightly mutated data to find crashes and bugs.
  • Harness: glue code that delivers fuzzer inputs to the right place in the target program.
  • Header file: a file that declares what functions and structures exist, without their full implementation.
  • Heap: the region of memory a program uses for data it creates while running.
  • Heap corruption: damage to the heap's data or bookkeeping, often causing later crashes.
  • Heap spray: filling the heap with many copies of a chosen pattern so a random jump is likely to land on it.
  • IDL (Interface Description Language): a small language for describing the shape of data and the functions that exchange it.
  • Illegal instruction: a crash caused by the processor being asked to execute bytes that are not a valid instruction.
  • IRP (I/O Request Packet): the internal Windows object representing a request to a device driver.
  • Marshaling: packing function arguments or structures into a flat byte stream for sending over a network.
  • Module: a loaded program file such as a DLL or executable.
  • MSRC: Microsoft Security Response Center, the team that receives vulnerability reports.
  • NDR (Network Data Representation): the serialisation format used by RPC to encode data on the wire.
  • Offset: a distance from a starting point, like a page number in a book.
  • Out-of-bounds read: reading memory outside the area a program was given.
  • Overrun: reading or writing past the end of a buffer.
  • Patch: an update that fixes a bug.
  • Payload: the exact malicious message that triggers a bug.
  • PDU (Protocol Data Unit): one message in a protocol conversation.
  • Pickling: Microsoft's word for serialising data into a flat form.
  • Pointer: a number that says where in memory something lives.
  • Proof of concept: a working demonstration that a bug can actually be exploited.
  • Protocol: an agreed set of rules for two programs to exchange messages.
  • RCE (Remote Code Execution): running your own commands on someone else's machine.
  • Register: a tiny, very fast storage slot inside the processor.
  • Reversing: studying a compiled program to understand what it does.
  • RPC (Remote Procedure Call): a way for one program to ask another, possibly on another machine, to run a function for it.
  • Seeding: giving a fuzzer realistic starting examples so its mutations stay close to valid messages.
  • Serialisation: turning structured data into a flat sequence of bytes.
  • Smart card: a chip card used for badges and secure logins.
  • Stub: generated helper code that does packing and unpacking for you.
  • Structure: a named bundle of fields, like a form with several boxes.
  • Virtual channel: a lane inside RDP that carries one kind of data, such as audio or clipboard.
  • Vtable (virtual method table): a list of function addresses a program uses to decide which code to run for an object.
  • WinAFL: a fuzzer for Windows programs that generates many input variations to find crashes.

More by Valentino Ricotta

View all

2 more disclosed reports, best first.

More from Microsoft

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.