Skip to content

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

test(linux): end-to-end, scale and benchmark suites

anof-cyber23e94ab9483c
diff --git a/Linux/tests/api_live.sh b/Linux/tests/api_live.sh
new file mode 100755
index 0000000..6c7b9b8
--- /dev/null
+++ b/Linux/tests/api_live.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+# Library API against the live datapath. Needs root, curl, python3, gcc. sudo tests/api_live.sh
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+WORK=$(mktemp -d); trap 'kill $FAKE 2>/dev/null; wait 2>/dev/null; rm -rf $WORK' EXIT
+gcc -Wall -Wextra -O1 -g -I"$ROOT/src" -o "$WORK/api_live_test" "$HERE/api_live_test.c" -L"$ROOT/src" -lproxybridge -lpthread || exit 1
+python3 "$HERE/fake_proxies.py" "$WORK/log" >/dev/null 2>&1 & FAKE=$!
+sleep 1
+LD_LIBRARY_PATH="$ROOT/src" "$WORK/api_live_test"
diff --git a/Linux/tests/api_live_test.c b/Linux/tests/api_live_test.c
new file mode 100644
index 0000000..ae7d64b
--- /dev/null
+++ b/Linux/tests/api_live_test.c
@@ -0,0 +1,113 @@
+// Library API test against the live eBPF datapath: every rule/proxy mutation must take effect immediately on new connections.
+// Needs root and the fake proxies running (tests/api_live.sh starts them).
+#define _GNU_SOURCE
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include "../src/ProxyBridge.h"
+
+static int pass, fail;
+static int events;
+static void on_conn(const char *p, uint32_t pid, const char *ip, uint16_t port, const char *info) { (void)p; (void)pid; (void)ip; (void)port; (void)info; events++; }
+static void on_log(const char *m) { if (getenv("PB_VERBOSE")) fprintf(stderr, "[log] %s\n", m); }
+
+static void fetch(const char *ip, char *out, size_t n)
+{
+ char cmd[256]; snprintf(cmd, sizeof cmd, "curl -s -m 2 http://%s/ 2>&1; echo \"rc=$?\"", ip);
+ FILE *f = popen(cmd, "r"); size_t l = 0;
+ while (f && l + 1 < n && fgets(out + l, (int)(n - l), f)) l = strlen(out);
+ if (f) pclose(f);
+}
+static void expect(const char *what, const char *ip, const char *want)
+{
+ char out[512] = ""; fetch(ip, out, sizeof out);
+ int ok = want ? strstr(out, want) != NULL : (strstr(out, "hello-from") == NULL && strstr(out, "rc=0") == NULL);
+ if (want && !strcmp(want, "BLOCKED")) ok = strstr(out, "rc=7") != NULL;
+ printf(" %s %s\n", ok ? "PASS" : "FAIL", what); if (!ok) printf(" got: %.120s\n", out);
+ ok ? pass++ : fail++;
+}
+static void check(const char *what, int cond) { printf(" %s %s\n", cond ? "PASS" : "FAIL", what); cond ? pass++ : fail++; }
+
+int main(void)
+{
+ char err[256] = "";
+ ProxyBridge_SetLogCallback(on_log); ProxyBridge_SetConnectionCallback(on_conn); ProxyBridge_SetTrafficLoggingEnabled(true);
+
+ printf("== validation\n");
+ check("invalid host rejected with a reason", !ProxyBridge_ValidateRule("curl", "999.1.1.1", "80", err, sizeof err) && err[0]);
+ check("invalid port rejected", !ProxyBridge_ValidateRule("curl", "*", "99999", err, sizeof err));
+ check("domain accepted", ProxyBridge_ValidateRule("curl", "*.example.org", "443", err, sizeof err));
+ check("AddRule with bad pattern returns 0 + message", ProxyBridge_AddRule("curl", "1.2.3", "*", RULE_PROTOCOL_TCP, RULE_ACTION_PROXY, 0, err, sizeof err) == 0 && err[0]);
+ check("AddProxy with empty host rejected", ProxyBridge_AddProxy("x", PROXY_TYPE_SOCKS5, "", 1080, "", "", err, sizeof err) == 0);
+ check("AddProxy with port 0 rejected", ProxyBridge_AddProxy("x", PROXY_TYPE_SOCKS5, "h", 0, "", "", err, sizeof err) == 0);
+
+ uint32_t pa = ProxyBridge_AddProxy("a", PROXY_TYPE_SOCKS5, "127.0.0.1", 19080, "", "", err, sizeof err);
+ uint32_t pb = ProxyBridge_AddProxy("b", PROXY_TYPE_SOCKS5, "127.0.0.1", 19081, "bob", "pw", err, sizeof err);
+ uint32_t pc = ProxyBridge_AddProxy("c", PROXY_TYPE_HTTP, "127.0.0.1", 19082, "", "", err, sizeof err);
+ check("three proxies added with distinct ids", pa && pb && pc && pa != pb && pb != pc);
+ uint32_t r1 = ProxyBridge_AddRule("curl", "192.0.2.0/24", "*", RULE_PROTOCOL_TCP, RULE_ACTION_PROXY, pa, err, sizeof err);
+ check("rule added", r1 != 0);
+ check("Start", ProxyBridge_Start());
+ sleep(1);
+
+ printf("== live edits take effect on the next connection\n");
+ expect("initial: rule -> proxy a", "192.0.2.5", "hello-from-A dst=192.0.2.5:80");
+ check("EditRule -> proxy b", ProxyBridge_EditRule(r1, "curl", "192.0.2.0/24", "*", RULE_PROTOCOL_TCP, RULE_ACTION_PROXY, pb, err, sizeof err));
+ expect("after edit: proxy b", "192.0.2.5", "hello-from-B dst=192.0.2.5:80");
+ check("EditRule with a bad pattern fails and keeps the old rule", !ProxyBridge_EditRule(r1, "curl", "bad host", "*", RULE_PROTOCOL_TCP, RULE_ACTION_PROXY, pb, err, sizeof err));
+ expect("old rule still active", "192.0.2.5", "hello-from-B");
+ check("DisableRule", ProxyBridge_DisableRule(r1));
+ expect("disabled: traffic is direct", "192.0.2.5", NULL);
+ check("EnableRule", ProxyBridge_EnableRule(r1));
+ expect("enabled again", "192.0.2.5", "hello-from-B");
+
+ printf("== ordering\n");
+ uint32_t r2 = ProxyBridge_AddRule("curl", "192.0.2.5", "*", RULE_PROTOCOL_TCP, RULE_ACTION_BLOCK, 0, err, sizeof err);
+ expect("BLOCK rule added after the PROXY rule loses (first match wins)", "192.0.2.5", "hello-from-B");
+ check("MoveRule to the top", ProxyBridge_MoveRule(r2, 0));
+ expect("after move: BLOCK wins", "192.0.2.5", "BLOCKED");
+ expect("other addresses still proxied", "192.0.2.6", "hello-from-B dst=192.0.2.6:80");
+ check("MoveRule back to the end", ProxyBridge_MoveRule(r2, 99));
+ expect("PROXY wins again", "192.0.2.5", "hello-from-B");
+ check("DeleteRule (the BLOCK rule)", ProxyBridge_DeleteRule(r2));
+ check("DeleteRule on an unknown id fails", !ProxyBridge_DeleteRule(424242));
+
+ printf("== proxy lifecycle\n");
+ check("DeleteProxy(b)", ProxyBridge_DeleteProxy(pb));
+ expect("rule that used a deleted proxy falls back to the default proxy (a)", "192.0.2.5", "hello-from-A dst=192.0.2.5:80");
+ ProxyBridge_ClearProxies();
+ expect("no proxies at all: PROXY rule fails CLOSED (blocked, never direct)", "192.0.2.5", "BLOCKED");
+ uint32_t pb2 = ProxyBridge_AddProxy("b2", PROXY_TYPE_SOCKS5, "127.0.0.1", 19081, "bob", "pw", err, sizeof err);
+ uint32_t pa2 = ProxyBridge_AddProxy("a2", PROXY_TYPE_SOCKS5, "127.0.0.1", 19080, "", "", err, sizeof err);
+ check("proxies re-added", pa2 && pb2);
+ check("EditRule to proxy_id 0 (= default)", ProxyBridge_EditRule(r1, "curl", "192.0.2.0/24", "*", RULE_PROTOCOL_TCP, RULE_ACTION_PROXY, 0, err, sizeof err));
+ expect("default = first proxy added (b2)", "192.0.2.5", "hello-from-B");
+ ProxyBridge_SetDefaultProxy(pa2);
+ expect("SetDefaultProxy(a2) retargets proxy_id 0 rules", "192.0.2.5", "hello-from-A");
+ check("EditProxy changes the endpoint live (a2 -> HTTP proxy c's port)", ProxyBridge_EditProxy(pa2, "a2", PROXY_TYPE_HTTP, "127.0.0.1", 19082, "", "", err, sizeof err));
+ expect("now served through the HTTP proxy", "192.0.2.5", "hello-from-C dst=192.0.2.5:80");
+
+ printf("== stop/start keeps configuration\n");
+ check("Stop", ProxyBridge_Stop());
+ expect("while stopped: nothing redirected", "192.0.2.5", NULL);
+ check("Start again", ProxyBridge_Start());
+ sleep(1);
+ expect("rules and proxies survived Stop/Start", "192.0.2.5", "hello-from-C");
+
+ printf("== proxy test helper\n");
+ char buf[512] = "";
+ check("TestProxy through a SOCKS5 proxy works", ProxyBridge_TestProxy(pb2, "192.0.2.77", 80, buf, sizeof buf) == 0);
+ printf(" (%s)\n", buf);
+ uint32_t dead = ProxyBridge_AddProxy("dead", PROXY_TYPE_SOCKS5, "127.0.0.1", 19999, "", "", err, sizeof err);
+ buf[0] = 0; check("TestProxy against a dead proxy fails with a readable message", ProxyBridge_TestProxy(dead, "192.0.2.77", 80, buf, sizeof buf) != 0 && strlen(buf) > 5);
+ printf(" (%s)\n", buf);
+
+ printf("== cleanup\n");
+ ProxyBridge_ClearRules();
+ expect("ClearRules: direct again", "192.0.2.5", NULL);
+ check("connection events were reported to the callback", events > 0);
+ ProxyBridge_Stop();
+ printf("\npassed=%d failed=%d\n", pass, fail);
+ return fail != 0;
+}
diff --git a/Linux/tests/dnsbench.sh b/Linux/tests/dnsbench.sh
new file mode 100755
index 0000000..ffe6f81
--- /dev/null
+++ b/Linux/tests/dnsbench.sh
@@ -0,0 +1,31 @@
+#!/bin/bash
+# Latency/throughput of DNS queries with and without the DNS tap. Needs root, python3.
+# sudo tests/dnsbench.sh [queries]
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"; N=${1:-20000}
+export LD_LIBRARY_PATH="$ROOT/src"; DNSIP=10.77.0.3
+WORK=$(mktemp -d); trap 'kill $DNS $PB 2>/dev/null; wait 2>/dev/null; ip addr del $DNSIP/32 dev lo 2>/dev/null; rm -rf $WORK' EXIT
+ip addr add $DNSIP/32 dev lo 2>/dev/null
+python3 "$HERE/fake_dns.py" $DNSIP $WORK/dns.log >/dev/null 2>&1 & DNS=$!
+sleep 1
+bench() { python3 - "$N" "$DNSIP" <<'PY'
+import socket, struct, sys, time
+n, ip = int(sys.argv[1]), sys.argv[2]
+q = struct.pack("!HHHHHH", 1, 0x0100, 1, 0, 0, 0) + b"\x03app\x07example\x04test\x00" + struct.pack("!HH", 1, 1)
+s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.settimeout(2)
+lat = []
+t0 = time.perf_counter()
+for i in range(n):
+ a = time.perf_counter(); s.sendto(q, (ip, 53)); s.recvfrom(512); lat.append(time.perf_counter() - a)
+dt = time.perf_counter() - t0; lat.sort()
+print(" %d queries: %.0f qps avg=%.0fus p50=%.0fus p99=%.0fus" % (n, n / dt, sum(lat) / n * 1e6, lat[n // 2] * 1e6, lat[int(n * 0.99)] * 1e6))
+PY
+}
+echo "== no ProxyBridge"; bench; bench
+stdbuf -oL "$ROOT/cli/ProxyBridge" --proxy a=socks5://127.0.0.1:19080 --rule "*:*.example.test:*:TCP:PROXY=a" > $WORK/pb.out 2>&1 & PB=$!
+for _ in $(seq 40); do grep -q "ProxyBridge started" $WORK/pb.out && break; sleep 0.25; done
+echo "== ProxyBridge running, python3 covered by a domain rule (every query goes through the DNS tap)"; bench; bench
+kill -INT $PB; wait $PB 2>/dev/null
+stdbuf -oL "$ROOT/cli/ProxyBridge" --proxy a=socks5://127.0.0.1:19080 --rule "someother:*.example.test:*:TCP:PROXY=a" > $WORK/pb.out 2>&1 & PB=$!
+for _ in $(seq 40); do grep -q "ProxyBridge started" $WORK/pb.out && break; sleep 0.25; done
+echo "== ProxyBridge running, python3 NOT covered (DNS untouched by the tap)"; bench; bench
diff --git a/Linux/tests/e2e.sh b/Linux/tests/e2e.sh
new file mode 100755
index 0000000..a0fe0d1
--- /dev/null
+++ b/Linux/tests/e2e.sh
@@ -0,0 +1,143 @@
+#!/bin/bash
+# End-to-end test of the eBPF backend. Needs root, curl, python3. Uses only loopback + TEST-NET addresses (nothing leaves the host).
+# sudo Linux/tests/e2e.sh
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(dirname "$HERE")"
+WORK="$(mktemp -d)"
+LOG="$WORK/proxy.log"; : > "$LOG"
+PASS=0; FAIL=0
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+expect_contains() { # name haystack needle
+ if [[ "$2" == *"$3"* ]]; then ok "$1"; else bad "$1 (got: ${2:0:200})"; fi; }
+
+cleanup() { kill "$PB_PID" "$FAKE_PID" "$DIRECT_PID" 2>/dev/null; wait 2>/dev/null; rm -rf "$WORK"; }
+trap cleanup EXIT
+
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+export LD_LIBRARY_PATH="$ROOT/src"
+
+python3 "$HERE/fake_proxies.py" "$LOG" > "$WORK/fake.out" 2>&1 & FAKE_PID=$!
+# a direct (non-proxied) origin on the host's own LAN address, so DIRECT rules can be seen to work
+MYIP=$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p' | head -1); MYIP=${MYIP:-127.0.0.1}
+mkdir -p "$WORK/www"; echo "direct-origin" > "$WORK/www/index.html"
+python3 -m http.server 18399 --bind "$MYIP" --directory "$WORK/www" >/dev/null 2>&1 & DIRECT_PID=$!
+sleep 1
+
+cp "$(command -v curl)" "$WORK/newcurl" # a binary that did not exist when ProxyBridge started
+
+stdbuf -oL "$ROOT/cli/ProxyBridge" --verbose 3 \
+ --proxy a=socks5://127.0.0.1:19080 --proxy b=socks5://bob:[email protected]:19081 --proxy c=http://127.0.0.1:19082 \
+ --rule "curl:$MYIP/32:18399:TCP:DIRECT" \
+ --rule "curl:192.0.2.0/24:*:TCP:PROXY=a" \
+ --rule "curl:198.51.100.0/24:*:TCP:PROXY=b" \
+ --rule "curl:203.0.113.0/24:*:TCP:PROXY=c" \
+ --rule "curl:203.0.114.0/24:*:TCP:BLOCK" \
+ --rule "curl:2001:db8::/32:80:TCP:PROXY=a" \
+ --rule "curl:10.200.0.0/24:*:TCP:PROXY=a" \
+ --rule "newcurl:192.0.2.0/24:*:TCP:PROXY=b" \
+ --rule "python3*:192.0.2.0/24:5300:UDP:PROXY=a" \
+ --rule "python3*:198.51.100.0/24:5300:UDP:PROXY=b" \
+ --rule "python3*:2001:db8::/32:*:BOTH:PROXY=a" \
+ > "$WORK/pb.out" 2>&1 & PB_PID=$!
+for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && break; sleep 0.25; done
+if ! grep -q "ProxyBridge started" "$WORK/pb.out"; then echo "ProxyBridge failed to start:"; cat "$WORK/pb.out"; exit 1; fi
+sleep 1
+
+echo "== TCP: per-rule proxy selection, original destination recovery"
+out=$(curl -s -m 5 http://192.0.2.7/); expect_contains "proxy A via SOCKS5" "$out" "hello-from-A dst=192.0.2.7:80"
+out=$(curl -s -m 5 http://198.51.100.7:8080/); expect_contains "proxy B via SOCKS5 user/pass" "$out" "hello-from-B dst=198.51.100.7:8080"
+out=$(curl -s -m 5 http://203.0.113.7:81/); expect_contains "proxy C via HTTP CONNECT" "$out" "hello-from-C dst=203.0.113.7:81"
+out=$(curl -s -m 5 http://203.0.114.7/ 2>&1; echo "rc=$?"); expect_contains "BLOCK rule rejects connect()" "$out" "rc=7"
+out=$(curl -s -m 5 "http://$MYIP:18399/"); expect_contains "DIRECT rule bypasses the proxies" "$out" "direct-origin"
+out=$(curl -s -g -m 5 'http://[2001:db8::7]/'); expect_contains "IPv6 destination through proxy A" "$out" "hello-from-A dst=2001:db8::7:80"
+out=$(curl -s -m 5 http://127.0.0.1:19080/ 2>&1; echo "rc=$?"); expect_contains "loopback is never redirected" "$out" "rc="
+out=$("$WORK/newcurl" -s -m 5 http://192.0.2.8/); expect_contains "binary unknown at start (slow path)" "$out" "hello-from-B dst=192.0.2.8:80"
+out=$("$WORK/newcurl" -s -m 5 http://192.0.2.9/); expect_contains "same binary, learned class (fast path)" "$out" "hello-from-B dst=192.0.2.9:80"
+out=$(curl -s -m 5 http://192.0.2.10/); expect_contains "other binary still uses its own rule" "$out" "hello-from-A dst=192.0.2.10:80"
+pids=(); for i in $(seq 30); do curl -s -m 5 http://192.0.2.$((20+i))/ >/dev/null & pids+=($!); done; wait "${pids[@]}" 2>/dev/null
+sleep 1
+c=$(grep -c "^A TCP 192.0.2.\(2[1-9]\|3[0-9]\|4[0-9]\|50\):80" "$LOG"); [ "$c" -ge 30 ] && ok "30 concurrent connections all proxied ($c)" || bad "concurrent: only $c/30 reached proxy A"
+
+echo "== isolation: other network namespaces (containers) are never redirected"
+if ip netns add pbtest 2>/dev/null; then
+ ip netns exec pbtest ip link set lo up; ip netns exec pbtest ip addr add 10.200.0.1/32 dev lo
+ ip netns exec pbtest python3 -m http.server 18400 --bind 10.200.0.1 --directory "$WORK/www" >/dev/null 2>&1 & NSPID=$!
+ sleep 1
+ out=$(ip netns exec pbtest curl -s -m 4 http://10.200.0.1:18400/ 2>&1; echo "rc=$?")
+ expect_contains "curl inside a netns reaches its own server (rule matches the IP, but the namespace is foreign)" "$out" "direct-origin"
+ kill $NSPID 2>/dev/null; ip netns del pbtest 2>/dev/null
+else
+ echo " SKIP ip netns not available"
+fi
+
+echo "== UDP: unconnected, multi-destination, connected, IPv6"
+out=$(python3 - <<'PY'
+import socket
+s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.settimeout(4)
+res = []
+for dst in [("192.0.2.9", 5300), ("198.51.100.9", 5300), ("192.0.2.9", 5300)]:
+ s.sendto(b"ping", dst)
+ d, a = s.recvfrom(200)
+ res.append(f"{d.decode()}|from={a[0]}:{a[1]}")
+print("\n".join(res))
+c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); c.settimeout(4)
+c.connect(("192.0.2.9", 5300)); c.send(b"conn"); d = c.recv(200)
+print("connected:" + d.decode() + "|peer=%s:%d" % c.getpeername())
+s6 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM); s6.settimeout(4)
+try:
+ s6.sendto(b"v6", ("2001:db8::9", 5300)); print("v6 unconnected: sent")
+except OSError as e:
+ print("v6 unconnected: blocked errno=%d" % e.errno)
+c6 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM); c6.settimeout(4)
+c6.connect(("2001:db8::9", 5300)); c6.send(b"v6c"); d = c6.recv(200)
+print("v6 connected:" + d.decode() + "|peer=%s:%d" % c6.getpeername()[:2])
+d6 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM); d6.settimeout(4)
+d6.sendto(b"mapped", ("::ffff:192.0.2.9", 5300)); d, a = d6.recvfrom(200)
+print("v6 socket, v4 dest:" + d.decode() + "|from=%s" % a[0])
+PY
+)
+expect_contains "UDP via proxy A, source restored" "$out" "UDP-A 192.0.2.9:5300 ping|from=192.0.2.9:5300"
+expect_contains "same socket, second destination -> proxy B" "$out" "UDP-B 198.51.100.9:5300 ping|from=198.51.100.9:5300"
+expect_contains "connected UDP works and getpeername restored" "$out" "connected:UDP-A 192.0.2.9:5300 conn|peer=192.0.2.9:5300"
+expect_contains "native IPv6 unconnected UDP fails closed (EPERM)" "$out" "v6 unconnected: blocked errno=1"
+expect_contains "connected IPv6 UDP through proxy A, peer restored" "$out" "v6 connected:UDP-A 2001:db8::9:5300 v6c|peer=2001:db8::9:5300"
+expect_contains "dual-stack socket sending to IPv4 dest" "$out" "v6 socket, v4 dest:UDP-A 192.0.2.9:5300 mapped"
+
+echo "== UDP: large datagrams and many sockets"
+out=$(python3 - <<'PY'
+import socket, concurrent.futures as cf
+s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.settimeout(5)
+big = bytes(range(256)) * 230 # 58,880 bytes
+s.sendto(big, ("192.0.2.9", 5300)); d, a = s.recvfrom(70000)
+prefix = b"UDP-A 192.0.2.9:5300 "
+print("big:", "ok" if d == prefix + big else "MISMATCH len=%d" % len(d))
+def one(i):
+ c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); c.settimeout(8)
+ payload = b"n%d" % i
+ c.sendto(payload, ("192.0.2.%d" % (100 + i % 100), 5300))
+ d, a = c.recvfrom(100)
+ return d.endswith(payload) and a[0] == "192.0.2.%d" % (100 + i % 100)
+with cf.ThreadPoolExecutor(64) as ex:
+ res = list(ex.map(one, range(400)))
+print("many:", sum(res), "/ 400")
+PY
+)
+expect_contains "58KB datagram through SOCKS5 UDP, intact" "$out" "big: ok"
+expect_contains "400 concurrent UDP sockets, each reply from the right address" "$out" "many: 400 / 400"
+
+echo "== logging"
+sleep 1
+grep -q "\[CONN\] curl" "$WORK/pb.out" && ok "connection events reported to the CLI" || bad "no [CONN] events"
+
+echo "== lifecycle"
+kill -INT "$PB_PID"; wait "$PB_PID" 2>/dev/null
+out=$(curl -s -m 3 http://192.0.2.7/ 2>&1; echo "rc=$?")
+[[ "$out" != *hello-from* ]] && ok "after stop traffic is no longer redirected" || bad "still redirected after stop"
+bpftool prog show 2>/dev/null | grep -q pb_connect && bad "BPF programs left behind" || ok "BPF programs detached"
+ss -ltn 2>/dev/null | grep -qE ":2401[0-9]" && bad "relay ports still listening" || ok "relay ports released"
+
+echo
+echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ] || { echo "---- proxy log"; cat "$LOG"; echo "---- pb output"; tail -30 "$WORK/pb.out"; exit 1; }
diff --git a/Linux/tests/e2e_domains.sh b/Linux/tests/e2e_domains.sh
new file mode 100755
index 0000000..60cdadb
--- /dev/null
+++ b/Linux/tests/e2e_domains.sh
@@ -0,0 +1,68 @@
+#!/bin/bash
+# End-to-end test of domain-name rules (DNS tap). Needs root, dig, curl, python3.
+# sudo Linux/tests/e2e_domains.sh
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+WORK="$(mktemp -d)"; PLOG="$WORK/proxy.log"; DLOG="$WORK/dns.log"; : > "$PLOG"; : > "$DLOG"
+PASS=0; FAIL=0; DNSIP=10.77.0.2
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+has() { [[ "$2" == *"$3"* ]] && ok "$1" || bad "$1 (got: ${2:0:160})"; }
+cleanup() { kill "$PB_PID" "$FAKE_PID" "$DNS_PID" 2>/dev/null; wait 2>/dev/null; ip addr del $DNSIP/32 dev lo 2>/dev/null; rm -rf "$WORK"; }
+trap cleanup EXIT
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+export LD_LIBRARY_PATH="$ROOT/src"
+ip addr add $DNSIP/32 dev lo 2>/dev/null
+python3 "$HERE/fake_proxies.py" "$PLOG" > /dev/null 2>&1 & FAKE_PID=$!
+python3 "$HERE/fake_dns.py" $DNSIP "$DLOG" > /dev/null 2>&1 & DNS_PID=$!
+sleep 1
+
+stdbuf -oL "$ROOT/cli/ProxyBridge" --verbose 2 \
+ --proxy a=socks5://127.0.0.1:19080 --proxy b=socks5://bob:[email protected]:19081 --proxy h=socks5://localhost:19080 \
+ --rule "*:blocked.example.test:*:TCP:BLOCK" \
+ --rule "*:*.example.test:*:TCP:PROXY=a" \
+ --rule "*:*.corp.test;*.cdnnet.test:*:TCP:PROXY=b" \
+ --rule "*:svc.byname.test:*:TCP:PROXY=h" \
+ > "$WORK/pb.out" 2>&1 & PB_PID=$!
+for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && break; sleep 0.25; done
+grep -q "ProxyBridge started" "$WORK/pb.out" || { echo "ProxyBridge failed to start"; cat "$WORK/pb.out"; exit 1; }
+sleep 1
+
+resolve() { dig @$DNSIP "$@" +short +time=3 +tries=1 | head -1; }
+
+echo "== resolver answers are delivered unchanged"
+ip1=$(resolve app.example.test); has "UDP DNS answer reaches the application" "$ip1" "192.0.2.77"
+ip2=$(dig @$DNSIP +tcp tcp.example.test +short +time=3 +tries=1 | head -1); has "TCP DNS answer reaches the application" "$ip2" "192.0.2.80"
+nx=$(dig @$DNSIP nope.example.test +time=3 +tries=1 | grep -c NXDOMAIN); [ "$nx" -ge 1 ] && ok "NXDOMAIN is passed through" || bad "NXDOMAIN lost"
+
+echo "== domain rules: resolve with one process, connect with another"
+out=$(curl -s -m 5 http://192.0.2.77/); has "*.example.test -> proxy a (UDP DNS learned)" "$out" "hello-from-A dst=192.0.2.77:80"
+out=$(curl -s -m 5 http://192.0.2.80/); has "*.example.test -> proxy a (TCP DNS learned)" "$out" "hello-from-A dst=192.0.2.80:80"
+resolve blocked.example.test >/dev/null
+out=$(curl -s -m 5 http://192.0.2.78/ 2>&1; echo "rc=$?"); has "exact-name BLOCK rule beats the wildcard rule" "$out" "rc=7"
+resolve www.corp.test >/dev/null
+out=$(curl -s -m 5 http://192.0.2.79/); has "CNAME chain: rule on the canonical name -> proxy b" "$out" "hello-from-B dst=192.0.2.79:80"
+resolve svc.byname.test >/dev/null
+out=$(curl -s -m 5 http://192.0.2.81/); has "domain rule + proxy configured by hostname (localhost)" "$out" "hello-from-A dst=192.0.2.81:80"
+
+echo "== things that must NOT match"
+resolve plain.other.test >/dev/null
+out=$(curl -s -m 2 http://192.0.2.82/ 2>&1; echo "rc=$?"); [[ "$out" != *hello-from* ]] && ok "resolved name without a rule is not proxied" || bad "unexpected proxying"
+out=$(curl -s -m 2 http://192.0.2.99/ 2>&1; echo "rc=$?"); [[ "$out" != *hello-from* ]] && ok "IP never seen in DNS is not matched by a domain rule" || bad "unexpected proxying"
+grep -q "192.0.2.82\|192.0.2.99" "$PLOG" && bad "proxy saw traffic it should not have" || ok "proxies saw no unmatched destinations"
+
+echo "== latency: first connection right after the answer (no race)"
+okc=0; for i in 1 2 3 4 5; do resolve app.example.test >/dev/null; r=$(curl -s -m 5 http://192.0.2.77/); [[ "$r" == *hello-from-A* ]] && okc=$((okc+1)); done
+[ "$okc" = 5 ] && ok "5/5 connections matched immediately after resolution" || bad "only $okc/5 matched immediately"
+
+echo "== logging"
+sleep 1
+grep -q "192.0.2.77 (app.example.test)" "$WORK/pb.out" && ok "connection log shows the domain name" || bad "no domain name in connection log"
+
+echo "== lifecycle"
+kill -INT "$PB_PID"; wait "$PB_PID" 2>/dev/null
+out=$(dig @$DNSIP app.example.test +short +time=3 +tries=1 | head -1); has "DNS still works after ProxyBridge stops" "$out" "192.0.2.77"
+bpftool prog show 2>/dev/null | grep -q pb_connect && bad "BPF programs left behind" || ok "BPF programs detached"
+
+echo; echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ] || { echo "---- dns log"; cat "$DLOG"; echo "---- proxy log"; cat "$PLOG"; echo "---- pb output"; tail -30 "$WORK/pb.out"; exit 1; }
diff --git a/Linux/tests/e2e_openssh.sh b/Linux/tests/e2e_openssh.sh
new file mode 100755
index 0000000..6124e9b
--- /dev/null
+++ b/Linux/tests/e2e_openssh.sh
@@ -0,0 +1,79 @@
+#!/bin/bash
+# Interoperability with a REAL third-party SOCKS5 server: OpenSSH's `ssh -D`. Needs root, sshd, ssh, curl, python3.
+# sudo tests/e2e_openssh.sh
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+WORK="$(mktemp -d)"; PASS=0; FAIL=0; ORIGIN=10.77.0.5
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+cleanup() { kill $SSHD $SSH $WWW $PB 2>/dev/null; wait 2>/dev/null; ip addr del $ORIGIN/32 dev lo 2>/dev/null; rm -rf "$WORK"; }
+trap cleanup EXIT
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+export LD_LIBRARY_PATH="$ROOT/src"
+command -v sshd >/dev/null && command -v ssh >/dev/null || { echo "SKIP: openssh not installed"; exit 0; }
+ip addr add $ORIGIN/32 dev lo 2>/dev/null
+
+ssh-keygen -q -t ed25519 -N '' -f "$WORK/hostkey"; ssh-keygen -q -t ed25519 -N '' -f "$WORK/clientkey"
+cp "$WORK/clientkey.pub" "$WORK/authorized_keys"; chmod 600 "$WORK/authorized_keys"
+cat > "$WORK/sshd_config" <<CFG
+Port 22222
+ListenAddress 127.0.0.1
+HostKey $WORK/hostkey
+AuthorizedKeysFile $WORK/authorized_keys
+PermitRootLogin yes
+PasswordAuthentication no
+UsePAM no
+PidFile $WORK/sshd.pid
+StrictModes no
+AllowTcpForwarding yes
+LogLevel VERBOSE
+CFG
+mkdir -p /run/sshd
+/usr/sbin/sshd -D -e -f "$WORK/sshd_config" 2> "$WORK/sshd.log" & SSHD=$!
+sleep 1
+ssh -N -D 127.0.0.1:19090 -p 22222 -i "$WORK/clientkey" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ExitOnForwardFailure=yes [email protected] 2> "$WORK/ssh.log" & SSH=$!
+for _ in $(seq 30); do ss -ltn 2>/dev/null | grep -q ":19090" && break; sleep 0.3; done
+ss -ltn | grep -q ":19090" && ok "OpenSSH SOCKS5 server is up (ssh -D 19090)" || { bad "ssh -D did not start: $(tail -3 $WORK/ssh.log)"; exit 1; }
+
+# a real origin on a non-loopback local address, serving a 40MB file and a small page
+head -c 41943040 /dev/urandom > "$WORK/big.bin"; echo "real-origin-page" > "$WORK/index.html"
+python3 -m http.server 18500 --bind $ORIGIN --directory "$WORK" >/dev/null 2>&1 & WWW=$!
+sleep 1
+SUM=$(sha256sum "$WORK/big.bin" | cut -d' ' -f1)
+
+stdbuf -oL "$ROOT/cli/ProxyBridge" --verbose 1 --proxy ossh=socks5://127.0.0.1:19090 \
+ --rule "curl:$ORIGIN:18500:TCP:PROXY=ossh" > "$WORK/pb.out" 2>&1 & PB=$!
+for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && break; sleep 0.25; done
+
+out=$(curl -s -m 8 http://$ORIGIN:18500/index.html)
+[[ "$out" == *real-origin-page* ]] && ok "small request through OpenSSH's SOCKS5 server" || bad "small request (got: ${out:0:100})"
+GOT=$(curl -s -m 60 http://$ORIGIN:18500/big.bin | sha256sum | cut -d' ' -f1)
+[ "$GOT" = "$SUM" ] && ok "40 MB download through OpenSSH SOCKS5: checksum identical" || bad "40MB checksum mismatch"
+pids=(); for i in $(seq 40); do curl -s -m 20 http://$ORIGIN:18500/index.html > "$WORK/c$i.out" & pids+=($!); done; wait "${pids[@]}" 2>/dev/null
+n=$(grep -l real-origin-page "$WORK"/c*.out 2>/dev/null | wc -l); [ "$n" = 40 ] && ok "40 parallel connections through OpenSSH SOCKS5" || bad "only $n/40 parallel requests succeeded"
+# upload (client -> origin) integrity
+python3 - "$WORK" <<'PY' &
+import http.server, socketserver, sys, hashlib, threading
+class H(http.server.BaseHTTPRequestHandler):
+ def do_POST(self):
+ n = int(self.headers["Content-Length"]); h = hashlib.sha256(); left = n
+ while left:
+ b = self.rfile.read(min(65536, left)); h.update(b); left -= len(b)
+ body = h.hexdigest().encode(); self.send_response(200); self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
+ def log_message(self, *a): pass
+socketserver.TCPServer.allow_reuse_address = True
+socketserver.ThreadingTCPServer(("10.77.0.5", 18501), H).serve_forever()
+PY
+UP=$!; sleep 1
+kill -INT $PB; wait $PB 2>/dev/null
+stdbuf -oL "$ROOT/cli/ProxyBridge" --proxy ossh=socks5://127.0.0.1:19090 --rule "curl:$ORIGIN:18500-18501:TCP:PROXY=ossh" > "$WORK/pb.out" 2>&1 & PB=$!
+for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && break; sleep 0.25; done
+GOT=$(curl -s -m 60 --data-binary @"$WORK/big.bin" http://$ORIGIN:18501/ )
+[ "$GOT" = "$SUM" ] && ok "40 MB upload through OpenSSH SOCKS5: origin received identical bytes" || bad "upload checksum mismatch (got ${GOT:0:20})"
+kill $UP 2>/dev/null
+# negative control: with the SSH proxy gone, the redirected request must FAIL (it would succeed if it bypassed the proxy)
+kill $SSH 2>/dev/null; sleep 1
+out=$(curl -s -m 4 http://$ORIGIN:18500/index.html 2>&1; echo "rc=$?")
+[[ "$out" != *real-origin-page* ]] && ok "negative control: with the proxy killed the request fails, so it really went through the proxy" || bad "request succeeded without the proxy: traffic bypassed it"
+echo; echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ] || { echo "--- pb"; tail -15 "$WORK/pb.out"; echo "--- sshd"; tail -10 "$WORK/sshd.log"; exit 1; }
diff --git a/Linux/tests/e2e_rules.sh b/Linux/tests/e2e_rules.sh
new file mode 100755
index 0000000..da0f700
--- /dev/null
+++ b/Linux/tests/e2e_rules.sh
@@ -0,0 +1,143 @@
+#!/bin/bash
+# Rule-matrix end-to-end test: every rule form and every upstream proxy type through the real kernel datapath.
+# sudo tests/e2e_rules.sh (needs curl, python3; only loopback + TEST-NET addresses are used)
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+WORK="$(mktemp -d)"; PLOG="$WORK/proxy.log"; : > "$PLOG"
+PASS=0; FAIL=0
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+via() { # name url expected-proxy-letter expected-dst
+ local out; out=$(curl -s -m 5 "$2" 2>&1)
+ [[ "$out" == *"hello-from-$3 dst=$4"* ]] && ok "$1" || bad "$1 (got: ${out:0:140})"; }
+direct() { # name url -> must NOT reach any proxy (times out / fails)
+ local out; out=$(curl -s -m 2 "$2" 2>&1; echo "rc=$?")
+ [[ "$out" != *hello-from* && "$out" != *"rc=0"* ]] && ok "$1" || bad "$1 (got: ${out:0:140})"; }
+blocked() { local out; out=$(curl -s -m 5 "$2" 2>&1; echo "rc=$?"); [[ "$out" == *"rc=7"* ]] && ok "$1" || bad "$1 (got: ${out:0:140})"; }
+cleanup() { kill $PB_PID $FAKE_PID 2>/dev/null; wait 2>/dev/null; rm -rf "$WORK"; }
+trap cleanup EXIT
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+export LD_LIBRARY_PATH="$ROOT/src"
+
+python3 "$HERE/fake_proxies.py" "$PLOG" >/dev/null 2>&1 & FAKE_PID=$!
+mkdir -p "$WORK/bin" "$WORK/pbpath"
+CURL=$(command -v curl)
+cp "$CURL" "$WORK/bin/wget"; cp "$CURL" "$WORK/bin/newtool"; cp "$CURL" "$WORK/bin/mycurlbin"; cp "$CURL" "$WORK/pbpath/tool"
+sleep 1
+
+start_pb() { # extra CLI args...
+ stdbuf -oL "$ROOT/cli/ProxyBridge" --verbose 1 \
+ --proxy a=socks5://127.0.0.1:19080 --proxy b=socks5://bob:[email protected]:19081 --proxy c=http://127.0.0.1:19082 \
+ --proxy d=http://bob:[email protected]:19083 --proxy e=http://bob:[email protected]:19083 "$@" > "$WORK/pb.out" 2>&1 & PB_PID=$!
+ for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && return 0; sleep 0.25; done
+ echo "ProxyBridge failed to start"; cat "$WORK/pb.out"; exit 1; }
+
+start_pb \
+ --rule "curl:192.0.2.90:*:TCP:BLOCK" \
+ --rule "curl:192.0.2.0/24:*:TCP:PROXY=a" \
+ --rule "curl:198.51.100.20-198.51.100.29:*:TCP:PROXY=b" \
+ --rule "curl:198.51.*.*:443:TCP:PROXY=c" \
+ --rule "curl:203.0.1-3.*:*:TCP:PROXY=a" \
+ --rule "curl:203.0.113.40:80;443;8000-9000:TCP:PROXY=b" \
+ --rule "wget;newtool:203.0.113.50:*:TCP:PROXY=a" \
+ --rule "$WORK/pbpath/*:203.0.113.60:*:TCP:PROXY=b" \
+ --rule "*urlbin*:203.0.113.70:*:TCP:PROXY=a" \
+ --rule "curl:203.0.113.80:1;2;3;4;5;6;7;80:TCP:PROXY=b" \
+ --rule "curl:10.0.0.0/8;172.16.0.0/12;100.64.0.0/10;192.168.0.0/16;169.254.0.0/16;203.0.113.90:*:TCP:PROXY=a" \
+ --rule "CURL:203.0.113.150:*:TCP:PROXY=a" \
+ --rule "curl:203.0.113.100:*:TCP:PROXY=d" \
+ --rule "curl:203.0.113.101:*:TCP:PROXY=e" \
+ --rule "python3*:203.0.113.70:*:UDP:PROXY=a" \
+ --rule "python3*:203.0.113.110:5300:UDP:PROXY=c" \
+ --rule "python3*:203.0.113.120:*:UDP:BLOCK" \
+ --rule "python3*:203.0.113.130:5300-5310:UDP:PROXY=b" \
+ --rule "python3*:203.0.113.140:53:UDP:PROXY=a" \
+ --rule "python3*:203.0.113.160:*:BOTH:PROXY=a"
+sleep 1
+
+echo "== host forms (process: curl)"
+via "single IP" http://192.0.2.10/ A 192.0.2.10:80
+via "CIDR /24" http://192.0.2.200/ A 192.0.2.200:80
+via "range a-b (inside)" http://198.51.100.25/ B 198.51.100.25:80
+direct "range a-b (outside)" http://198.51.100.30:8080/
+via "octet wildcard 198.51.*.* + port 443" http://198.51.100.99:443/ C 198.51.100.99:443
+via "octet-range box 203.0.1-3.* (slow path)" http://203.0.2.77/ A 203.0.2.77:80
+direct "octet-range box (outside)" http://203.0.4.77/
+via "6 CIDRs in one rule (kernel cannot hold them, slow path)" http://203.0.113.90/ A 203.0.113.90:80
+
+echo "== port forms"
+via "port list: 80" http://203.0.113.40/ B 203.0.113.40:80
+via "port range 8000-9000 (8500)" http://203.0.113.40:8500/ B 203.0.113.40:8500
+direct "port not in list/range (22)" http://203.0.113.40:22/
+via "8 ports in a list (kernel table has 4 -> slow path)" http://203.0.113.80/ B 203.0.113.80:80
+direct "port 81 not in that list" http://203.0.113.80:81/
+
+echo "== process forms"
+out=$("$WORK/bin/wget" -s -m 5 http://203.0.113.50/); [[ "$out" == *"hello-from-A dst=203.0.113.50:80"* ]] && ok "process list a;b matches 'wget'" || bad "process list (got ${out:0:100})"
+out=$("$WORK/bin/newtool" -s -m 5 http://203.0.113.50/); [[ "$out" == *"hello-from-A dst=203.0.113.50:80"* ]] && ok "process list a;b matches 'newtool'" || bad "process list 2 (got ${out:0:100})"
+out=$(curl -s -m 2 http://203.0.113.50/ 2>&1; echo "rc=$?"); [[ "$out" != *hello-from* ]] && ok "process not in the list ('curl') is not matched" || bad "list leaked"
+out=$("$WORK/pbpath/tool" -s -m 5 http://203.0.113.60/); [[ "$out" == *"hello-from-B dst=203.0.113.60:80"* ]] && ok "full-path glob /dir/* matches" || bad "path glob (got ${out:0:100})"
+out=$("$WORK/bin/mycurlbin" -s -m 5 http://203.0.113.70/); [[ "$out" == *"hello-from-A dst=203.0.113.70:80"* ]] && ok "middle glob *urlbin* matches 'mycurlbin'" || bad "middle glob (got ${out:0:100})"
+direct "process names are case-sensitive (rule 'CURL' does not match 'curl')" http://203.0.113.150/
+
+echo "== ordering: first match wins"
+blocked "specific BLOCK before the broader /24 PROXY" http://192.0.2.90/
+via "same /24, other address, still proxied" http://192.0.2.91/ A 192.0.2.91:80
+
+echo "== HTTP proxies"
+via "HTTP CONNECT with Basic auth (correct credentials)" http://203.0.113.100/ D 203.0.113.100:80
+out=$(curl -s -m 5 http://203.0.113.101/ 2>&1; echo "rc=$?"); [[ "$out" != *hello-from* ]] && ok "HTTP CONNECT with wrong credentials fails (407), nothing leaks" || bad "wrong creds accepted"
+grep -q "^D AUTHFAIL" "$PLOG" && ok "the proxy really answered 407 (proxy log)" || bad "no 407 seen by the proxy"
+
+echo "== UDP rules"
+out=$(python3 - <<'PY'
+import socket
+def probe(dst, payload=b"p", timeout=2):
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.settimeout(timeout)
+ try:
+ s.sendto(payload, dst); d, a = s.recvfrom(200); return d.decode() + "|" + a[0] + ":" + str(a[1])
+ except socket.timeout: return "timeout"
+ except OSError as e: return "errno=%d" % e.errno
+print("port-range-in:", probe(("203.0.113.130", 5305)))
+print("port-range-out:", probe(("203.0.113.130", 5400), timeout=1))
+print("udp-only-rule-on-tcp-dst:", probe(("203.0.113.70", 5300), timeout=1))
+print("block:", probe(("203.0.113.120", 5300)))
+print("http-proxy-udp:", probe(("203.0.113.110", 5300), timeout=1))
+print("both:", probe(("203.0.113.160", 5300)))
+print("dns-port-53:", probe(("203.0.113.140", 53)))
+PY
+)
+[[ "$out" == *"port-range-in: UDP-B 203.0.113.130:5305 p|203.0.113.130:5305"* ]] && ok "UDP port range 5300-5310 via SOCKS5+auth, source restored" || bad "udp port range ($out)"
+[[ "$out" == *"port-range-out: timeout"* ]] && ok "UDP port outside the range is not proxied" || bad "udp range leak"
+[[ "$out" == *"udp-only-rule-on-tcp-dst: UDP-A 203.0.113.70:5300"* ]] && ok "protocol UDP rule matches UDP" || bad "udp proto rule ($out)"
+direct "protocol UDP rule does NOT match TCP to the same address" http://203.0.113.70/
+[[ "$out" == *"block: errno=1"* ]] && ok "UDP BLOCK rule: sendto fails with EPERM" || bad "udp block ($out)"
+[[ "$out" == *"http-proxy-udp: timeout"* ]] && ok "UDP rule pointing at an HTTP proxy goes direct (HTTP cannot carry UDP)" || bad "http udp ($out)"
+grep -q "UDP 203.0.113.110" "$PLOG" && bad "UDP leaked into the HTTP proxy" || ok "the HTTP proxy never saw that UDP"
+[[ "$out" == *"both: UDP-A 203.0.113.160:5300"* ]] && ok "protocol BOTH rule matches UDP" || bad "both/udp ($out)"
+tcpout=$(python3 - <<'PY'
+import socket
+s = socket.create_connection(("203.0.113.160", 80), timeout=5); s.sendall(b"GET / HTTP/1.0\r\n\r\n"); print(s.recv(300).decode())
+PY
+)
+[[ "$tcpout" == *"hello-from-A dst=203.0.113.160:80"* ]] && ok "protocol BOTH rule matches TCP too" || bad "both/tcp (got ${tcpout:0:100})"
+[[ "$out" == *"dns-port-53: UDP-A 203.0.113.140:53"* ]] && ok "DNS port rule applies when --dns-via-proxy is true (default)" || bad "dns true ($out)"
+
+echo "== DNS switch: --dns-via-proxy false makes port 53 always direct"
+kill -INT $PB_PID; wait $PB_PID 2>/dev/null
+start_pb --dns-via-proxy false --rule "python3*:203.0.113.140:53:UDP:PROXY=a" --rule "python3*:203.0.113.141:5353:UDP:PROXY=a"
+out=$(python3 - <<'PY'
+import socket
+def probe(dst, timeout=1.5):
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.settimeout(timeout)
+ try: s.sendto(b"p", dst); d, a = s.recvfrom(200); return d.decode()
+ except socket.timeout: return "timeout"
+print("dns:", probe(("203.0.113.140", 53)))
+print("other:", probe(("203.0.113.141", 5353)))
+PY
+)
+[[ "$out" == *"dns: timeout"* ]] && ok "port 53 stays direct with dns-via-proxy=false" || bad "dns false ($out)"
+[[ "$out" == *"other: UDP-A 203.0.113.141:5353"* ]] && ok "non-DNS UDP rule still proxied" || bad "other udp ($out)"
+
+echo; echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ] || { echo "---- proxy log"; cat "$PLOG"; echo "---- pb output"; tail -20 "$WORK/pb.out"; exit 1; }
diff --git a/Linux/tests/fake_dns.py b/Linux/tests/fake_dns.py
new file mode 100644
index 0000000..ab8e85a
--- /dev/null
+++ b/Linux/tests/fake_dns.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python3
+"""Tiny authoritative DNS server for ProxyBridge end-to-end tests (UDP + TCP, IPv4 A records and CNAME chains).
+
+usage: fake_dns.py <bind-ip> <logfile>
+Zone (everything else answers NXDOMAIN):
+ app.example.test A 192.0.2.77
+ blocked.example.test A 192.0.2.78
+ www.corp.test CNAME edge.cdnnet.test
+ edge.cdnnet.test A 192.0.2.79
+ tcp.example.test A 192.0.2.80
+ svc.byname.test A 192.0.2.81
+ plain.other.test A 192.0.2.82
+"""
+import socket, socketserver, struct, sys, threading
+
+ZONE = {
+ "app.example.test": [("A", "192.0.2.77")],
+ "blocked.example.test": [("A", "192.0.2.78")],
+ "www.corp.test": [("CNAME", "edge.cdnnet.test")],
+ "edge.cdnnet.test": [("A", "192.0.2.79")],
+ "tcp.example.test": [("A", "192.0.2.80")],
+ "svc.byname.test": [("A", "192.0.2.81")],
+ "plain.other.test": [("A", "192.0.2.82")],
+}
+LOG = open(sys.argv[2], "a", buffering=1)
+
+
+def enc_name(n):
+ return b"".join(bytes([len(p)]) + p.encode() for p in n.split(".")) + b"\0"
+
+
+def dec_name(m, off):
+ parts = []
+ while m[off]:
+ l = m[off]; parts.append(m[off + 1:off + 1 + l].decode()); off += 1 + l
+ return ".".join(parts), off + 1
+
+
+def answer(query, proto):
+ qid, flags, qd = struct.unpack("!HHH", query[:6])
+ name, off = dec_name(query, 12)
+ qtype = struct.unpack("!H", query[off:off + 2])[0]
+ LOG.write(f"{proto} {name} type={qtype}\n")
+ key = name.lower()
+ rrs, cur, seen = [], key, 0
+ while cur in ZONE and seen < 8:
+ seen += 1
+ for kind, val in ZONE[cur]:
+ if kind == "CNAME":
+ rd = enc_name(val)
+ rrs.append(enc_name(cur) + struct.pack("!HHIH", 5, 1, 300, len(rd)) + rd)
+ cur = val
+ elif qtype in (1, 255):
+ rrs.append(enc_name(cur) + struct.pack("!HHIH", 1, 1, 300, 4) + socket.inet_aton(val))
+ cur = None
+ else:
+ cur = None
+ if cur is None:
+ break
+ if cur is None:
+ break
+ rcode = 0 if rrs or key in ZONE else 3
+ hdr = struct.pack("!HHHHHH", qid, 0x8180 | rcode, 1, len(rrs), 0, 0)
+ return hdr + query[12:off + 4] + b"".join(rrs)
+
+
+class UDP(socketserver.BaseRequestHandler):
+ def handle(self):
+ data, sock = self.request
+ try:
+ sock.sendto(answer(data, "udp"), self.client_address)
+ except Exception as e:
+ LOG.write(f"error {e!r}\n")
+
+
+class TCP(socketserver.BaseRequestHandler):
+ def handle(self):
+ try:
+ while True:
+ hdr = self.request.recv(2)
+ if len(hdr) < 2:
+ return
+ n = struct.unpack("!H", hdr)[0]
+ data = b""
+ while len(data) < n:
+ chunk = self.request.recv(n - len(data))
+ if not chunk:
+ return
+ data += chunk
+ resp = answer(data, "tcp")
+ # deliver in two pieces to exercise stream reassembly in the relay
+ out = struct.pack("!H", len(resp)) + resp
+ self.request.sendall(out[:3]); self.request.sendall(out[3:])
+ except Exception as e:
+ LOG.write(f"error {e!r}\n")
+
+
+class TS(socketserver.ThreadingMixIn, socketserver.TCPServer):
+ allow_reuse_address = True
+ daemon_threads = True
+
+
+class US(socketserver.ThreadingMixIn, socketserver.UDPServer):
+ allow_reuse_address = True
+ daemon_threads = True
+
+
+ip = sys.argv[1]
+threading.Thread(target=TS((ip, 53), TCP).serve_forever, daemon=True).start()
+print("fake dns up on", ip, flush=True)
+US((ip, 53), UDP).serve_forever()
diff --git a/Linux/tests/fake_proxies.py b/Linux/tests/fake_proxies.py
new file mode 100644
index 0000000..ffce010
--- /dev/null
+++ b/Linux/tests/fake_proxies.py
@@ -0,0 +1,182 @@
+#!/usr/bin/env python3
+"""Fake upstream proxies for ProxyBridge end-to-end tests.
+
+Starts, on 127.0.0.1:
+ A SOCKS5 no-auth 19080 (also UDP ASSOCIATE)
+ B SOCKS5 user/pass 19081 (user "bob", pass "pw")
+ C HTTP CONNECT 19082
+ D HTTP CONNECT, Basic auth 19083 (user "bob", pass "pw"; anything else gets 407)
+Whatever destination a client asks for, the "origin" is a built-in responder:
+ TCP -> an HTTP/1.0 200 response whose body is "hello-from-<proxy> dst=<requested host:port>"
+ UDP -> "UDP-<proxy> <requested host:port> <payload>"
+Every request is appended to the log file given as argv[1] ("<proxy> TCP <host>:<port>" / "<proxy> UDP <host>:<port>").
+"""
+import asyncio, ipaddress, socket, struct, sys
+
+LOG = open(sys.argv[1], "a", buffering=1) if len(sys.argv) > 1 else sys.stdout
+
+
+def log(proxy, kind, dst):
+ LOG.write(f"{proxy} {kind} {dst}\n")
+
+
+async def origin(reader, writer, proxy, dst):
+ """Minimal HTTP/echo origin on an already-tunnelled stream."""
+ if dst.endswith(":8888"): # "hold" destination: keep the tunnel open until the client closes (scale tests)
+ try:
+ while await reader.read(65536):
+ pass
+ except Exception:
+ pass
+ writer.close()
+ return
+ try:
+ data = await asyncio.wait_for(reader.read(65536), 5)
+ except Exception:
+ data = b""
+ if data.startswith((b"GET", b"HEAD", b"POST")):
+ body = f"hello-from-{proxy} dst={dst}\n".encode()
+ writer.write(b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\nConnection: close\r\n\r\n" % len(body) + body)
+ else:
+ writer.write(f"echo-{proxy}:".encode() + data)
+ try:
+ await writer.drain()
+ except Exception:
+ pass
+ writer.close()
+
+
+def addr_str(atyp, raw):
+ if atyp == 1:
+ return str(ipaddress.IPv4Address(raw))
+ if atyp == 4:
+ return str(ipaddress.IPv6Address(raw))
+ return raw.decode()
+
+
+async def read_addr(reader):
+ atyp = (await reader.readexactly(1))[0]
+ if atyp == 1:
+ raw = await reader.readexactly(4)
+ elif atyp == 4:
+ raw = await reader.readexactly(16)
+ else:
+ n = (await reader.readexactly(1))[0]
+ raw = await reader.readexactly(n)
+ port = struct.unpack("!H", await reader.readexactly(2))[0]
+ return atyp, raw, port
+
+
+def socks_handler(name, auth):
+ async def handle(reader, writer):
+ try:
+ ver, n = await reader.readexactly(2)
+ methods = await reader.readexactly(n)
+ if auth:
+ if 2 not in methods:
+ writer.write(b"\x05\xff"); await writer.drain(); writer.close(); return
+ writer.write(b"\x05\x02"); await writer.drain()
+ v, ul = await reader.readexactly(2)
+ user = await reader.readexactly(ul)
+ pl = (await reader.readexactly(1))[0]
+ pw = await reader.readexactly(pl)
+ ok = user == b"bob" and pw == b"pw"
+ writer.write(b"\x01" + (b"\x00" if ok else b"\x01")); await writer.drain()
+ if not ok:
+ log(name, "AUTHFAIL", user.decode()); writer.close(); return
+ else:
+ writer.write(b"\x05\x00"); await writer.drain()
+ ver, cmd, _rsv = await reader.readexactly(3)
+ atyp, raw, port = await read_addr(reader)
+ dst = f"{addr_str(atyp, raw)}:{port}"
+ if cmd == 1:
+ log(name, "TCP", dst)
+ writer.write(b"\x05\x00\x00\x01" + socket.inet_aton("127.0.0.1") + struct.pack("!H", 0)); await writer.drain()
+ await origin(reader, writer, name, dst)
+ elif cmd == 3:
+ loop = asyncio.get_running_loop()
+ transport, _ = await loop.create_datagram_endpoint(lambda: UdpRelay(name), local_addr=("127.0.0.1", 0))
+ bport = transport.get_extra_info("sockname")[1]
+ writer.write(b"\x05\x00\x00\x01" + socket.inet_aton("127.0.0.1") + struct.pack("!H", bport)); await writer.drain()
+ try:
+ while await reader.read(1024): # association lives as long as the TCP control connection
+ pass
+ finally:
+ transport.close()
+ else:
+ writer.write(b"\x05\x07\x00\x01" + b"\0" * 6); await writer.drain()
+ except Exception as e:
+ log(name, "ERR", repr(e))
+ finally:
+ try:
+ writer.close()
+ except Exception:
+ pass
+ return handle
+
+
+class UdpRelay(asyncio.DatagramProtocol):
+ def __init__(self, name):
+ self.name = name
+
+ def connection_made(self, transport):
+ self.t = transport
+
+ def datagram_received(self, data, addr):
+ if len(data) < 10 or data[2] != 0:
+ return
+ atyp = data[3]
+ if atyp == 1:
+ raw, off = data[4:8], 8
+ elif atyp == 4:
+ raw, off = data[4:20], 20
+ else:
+ n = data[4]; raw, off = data[5:5 + n], 5 + n
+ port = struct.unpack("!H", data[off:off + 2])[0]
+ payload = data[off + 2:]
+ dst = f"{addr_str(atyp, raw)}:{port}"
+ log(self.name, "UDP", dst)
+ reply = f"UDP-{self.name} {dst} ".encode() + payload
+ self.t.sendto(data[:off + 2] + reply, addr)
+
+
+import base64
+
+
+def http_connect_handler(name, need_auth):
+ async def handler(reader, writer):
+ await http_connect(reader, writer, name, need_auth)
+ return handler
+
+
+async def http_connect(reader, writer, name="C", need_auth=False):
+ try:
+ head = await reader.readuntil(b"\r\n\r\n")
+ first = head.split(b"\r\n")[0].decode()
+ if need_auth:
+ want = b"Proxy-Authorization: Basic " + base64.b64encode(b"bob:pw")
+ if want.lower() not in head.lower():
+ log(name, "AUTHFAIL", first)
+ writer.write(b"HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm=\"t\"\r\nContent-Length: 0\r\n\r\n")
+ await writer.drain(); writer.close(); return
+ if not first.startswith("CONNECT "):
+ writer.write(b"HTTP/1.1 405 Method Not Allowed\r\n\r\n"); await writer.drain(); writer.close(); return
+ dst = first.split()[1]
+ log(name, "TCP", dst)
+ writer.write(b"HTTP/1.1 200 Connection established\r\n\r\n"); await writer.drain()
+ await origin(reader, writer, name, dst)
+ except Exception as e:
+ log(name, "ERR", repr(e))
+ finally:
+ writer.close()
+
+
+async def main():
+ await asyncio.start_server(socks_handler("A", False), "127.0.0.1", 19080)
+ await asyncio.start_server(socks_handler("B", True), "127.0.0.1", 19081)
+ await asyncio.start_server(http_connect_handler("C", False), "127.0.0.1", 19082)
+ await asyncio.start_server(http_connect_handler("D", True), "127.0.0.1", 19083)
+ print("fake proxies up: A=socks5:19080 B=socks5(bob:pw):19081 C=http:19082", flush=True)
+ await asyncio.Event().wait()
+
+asyncio.run(main())
diff --git a/Linux/tests/gui_headless.sh b/Linux/tests/gui_headless.sh
new file mode 100755
index 0000000..ae4c1d2
--- /dev/null
+++ b/Linux/tests/gui_headless.sh
@@ -0,0 +1,86 @@
+#!/bin/bash
+# Runs the real GTK GUI headlessly (GTK Broadway backend, no window on your desktop) against the real engine:
+# config loading (profiles, proxies, rules incl. domain rules) -> engine start -> real traffic -> clean shutdown.
+# Needs root, broadwayd, dig, curl, and a built GUI: pass the path of ProxyBridgeGUI and of the directory holding libproxybridge.so.
+# sudo tests/gui_headless.sh <ProxyBridgeGUI> <libdir>
+set -u
+GUI=${1:?path to ProxyBridgeGUI}; LIBDIR=${2:?dir with libproxybridge.so}
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+WORK="$(mktemp -d)"; PLOG="$WORK/proxy.log"; DLOG="$WORK/dns.log"; : > "$PLOG"; : > "$DLOG"
+PASS=0; FAIL=0; DNSIP=10.77.0.4
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+has() { [[ "$2" == *"$3"* ]] && ok "$1" || bad "$1 (got: ${2:0:160})"; }
+cleanup() { kill $GUI_PID $FAKE $DNSP $BW 2>/dev/null; wait 2>/dev/null; ip addr del $DNSIP/32 dev lo 2>/dev/null; rm -rf "$WORK"; }
+trap cleanup EXIT
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+ip addr add $DNSIP/32 dev lo 2>/dev/null
+python3 "$HERE/fake_proxies.py" "$PLOG" >/dev/null 2>&1 & FAKE=$!
+python3 "$HERE/fake_dns.py" $DNSIP "$DLOG" >/dev/null 2>&1 & DNSP=$!
+broadwayd :9 >/dev/null 2>&1 & BW=$!
+sleep 1.5
+
+# profile "Default": proxy a (default) + b; "Alt": curl goes through b instead
+write_cfg() { # active-profile
+mkdir -p "$WORK/cfg"
+cat > "$WORK/cfg/config.ini" <<CFG
+[SETTINGS]
+activeProfile=$1
+logging=1
+dns=1
+[PROFILE:Default]
+defaultProxy=a
+[PROXIES]
+a|1|127.0.0.1|19080||
+b|1|127.0.0.1|19081|bob|pw
+[RULES]
+1|0|0|1|curl|192.0.2.0/26|*|a
+2|0|0|1|curl|198.51.100.0/24|*|b
+3|0|2|1|curl|203.0.114.0/24|*|
+4|0|0|1|*|*.example.test|*|b
+5|0|0|0|curl|203.0.113.0/24|*|a
+[PROFILE:Alt]
+defaultProxy=b
+[PROXIES]
+b|1|127.0.0.1|19081|bob|pw
+[RULES]
+1|0|0|1|curl|192.0.2.0/26|*|b
+CFG
+chmod 600 "$WORK/cfg/config.ini"
+}
+
+run_gui() { # active profile
+ write_cfg "$1"
+ GDK_BACKEND=broadway BROADWAY_DISPLAY=:9 PROXYBRIDGE_CONFIG_DIR="$WORK/cfg" LD_LIBRARY_PATH="$LIBDIR" "$GUI" > "$WORK/gui.out" 2>&1 & GUI_PID=$!
+ for _ in $(seq 60); do bpftool prog show 2>/dev/null | grep -q pb_connect4 && break; kill -0 $GUI_PID 2>/dev/null || break; sleep 0.25; done
+ sleep 1
+}
+stop_gui() {
+ kill -TERM $GUI_PID 2>/dev/null
+ for _ in $(seq 40); do kill -0 $GUI_PID 2>/dev/null || break; sleep 0.25; done
+ if kill -0 $GUI_PID 2>/dev/null; then kill -KILL $GUI_PID; bad "GUI did not exit on SIGTERM"; else wait $GUI_PID; rc=$?; [ "$rc" = 0 ] && ok "GUI exits cleanly on SIGTERM (rc=0)" || bad "GUI exit code $rc"; fi
+}
+
+echo "== profile Default"
+run_gui Default
+kill -0 $GUI_PID 2>/dev/null && ok "GUI started under Broadway" || { bad "GUI died: $(head -5 "$WORK/gui.out")"; }
+bpftool prog show 2>/dev/null | grep -q pb_connect4 && ok "engine started by the GUI (eBPF programs attached)" || bad "no eBPF programs"
+out=$(curl -s -m 5 http://192.0.2.7/); has "rule 1 from the config file: curl -> proxy a" "$out" "hello-from-A dst=192.0.2.7:80"
+out=$(curl -s -m 5 http://198.51.100.7/); has "rule 2: curl -> proxy b (with credentials from the config)" "$out" "hello-from-B dst=198.51.100.7:80"
+out=$(curl -s -m 5 http://203.0.114.7/ 2>&1; echo "rc=$?"); has "rule 3: BLOCK" "$out" "rc=7"
+out=$(curl -s -m 2 http://203.0.113.7/ 2>&1; echo "rc=$?"); [[ "$out" != *hello-from* ]] && ok "disabled rule 5 is not applied" || bad "disabled rule applied"
+ip4=$(dig @$DNSIP app.example.test +short +time=3 +tries=1 | head -1)
+out=$(curl -s -m 5 http://$ip4/); has "domain rule from the config (*.example.test -> b) after a real DNS lookup" "$out" "hello-from-B dst=192.0.2.77:80"
+stop_gui
+bpftool prog show 2>/dev/null | grep -q pb_connect && bad "BPF programs left after GUI exit" || ok "programs detached after GUI exit"
+
+echo "== profile Alt (same GUI, different active profile)"
+run_gui Alt
+out=$(curl -s -m 5 http://192.0.2.7/); has "Alt profile: same rule now goes through proxy b" "$out" "hello-from-B dst=192.0.2.7:80"
+out=$(curl -s -m 2 http://198.51.100.7/ 2>&1; echo "rc=$?"); [[ "$out" != *hello-from* ]] && ok "Alt profile does not apply rules of the Default profile" || bad "Default rules leaked into Alt"
+stop_gui
+grep -q "^\[PROFILE:Default\]" "$WORK/cfg/config.ini" && grep -q "^\[PROFILE:Alt\]" "$WORK/cfg/config.ini" && ok "both profiles preserved in the config after the GUI saved it" || bad "profiles lost from the config"
+[ "$(stat -c %a "$WORK/cfg/config.ini")" = 600 ] && ok "config file mode is 0600" || bad "config file mode"
+
+echo; echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ] || { echo "---- gui output"; cat "$WORK/gui.out"; echo "---- config"; cat "$WORK/cfg/config.ini"; exit 1; }
diff --git a/Linux/tests/hookbench.c b/Linux/tests/hookbench.c
new file mode 100644
index 0000000..3add3d0
--- /dev/null
+++ b/Linux/tests/hookbench.c
@@ -0,0 +1,37 @@
+// hookbench tcp|udp <ip> <port> <n> : measures connect() latency (tcp) or sendto() rate + loopback delivery (udp) to a local server it starts itself.
+#include <arpa/inet.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+#include <sys/socket.h>
+static double now_us(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e6 + t.tv_nsec / 1e3; }
+static const char *ip; static int port, tcp;
+static void *srv(void *a)
+{
+ (void)a;
+ int s = socket(AF_INET, tcp ? SOCK_STREAM : SOCK_DGRAM, 0), one = 1; setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
+ struct sockaddr_in sa = { .sin_family = AF_INET, .sin_port = htons(port) }; inet_pton(AF_INET, ip, &sa.sin_addr);
+ if (bind(s, (void *)&sa, sizeof sa)) { perror("bind"); exit(1); }
+ if (tcp) { listen(s, 4096); for (;;) { int c = accept(s, 0, 0); if (c >= 0) close(c); } }
+ char b[2048]; for (;;) recv(s, b, sizeof b, 0);
+}
+int main(int argc, char **argv)
+{
+ tcp = !strcmp(argv[1], "tcp"); ip = argv[2]; port = atoi(argv[3]); int n = atoi(argv[4]);
+ pthread_t t; pthread_create(&t, 0, srv, 0); usleep(200000);
+ struct sockaddr_in sa = { .sin_family = AF_INET, .sin_port = htons(port) }; inet_pton(AF_INET, ip, &sa.sin_addr);
+ if (tcp) {
+ double sum = 0; int ok = 0;
+ for (int i = 0; i < n; i++) { int s = socket(AF_INET, SOCK_STREAM, 0); double a = now_us(); int r = connect(s, (void *)&sa, sizeof sa); sum += now_us() - a; ok += !r; close(s); }
+ printf("tcp connect %s:%d ok=%d/%d avg=%.2f us\n", ip, port, ok, n, sum / n);
+ } else {
+ int s = socket(AF_INET, SOCK_DGRAM, 0); char buf[64] = "x"; double a = now_us();
+ for (int i = 0; i < n; i++) sendto(s, buf, 32, 0, (void *)&sa, sizeof sa);
+ double d = now_us() - a;
+ printf("udp sendto %s:%d n=%d %.3f us/call %.0f kpps\n", ip, port, n, d / n, n / d * 1e3);
+ }
+ return 0;
+}
diff --git a/Linux/tests/hookbench.sh b/Linux/tests/hookbench.sh
new file mode 100755
index 0000000..ea3affc
--- /dev/null
+++ b/Linux/tests/hookbench.sh
@@ -0,0 +1,16 @@
+#!/bin/bash
+# Overhead of the eBPF hooks on DIRECT traffic. Needs root. sudo tests/hookbench.sh <path-to-hookbench-binary>
+HB=${1:?path to hookbench}; ROOT="$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)")"
+export LD_LIBRARY_PATH="$ROOT/src"
+IP=10.77.0.1 # alias on lo: local like loopback, but not caught by the implicit-loopback bypass
+ip addr add $IP/32 dev lo 2>/dev/null
+trap 'ip addr del $IP/32 dev lo 2>/dev/null' EXIT
+run() { for i in 1 2 3; do $HB tcp $IP 19555 20000; done; for i in 1 2 3; do $HB udp $IP 19556 1000000; done; }
+echo "### A: ProxyBridge not running"; run
+start() { stdbuf -oL "$ROOT/cli/ProxyBridge" "$@" > /tmp/pbbench.out 2>&1 & PB=$!; for _ in $(seq 40); do grep -q "ProxyBridge started" /tmp/pbbench.out && break; sleep 0.25; done; }
+echo "### B: running, 20 rules for other programs (this binary: empty class -> immediate direct)"
+start $(for i in $(seq 20); do echo --rule "someapp$i:*:*:BOTH:PROXY"; done); run; kill -INT $PB; wait $PB 2>/dev/null
+echo "### C: running, rules that match this binary but not this destination (full rule evaluation, then direct)"
+start --rule "hookbench:192.0.2.0/24:*:BOTH:PROXY" --rule "hookbench:198.51.100.0/24:80;443;8000-9000:BOTH:PROXY" --rule "hookbench:203.0.113.0/24:*:BOTH:BLOCK"; run; kill -INT $PB; wait $PB 2>/dev/null
+echo "### D: running, wildcard process rule with 4 destination ranges (every process evaluated)"
+start --rule "*:192.0.2.0/24;198.51.100.0/24;203.0.113.0/24;100.64.0.0/10:*:BOTH:PROXY"; run; kill -INT $PB; wait $PB 2>/dev/null
diff --git a/Linux/tests/scale.sh b/Linux/tests/scale.sh
new file mode 100755
index 0000000..55a5cc0
--- /dev/null
+++ b/Linux/tests/scale.sh
@@ -0,0 +1,54 @@
+#!/bin/bash
+# Holds N concurrent proxied TCP connections open through the full stack and reports ProxyBridge memory / CPU.
+# sudo tests/scale.sh [N]
+set -u
+N=${1:-10000}
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+export LD_LIBRARY_PATH="$ROOT/src"
+ulimit -n 200000
+WORK=$(mktemp -d); trap 'kill $FAKE $PB 2>/dev/null; wait 2>/dev/null; rm -rf $WORK' EXIT
+python3 "$HERE/fake_proxies.py" $WORK/log >/dev/null 2>&1 & FAKE=$!
+sleep 1
+stdbuf -oL "$ROOT/cli/ProxyBridge" --proxy a=socks5://127.0.0.1:19080 --rule "python3*:192.0.2.0/24:*:TCP:PROXY=a" > $WORK/pb.out 2>&1 & PB=$!
+for _ in $(seq 40); do grep -q "ProxyBridge started" $WORK/pb.out && break; sleep 0.25; done
+rss() { awk '/VmRSS/{print $2}' /proc/$PB/status; }
+maps_kb() { bpftool map show 2>/dev/null | grep -oE 'memlock [0-9]+' | awk '{s+=$2} END{printf "%d", s/1024}'; }
+echo "baseline: ProxyBridge RSS=$(( $(rss) / 1024 )) MB BPF maps=$(maps_kb) KB threads=$(ls /proc/$PB/task | wc -l)"
+CPU0=$(awk '{print $14+$15}' /proc/$PB/stat)
+rm -f /tmp/pb_scale_ready /tmp/pb_scale_go
+python3 - $N > $WORK/client.out <<'PY' &
+import asyncio, sys, time, resource, os
+n = int(sys.argv[1])
+resource.setrlimit(resource.RLIMIT_NOFILE, (200000, 200000))
+async def main():
+ t0 = time.time(); conns = []; fails = 0
+ sem = asyncio.Semaphore(500)
+ async def one(i):
+ nonlocal fails
+ async with sem:
+ try:
+ r, w = await asyncio.wait_for(asyncio.open_connection("192.0.2.%d" % (1 + i % 250), 8888), 30)
+ w.write(b"x"); await w.drain()
+ conns.append((r, w))
+ except Exception:
+ fails += 1
+ await asyncio.gather(*(one(i) for i in range(n)))
+ dt = time.time() - t0
+ print(f"client: {len(conns)} established, {fails} failed, {dt:.1f}s ({len(conns)/dt:.0f} conn/s)", flush=True)
+ open("/tmp/pb_scale_ready", "w").write("1")
+ while not os.path.exists("/tmp/pb_scale_go"):
+ await asyncio.sleep(0.2)
+ for r, w in conns: w.close()
+asyncio.run(main())
+PY
+CL=$!
+for _ in $(seq 300); do [ -e /tmp/pb_scale_ready ] && break; sleep 1; done
+sleep 2
+cat $WORK/client.out
+CPU1=$(awk '{print $14+$15}' /proc/$PB/stat)
+echo "under load: ProxyBridge RSS=$(( $(rss) / 1024 )) MB BPF maps=$(maps_kb) KB threads=$(ls /proc/$PB/task | wc -l) fds=$(ls /proc/$PB/fd | wc -l)"
+echo "ProxyBridge CPU while opening: $(( (CPU1 - CPU0) * 1000 / $(getconf CLK_TCK) )) ms"
+echo "kernel socket memory (TCP): $(grep '^TCP:' /proc/net/sockstat)"
+touch /tmp/pb_scale_go; wait $CL 2>/dev/null; sleep 3
+echo "after close: ProxyBridge RSS=$(( $(rss) / 1024 )) MB fds=$(ls /proc/$PB/fd | wc -l)"
+rm -f /tmp/pb_scale_ready /tmp/pb_scale_go
diff --git a/Linux/tests/thrbench.c b/Linux/tests/thrbench.c
new file mode 100644
index 0000000..b033442
--- /dev/null
+++ b/Linux/tests/thrbench.c
@@ -0,0 +1,93 @@
+// Throughput benchmark: compares an application talking to a SOCKS5 proxy itself ("socks") against the same application being
+// transparently redirected by ProxyBridge ("transparent"). The bundled proxy accepts any CONNECT and forwards to the local sink.
+// thrbench proxy <port> <sink_port> SOCKS5 (no auth) forwarder, splice() based
+// thrbench sink <port> discards data, replies with the byte count at EOF
+// thrbench socks <proxy_port> <ip> <port> <MB> [conns] client doing the SOCKS5 handshake itself
+// thrbench direct <ip> <port> <MB> [conns] client connecting straight to the sink
+#define _GNU_SOURCE
+#include <arpa/inet.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+#include <sys/socket.h>
+static double now_s(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec + t.tv_nsec / 1e9; }
+static struct sockaddr_in addr_of(const char *ip, int port) { struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(port) }; inet_pton(AF_INET, ip, &a.sin_addr); return a; }
+static int listener(int port)
+{
+ int s = socket(AF_INET, SOCK_STREAM, 0), one = 1; setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
+ struct sockaddr_in a = addr_of("127.0.0.1", port);
+ if (bind(s, (void *)&a, sizeof a) || listen(s, 1024)) { perror("listen"); exit(1); }
+ return s;
+}
+static int read_full(int fd, void *b, size_t n) { size_t o = 0; while (o < n) { ssize_t r = read(fd, (char *)b + o, n - o); if (r <= 0) return -1; o += (size_t)r; } return 0; }
+
+static void *sink_conn(void *a)
+{
+ int c = (int)(long)a; static __thread char b[1 << 20]; unsigned long long total = 0; ssize_t n;
+ while ((n = read(c, b, sizeof b)) > 0) total += (unsigned long long)n;
+ write(c, &total, sizeof total); close(c); return NULL;
+}
+static void run_sink(int port) { int l = listener(port); for (;;) { int c = accept(l, 0, 0); pthread_t t; pthread_create(&t, 0, sink_conn, (void *)(long)c); pthread_detach(t); } }
+
+struct pair { int a, b; };
+static void *pipe_dir(void *arg)
+{
+ struct pair *p = arg; int pp[2]; pipe(pp); fcntl(pp[0], F_SETPIPE_SZ, 1 << 20);
+ for (;;) {
+ ssize_t n = splice(p->a, 0, pp[1], 0, 1 << 20, SPLICE_F_MOVE);
+ if (n <= 0) break;
+ while (n > 0) { ssize_t w = splice(pp[0], 0, p->b, 0, (size_t)n, SPLICE_F_MOVE); if (w <= 0) goto out; n -= w; }
+ }
+out: shutdown(p->b, SHUT_WR); close(pp[0]); close(pp[1]); return NULL;
+}
+static void *proxy_conn(void *arg)
+{
+ int c = (int)(long)arg; unsigned char b[512];
+ if (read_full(c, b, 2) || read_full(c, b + 2, b[1])) goto done;
+ write(c, "\x05\x00", 2);
+ if (read_full(c, b, 4)) goto done;
+ if (b[3] == 1) read_full(c, b, 6); else if (b[3] == 4) read_full(c, b, 18); else { unsigned char l; read_full(c, &l, 1); read_full(c, b, l + 2u); }
+ extern int g_sink; int u = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in a = addr_of("127.0.0.1", g_sink);
+ if (connect(u, (void *)&a, sizeof a)) goto done;
+ write(c, "\x05\x00\x00\x01\x7f\x00\x00\x01\x00\x00", 10);
+ struct pair p1 = { c, u }, p2 = { u, c }; pthread_t t1, t2;
+ pthread_create(&t1, 0, pipe_dir, &p1); pthread_create(&t2, 0, pipe_dir, &p2); pthread_join(t1, 0); pthread_join(t2, 0); close(u);
+done: close(c); return NULL;
+}
+int g_sink;
+static void run_proxy(int port, int sink) { g_sink = sink; int l = listener(port); for (;;) { int c = accept(l, 0, 0); pthread_t t; pthread_create(&t, 0, proxy_conn, (void *)(long)c); pthread_detach(t); } }
+
+struct cl { const char *ip; int port, proxy_port; long mb; double secs; int ok; };
+static void *client(void *arg)
+{
+ struct cl *c = arg; int s = socket(AF_INET, SOCK_STREAM, 0);
+ struct sockaddr_in a = c->proxy_port ? addr_of("127.0.0.1", c->proxy_port) : addr_of(c->ip, c->port);
+ if (connect(s, (void *)&a, sizeof a)) { perror("connect"); return NULL; }
+ if (c->proxy_port) { // SOCKS5 CONNECT done by the application itself
+ unsigned char b[32] = { 5, 1, 0 }; write(s, b, 3); read_full(s, b, 2);
+ unsigned char req[10] = { 5, 1, 0, 1 }; inet_pton(AF_INET, c->ip, req + 4); req[8] = (unsigned char)(c->port >> 8); req[9] = (unsigned char)c->port;
+ write(s, req, 10); if (read_full(s, b, 10)) return NULL;
+ }
+ static __thread char buf[1 << 20]; memset(buf, 'x', sizeof buf);
+ double t0 = now_s();
+ for (long i = 0; i < c->mb; i++) if (write(s, buf, sizeof buf) <= 0) return NULL;
+ shutdown(s, SHUT_WR);
+ unsigned long long total = 0; read_full(s, &total, sizeof total);
+ c->secs = now_s() - t0; c->ok = total == (unsigned long long)c->mb << 20; close(s); return NULL;
+}
+int main(int argc, char **argv)
+{
+ if (!strcmp(argv[1], "sink")) run_sink(atoi(argv[2]));
+ if (!strcmp(argv[1], "proxy")) run_proxy(atoi(argv[2]), atoi(argv[3]));
+ int socks = !strcmp(argv[1], "socks"), ai = socks ? 3 : 2;
+ int pp = socks ? atoi(argv[2]) : 0; const char *ip = argv[ai]; int port = atoi(argv[ai + 1]); long mb = atol(argv[ai + 2]); int n = argc > ai + 3 ? atoi(argv[ai + 3]) : 1;
+ struct cl *c = calloc((size_t)n, sizeof *c); pthread_t *t = calloc((size_t)n, sizeof *t); double t0 = now_s();
+ for (int i = 0; i < n; i++) { c[i] = (struct cl){ ip, port, pp, mb }; pthread_create(&t[i], 0, client, &c[i]); }
+ int ok = 0; for (int i = 0; i < n; i++) { pthread_join(t[i], 0); ok += c[i].ok; }
+ double dt = now_s() - t0; printf("%-11s conns=%d ok=%d %ld MB each total %.0f MB in %.2fs = %.0f MB/s\n", argv[1], n, ok, mb, (double)n * (double)mb, dt, (double)n * (double)mb / dt);
+ return 0;
+}
diff --git a/Linux/tests/thrbench.sh b/Linux/tests/thrbench.sh
new file mode 100755
index 0000000..e5d35bc
--- /dev/null
+++ b/Linux/tests/thrbench.sh
@@ -0,0 +1,21 @@
+#!/bin/bash
+# Throughput through ProxyBridge vs the same application speaking SOCKS5 itself. Needs root.
+# sudo tests/thrbench.sh <thrbench-binary> (binary must be named thrbench so process rules can match it)
+TB=${1:?path to thrbench binary named "thrbench"}; ROOT="$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)")"
+export LD_LIBRARY_PATH="$ROOT/src"
+MB=${MB:-2048}
+$TB sink 19990 & SINK=$!; $TB proxy 19991 19990 & PROXY=$!
+trap 'kill $SINK $PROXY $PB 2>/dev/null' EXIT
+sleep 0.5
+echo "== baselines (ProxyBridge not running)"
+for i in 1 2 3; do $TB direct 127.0.0.1 19990 $MB 1; done
+for i in 1 2 3; do $TB socks 19991 192.0.2.7 9999 $MB 1; done
+for i in 1 2; do $TB socks 19991 192.0.2.7 9999 $((MB/8)) 8; done
+stdbuf -oL "$ROOT/cli/ProxyBridge" --proxy a=socks5://127.0.0.1:19991 --rule "thrbench:192.0.2.0/24:*:TCP:PROXY=a" > /tmp/thr_pb.out 2>&1 & PB=$!
+for _ in $(seq 40); do grep -q "ProxyBridge started" /tmp/thr_pb.out && break; sleep 0.25; done
+echo "== through ProxyBridge (app connects to 192.0.2.7:9999, transparently redirected)"
+for i in 1 2 3; do $TB direct 192.0.2.7 9999 $MB 1; done
+for i in 1 2; do $TB direct 192.0.2.7 9999 $((MB/8)) 8; done
+echo "== direct traffic while ProxyBridge is running (127.0.0.1 is never redirected; non-matching process)"
+for i in 1 2 3; do $TB direct 127.0.0.1 19990 $MB 1; done
+kill -INT $PB; wait $PB 2>/dev/null