← RDP tunnel
RDP·Guide
All tools

The RDP tunnel

An RDP client that connects to a Remote Desktop server through the local agent, shows the remote desktop on a canvas, and tunnels TCP ports over the same RDP connection, the way SSH does with -L. Because the desktop and the rdp2tcp virtual channel ride one connection, you can sign in interactively (a Fortinet or other OTP prompt included) and start the rdp2tcp server yourself inside that session, then add forwards and speak the rdp2tcp protocol on the channel. The graphics are a bitmap-only, 16 bpp, slow-path session (no drawing orders, no Fast-Path), which keeps the viewer small.

Reaching “active”

The connection log shows each phase: x224 (negotiation) → tls → mcs (channels assigned) → channels (joined) → logon → licensing → capabilities → active. Once it says active, the session is fully up and forwards can be added. A server that insists on NLA fails at x224 with a negotiation failure; a server set to standard RDP security stops with a clear message.

Trying it end to end

Inside the RDP session, run the rdp2tcp server that pairs with this client — the open-source build (github.com/V-E-O/rdp2tcp, server side) or the PowerShell port. It opens the rdp2tcp virtual channel with the WTS API and waits for connect requests. Then add a forward here, for example 127.0.0.1:5432:10.0.0.9:5432, and connect a local client to 127.0.0.1:5432; the server-side peer connects to 10.0.0.9:5432 from inside the remote network and relays.

Contents

  1. The rdp2tcp wire protocol
  2. The RdpClient library
  3. The Rdp2tcpTunnel library
  4. The PDU codec libraries
  5. The Agent library

1The rdp2tcp wire protocol

The rdp2tcp virtual channel carries a self-delimited byte stream (independent of how RDP chunks the channel). Each message is a 4-byte big-endian length followed by that many bytes — a one-byte command, a one-byte tunnel id, and the payload. lib/rdp/rdp2tcp.js matches the layout of the original rdp2tcp (Nicolas Collignon; common/rdp2tcp.h, common/msgparser.c) exactly, so it interoperates with that server.

[uint32 big-endian length N][byte cmd][byte tunnelId][N-2 bytes payload]   // N counts cmd + id + payload
CommandValuePayload
CONN0x00[uint16 BE port][byte addressFamily][hostname bytes][0x00] — ask the server-side peer to connect to host:port. The address family is 0 (any), 1 (IPv4) or 2 (IPv6); the hostname is null-terminated.
CLOSE0x01none — close this tunnel.
DATA0x02the raw tunnel bytes, in either direction.
PING0x03none — keepalive (sent every 5 s, as the reference client does).
BIND / RCONN0x04 / 0x05reverse-forward commands; not used by this local-forward (-L) client.

