Skip to content

Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic

perf(windows): resolve owner PID from WinDivert socket events instead of scanning the TCP table

AnoF-Cyber06fd2947bc03
diff --git a/Windows/compile.ps1 b/Windows/compile.ps1
index 327f289..f7b6197 100644
--- a/Windows/compile.ps1
+++ b/Windows/compile.ps1
@@ -10,7 +10,7 @@ param(
$WinDivertPath = "C:\WinDivert-2.2.2-A"
$SourcePath = "src"
# Core split across modular translation units (see src\pb_internal.h).
-$SourceFile = "ProxyBridge.c pb_util.c pb_process.c pb_rules.c pb_proxy.c pb_dns.c pb_socks5.c pb_http.c pb_conntrack.c pb_relay.c"
+$SourceFile = "ProxyBridge.c pb_util.c pb_process.c pb_rules.c pb_proxy.c pb_dns.c pb_socks5.c pb_http.c pb_conntrack.c pb_relay.c pb_sockmap.c"
$SourceFiles = ($SourceFile.Split(' ') | ForEach-Object { "$SourcePath\$_" }) -join ' '
$OutputDLL = "ProxyBridgeCore.dll"
$OutputDir = "output"
diff --git a/Windows/src/ProxyBridge.c b/Windows/src/ProxyBridge.c
index 31bb3ce..0cb916f 100644
--- a/Windows/src/ProxyBridge.c
+++ b/Windows/src/ProxyBridge.c
@@ -1143,6 +1143,10 @@ PROXYBRIDGE_API BOOL ProxyBridge_Start(void)
return FALSE;
}
+ // Socket-layer events give the owner PID of each new connection without a table scan.
+ // Optional: if it cannot be opened the lookups fall back to the table.
+ sockmap_start();
+
// WINDIVERT_PARAM_QUEUE_LENGTH: max packets in queue (range 32–16384).
// Under heavy upload the kernel enqueues bursts of outbound packets faster
// than the 4 packet threads can drain them; a full queue drops arriving
@@ -1219,6 +1223,8 @@ PROXYBRIDGE_API BOOL ProxyBridge_Stop(void)
running = FALSE;
+ sockmap_stop();
+
if (windivert_handle != INVALID_HANDLE_VALUE)
{
WinDivertShutdown(windivert_handle, WINDIVERT_SHUTDOWN_BOTH);
diff --git a/Windows/src/pb_internal.h b/Windows/src/pb_internal.h
index d312179..021ae40 100644
--- a/Windows/src/pb_internal.h
+++ b/Windows/src/pb_internal.h
@@ -253,6 +253,12 @@ void base64_encode(const char* input, char* output, size_t output_size);
// ---- pb_process.c ----
void *pidtbl_reserve(DWORD need);
+
+// pb_sockmap.c - owner PID of new outbound TCP connections from WinDivert's SOCKET layer
+BOOL sockmap_start(void);
+void sockmap_stop(void);
+DWORD sockmap_lookup_tcp(UINT16 port); // 0 = unknown, fall back to the table scan
+void sockmap_note_scan(void);
DWORD get_process_id_from_connection(UINT32 src_ip, UINT16 src_port);
DWORD get_process_id_from_udp_connection(UINT32 src_ip, UINT16 src_port);
DWORD get_process_id_from_connection_v6(const UINT8 src_ip6[16], UINT16 src_port);
diff --git a/Windows/src/pb_process.c b/Windows/src/pb_process.c
index cae4393..46a7955 100644
--- a/Windows/src/pb_process.c
+++ b/Windows/src/pb_process.c
@@ -32,23 +32,37 @@ void *pidtbl_reserve(DWORD need)
// silently treated as unowned (DIRECT, not logged). Add headroom and retry instead.
static void *owner_table_fetch(BOOL udp, ULONG af)
{
- DWORD size = 0;
- for (int attempt = 0; attempt < 4; attempt++)
+ DWORD size = 0, rc;
+#define OWNER_CALL(buf, szp) (udp ? GetExtendedUdpTable((buf), (szp), FALSE, af, UDP_TABLE_OWNER_PID, 0) \
+ : GetExtendedTcpTable((buf), (szp), FALSE, af, TCP_TABLE_OWNER_PID_ALL, 0))
+ if (g_pidtbl_buf != NULL)
+ {
+ // Fast path: the scratch buffer from the previous lookup is normally big enough, which
+ // saves the separate sizing call (it walks the whole table too, so it costs about as
+ // much as the fetch itself).
+ size = g_pidtbl_cap;
+ rc = OWNER_CALL(g_pidtbl_buf, &size);
+ if (rc == NO_ERROR) return g_pidtbl_buf;
+ if (rc != ERROR_INSUFFICIENT_BUFFER) return NULL;
+ }
+ else
{
- DWORD rc = udp ? GetExtendedUdpTable(NULL, &size, FALSE, af, UDP_TABLE_OWNER_PID, 0)
- : GetExtendedTcpTable(NULL, &size, FALSE, af, TCP_TABLE_OWNER_PID_ALL, 0);
+ rc = OWNER_CALL(NULL, &size);
if (rc != ERROR_INSUFFICIENT_BUFFER && rc != NO_ERROR) return NULL;
+ }
+ for (int attempt = 0; attempt < 4; attempt++)
+ {
size += size / 4 + 4096;
void *t = pidtbl_reserve(size);
if (t == NULL) return NULL;
DWORD got = size;
- rc = udp ? GetExtendedUdpTable(t, &got, FALSE, af, UDP_TABLE_OWNER_PID, 0)
- : GetExtendedTcpTable(t, &got, FALSE, af, TCP_TABLE_OWNER_PID_ALL, 0);
+ rc = OWNER_CALL(t, &got);
if (rc == NO_ERROR) return t;
if (rc != ERROR_INSUFFICIENT_BUFFER) return NULL;
size = got; // grew again: retry with the size it asked for
}
return NULL;
+#undef OWNER_CALL
}
DWORD get_process_id_from_connection(UINT32 src_ip, UINT16 src_port)
@@ -58,7 +72,13 @@ DWORD get_process_id_from_connection(UINT32 src_ip, UINT16 src_port)
if (cached_pid != 0)
return cached_pid;
- DWORD pid = 0;
+ DWORD pid = sockmap_lookup_tcp(src_port);
+ if (pid != 0)
+ {
+ cache_pid(src_ip, src_port, pid, FALSE);
+ return pid;
+ }
+ sockmap_note_scan();
MIB_TCPTABLE_OWNER_PID *tcp_table = (MIB_TCPTABLE_OWNER_PID *)owner_table_fetch(FALSE, AF_INET);
if (tcp_table == NULL)
@@ -145,7 +165,9 @@ DWORD get_process_id_from_udp_connection(UINT32 src_ip, UINT16 src_port)
DWORD get_process_id_from_connection_v6(const UINT8 src_ip6[16], UINT16 src_port)
{
- DWORD pid = 0;
+ DWORD pid = sockmap_lookup_tcp(src_port);
+ if (pid != 0) return pid;
+ sockmap_note_scan();
MIB_TCP6TABLE_OWNER_PID *tcp_table = (MIB_TCP6TABLE_OWNER_PID *)owner_table_fetch(FALSE, AF_INET6);
if (!tcp_table) return 0;
diff --git a/Windows/src/pb_sockmap.c b/Windows/src/pb_sockmap.c
new file mode 100644
index 0000000..8ef802f
--- /dev/null
+++ b/Windows/src/pb_sockmap.c
@@ -0,0 +1,115 @@
+#include "pb_internal.h"
+
+// Owner-PID by local port from WinDivert's SOCKET layer.
+//
+// Finding the process behind a new outbound TCP connection used to mean fetching the whole
+// system TCP table (GetExtendedTcpTable) for every SYN, on the single packet-capture thread.
+// The table includes every TIME_WAIT socket, so on a machine that has been busy for hours it
+// has tens of thousands of rows and one fetch costs several milliseconds - a few hundred new
+// connections per second saturate the thread and everything captured slows down (measured:
+// ~3.6 ms per fetch at ~9.6k rows, ~20 ms of capture-thread time per proxied connection).
+//
+// The socket layer reports every connect() together with its process ID *before* the SYN is
+// sent, so a small port-indexed table filled from those events answers the lookup in O(1).
+// Anything it cannot answer (event not seen yet, entry too old, socket-layer open failed)
+// falls back to the table scan, so behaviour is never worse than before.
+
+#define SOCKMAP_FRESH_MS 8000 // a SYN is evaluated within ~2 s even when the capture queue is backed up
+
+typedef struct { volatile LONG pid; volatile LONG tick; } SOCKMAP_ENTRY;
+static SOCKMAP_ENTRY g_sockmap[65536];
+static HANDLE g_sock_handle = INVALID_HANDLE_VALUE;
+static HANDLE g_sock_thread = NULL;
+static volatile LONG g_sock_events = 0, g_sock_hits = 0, g_sock_scans = 0;
+
+static DWORD WINAPI sockmap_thread(LPVOID arg)
+{
+ (void)arg;
+ WINDIVERT_ADDRESS addr;
+ while (1)
+ {
+ if (!WinDivertRecv(g_sock_handle, NULL, 0, NULL, &addr))
+ {
+ DWORD err = GetLastError();
+ if (!running || err == ERROR_INVALID_HANDLE || err == ERROR_NO_DATA || err == ERROR_OPERATION_ABORTED)
+ break;
+ Sleep(5);
+ continue;
+ }
+ if (addr.Event == WINDIVERT_EVENT_SOCKET_CONNECT && addr.Socket.Protocol == IPPROTO_TCP &&
+ addr.Socket.LocalPort != 0 && addr.Socket.ProcessId != 0)
+ {
+ SOCKMAP_ENTRY *e = &g_sockmap[addr.Socket.LocalPort];
+ InterlockedExchange(&e->tick, 0); // invalidate while updating
+ InterlockedExchange(&e->pid, (LONG)addr.Socket.ProcessId);
+ LONG t = (LONG)GetTickCount(); if (t == 0) t = 1;
+ InterlockedExchange(&e->tick, t);
+ if (InterlockedIncrement(&g_sock_events) == 1)
+ log_message("Process lookup: socket events active (first: PID %lu, local port %u)",
+ (unsigned long)addr.Socket.ProcessId, (unsigned)addr.Socket.LocalPort);
+ }
+ }
+ return 0;
+}
+
+BOOL sockmap_start(void)
+{
+ ZeroMemory(g_sockmap, sizeof(g_sockmap));
+ g_sock_events = g_sock_hits = g_sock_scans = 0;
+ g_sock_handle = WinDivertOpen("event == CONNECT", WINDIVERT_LAYER_SOCKET, 0,
+ WINDIVERT_FLAG_SNIFF | WINDIVERT_FLAG_RECV_ONLY);
+ if (g_sock_handle == INVALID_HANDLE_VALUE)
+ {
+ log_message("Process lookup: socket layer unavailable (%lu), using the TCP table scan", GetLastError());
+ return FALSE;
+ }
+ WinDivertSetParam(g_sock_handle, WINDIVERT_PARAM_QUEUE_LENGTH, 16384);
+ g_sock_thread = CreateThread(NULL, 0, sockmap_thread, NULL, 0, NULL);
+ if (g_sock_thread == NULL)
+ {
+ WinDivertClose(g_sock_handle);
+ g_sock_handle = INVALID_HANDLE_VALUE;
+ return FALSE;
+ }
+ return TRUE;
+}
+
+void sockmap_stop(void)
+{
+ if (g_sock_handle != INVALID_HANDLE_VALUE)
+ {
+ WinDivertShutdown(g_sock_handle, WINDIVERT_SHUTDOWN_BOTH);
+ WinDivertClose(g_sock_handle);
+ g_sock_handle = INVALID_HANDLE_VALUE;
+ }
+ if (g_sock_thread != NULL)
+ {
+ WaitForSingleObject(g_sock_thread, 2000);
+ CloseHandle(g_sock_thread);
+ g_sock_thread = NULL;
+ log_message("Process lookup: %ld connections resolved via socket events, %ld via table scan",
+ g_sock_hits, g_sock_scans);
+ }
+}
+
+// PID that connect()ed from this local port in the last SOCKMAP_FRESH_MS, or 0 (use the table).
+DWORD sockmap_lookup_tcp(UINT16 port)
+{
+ if (g_sock_thread == NULL || port == 0)
+ return 0;
+ SOCKMAP_ENTRY *e = &g_sockmap[port];
+ LONG t1 = e->tick;
+ LONG pid = e->pid;
+ LONG t2 = e->tick;
+ if (t1 == 0 || t1 != t2 || pid == 0)
+ return 0;
+ if ((LONG)((LONG)GetTickCount() - t1) > SOCKMAP_FRESH_MS)
+ return 0;
+ InterlockedIncrement(&g_sock_hits);
+ return (DWORD)pid;
+}
+
+void sockmap_note_scan(void)
+{
+ InterlockedIncrement(&g_sock_scans);
+}