The server answers a CONN with a CONN message back on tunnel id: [byte err][byte af][uint16 BE port][address bytes]. err is 0 on success, else a code (3 = connection refused, 6 = couldn't resolve the hostname, and so on). This client queues data from the local socket until a successful answer, then relays both ways until either side closes.

2The RdpClient library

lib/rdp/rdp-client.js drives the whole RDP connection sequence (MS-RDPBCGR) over an injected transport and exposes the joined static virtual channels. It is a JavaScript module with no user interface, so it also runs under a mock transport in tests. The transport has the shape of the agent's TCP socket: send(bytes), ondata, onclose, close() and startTls({ serverName }) — which the page implements by wrapping the raw socket with the in-browser TLS client (lib/crypto/tls), since the agent only moves bytes.

For graphics and input, pass the desktop size and colour depth (width, height, bpp) when constructing the client; it then negotiates a bitmap-only session and emits each painted rectangle to client.onbitmap = rect => … (rect is { x, y, width, height, rgba }, a top-down Uint8ClampedArray ready for ctx.putImageData). Send input with client.sendInput(events), where the events come from lib/rdp/rdp-input.js (Input.mouse, Input.wheel, Input.scancode, Input.unicode). The pixel decoding lives in lib/rdp/bitmap-rle.js (the Interleaved-RLE decompressor, MS-RDPBCGR 3.1.9) and lib/rdp/rdp-updates.js (the Bitmap Update parser); lib/rdp/scancodes.js maps a browser KeyboardEvent.code to a set-1 scan code.

import { RdpClient } from "../lib/rdp/rdp-client.js";

const tcp = await agent.tcpConnect("10.0.0.5", 3389);
const client = new RdpClient(tcp, { host: "10.0.0.5", username, password, domain,
                                    channels: ["rdp2tcp"], security: "auto" });
client.onstate = (name, detail) => …;   // x224, tls, mcs, channels, logon, licensing, capabilities, active
client.onlog = line => …;
await client.connect();                  // resolves once the session is active
const channel = client.channel("rdp2tcp");
channel.onmessage = bytes => …;          // a whole channel message (reassembled)
channel.send(bytes);                     // chunked into CHANNEL_PDU PDUs for you

The sequence it runs: X.224 negotiation (requesting TLS, optionally plain RDP) → TLS upgrade on the transport → MCS Connect-Initial/Response carrying the GCC conference PDUs (which declare the rdp2tcp channel and return its assigned id) → Erect Domain, Attach User and Channel Join for the user, I/O and virtual channels → the Client Info (logon) PDU → the licensing “valid client” path → the Demand/Confirm Active capability exchange and the finalization PDUs (synchronize, control, font list) up to the server’s Font Map. Graphics, input and the server’s capability sets are not interpreted.

3The Rdp2tcpTunnel library

lib/rdp/rdp2tcp.js holds both the framing (Rdp2tcpProtocol, documented in section 1) and the forward manager (Rdp2tcpTunnel). The manager opens local listeners through the agent and, for each accepted connection, allocates a tunnel id, sends a CONN and relays bytes.

import { Rdp2tcpTunnel } from "../lib/rdp/rdp2tcp.js";

const tunnel = new Rdp2tcpTunnel(client.channel("rdp2tcp"), agent);
tunnel.start();
await tunnel.addForward({ listenHost: "127.0.0.1", listenPort: 5432,
                          targetHost: "10.0.0.9", targetPort: 5432 });
Rdp2tcpTunnel.parseSpec("127.0.0.1:5432:10.0.0.9:5432");  // { listenHost, listenPort, targetHost, targetPort }
tunnel.onupdate = () => …;   // status, connection counts and byte totals changed
tunnel.removeForward(forward);
tunnel.stop();

Each forward tracks its status, the number of connections it has accepted, and the bytes sent up (local → remote) and down (remote → local). Tunnel ids are 0–254 (0xff is the protocol’s error value) and are reused as connections close.

4The PDU codec libraries

The connection sequence is built from small, dependency-free codec modules. Each has fixed, documented byte layouts and is covered by tests/rdp-test.js.

ModuleWhat it encodes/decodes
lib/rdp/io.jsByteWriter / ByteReader: little- and big-endian integers, UTF-16LE strings and byte slices.
lib/rdp/per.jsPer: the PER (aligned) constructs MCS and GCC use — lengths, integers, 16-bit ids, choices, octet and numeric strings, object identifiers.
lib/rdp/ber.jsBer: the BER subset for the MCS Connect-Initial / Connect-Response (integers, booleans, sequences, application tags 101/102).
lib/rdp/tpkt.jsTpkt and X224: TPKT framing, the X.224 Connection Request/Confirm with the RDP Negotiation Request/Response, and X.224 data TPDUs.
lib/rdp/mcs.jsMcs: Connect-Initial/Response, Erect Domain, Attach User, Channel Join and Send Data request/indication.
lib/rdp/gcc.jsGcc: the GCC Conference Create Request/Response and the client core/security/network and server network data blocks (the assigned channel ids).
lib/rdp/rdp-pdu.jsSecurity, ClientInfo, Licensing, ShareControl, ShareData, Caps, Channel: the logon PDU, the licensing path, the Demand/Confirm Active capability exchange, the finalization PDUs, and the static virtual channel chunk header.

5The Agent library

lib/agent.js is the client of the local agent, used here for the RDP connection, the TLS upgrade and the local listeners. The agent is what lets a web page reach the network and terminate TLS — the browser cannot.

import { Agent } from "../lib/agent.js";

const agent = await Agent.connectSaved();            // the address is set on the Settings page
const tcp = await agent.tcpConnect("10.0.0.5", 3389); // tcp.ondata, tcp.send(bytes), tcp.close()
// TLS runs in the page over the raw socket (the agent only moves bytes):
const tls = await Tls.client(new ByteStream(tcp), { serverName: "10.0.0.5", maxVersion: Tls.VERSIONS.TLS12 });
const listener = await agent.tcpListen("127.0.0.1", 5432);     // listener.onaccept = conn => …

Everything is Uint8Array. TLS is done in the page (lib/crypto/tls, up to TLS 1.2 for RDP), so the agent needs no TLS of its own. NLA (CredSSP) is out of scope because NTLM/CredSSP isn’t implemented, not for any transport reason.