Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic
C ccybersecurityhttp3httpproxylinuxlinux-proxymacosmacos-appmacos-proxyproxifierproxifier-alternativeproxyclienttcpthick-clientudpwindivertwindows
fix(linux): bind the relay hand-off to the client address, exempt local proxies, slim the datapath
anof-cyber5cedb7b22f10
diff --git a/Linux/src/Makefile b/Linux/src/Makefileindex 6c1b482..7c9d5e8 100644--- a/Linux/src/Makefile+++ b/Linux/src/Makefile@@ -7,6 +7,9 @@ MULTIARCH := $(shell $(CC) -print-multiarch)# build.sh points it at a temporary directory; a plain `make` builds in place for quick development.BUILD_DIR ?= .+# EXTRA_CFLAGS / EXTRA_LDFLAGS: e.g. -fsanitize=address,undefined (use STRIP_FLAG= to keep symbols for the report).+STRIP_FLAG ?= -s+CFLAGS = -Wall -Wextra -O2 -fPIC -D_GNU_SOURCE -I$(BUILD_DIR) \-fstack-protector-strong \-D_FORTIFY_SOURCE=2 \@@ -15,11 +18,11 @@ CFLAGS = -Wall -Wextra -O2 -fPIC -D_GNU_SOURCE -I$(BUILD_DIR) \-Werror=format-security \-fno-strict-overflow \-fno-delete-null-pointer-checks \- -fwrapv-LDFLAGS = -shared -Wl,-z,relro,-z,now -Wl,-z,noexecstack -s+ -fwrapv -fvisibility=hidden -ffunction-sections -fdata-sections $(EXTRA_CFLAGS)+LDFLAGS = -shared -Wl,-z,relro,-z,now -Wl,-z,noexecstack -Wl,--gc-sections $(STRIP_FLAG) $(EXTRA_LDFLAGS)LIBS = -lpthread -lbpf-SOURCES = ProxyBridge.c pb_rules.c pb_dns.c pb_bpf.c pb_relay.c+SOURCES = ProxyBridge.c pb_rules.c pb_dns.c pb_proc.c pb_bpf.c pb_relay.cOBJECTS = $(addprefix $(BUILD_DIR)/,$(SOURCES:.c=.o))TARGET = $(BUILD_DIR)/libproxybridge.soBPF_OBJ = $(BUILD_DIR)/proxybridge.bpf.o@@ -34,7 +37,7 @@ $(BPF_OBJ): bpf/proxybridge.bpf.c bpf/pb_bpf_shared.h | $(BUILD_DIR)$(CLANG) -O2 -g -target bpf -D__BPF__ -I/usr/include/$(MULTIARCH) -c $< -o $@$(SKEL): $(BPF_OBJ)- $(BPFTOOL) gen skeleton $< > $@+ $(BPFTOOL) gen skeleton $< > [email protected] && mv [email protected] $@$(BUILD_DIR)/pb_bpf.o: $(SKEL)diff --git a/Linux/src/ProxyBridge.c b/Linux/src/ProxyBridge.cindex 2cbb5a9..2d19db1 100644--- a/Linux/src/ProxyBridge.c+++ b/Linux/src/ProxyBridge.c@@ -1,33 +1,45 @@#include <arpa/inet.h>#include <ctype.h>-#include <errno.h>+#include <netdb.h>#include <pthread.h>#include <stdarg.h>+#include <stdatomic.h>#include <stdio.h>#include <stdlib.h>#include <string.h>+#include <sys/stat.h>+#include <time.h>#include <unistd.h>#include "ProxyBridge.h"-#include <stdatomic.h>#include "pb_bpf.h"#include "pb_dns.h"#include "pb_internal.h"+#include "pb_proc.h"#include "pb_rules.h"#define MAX_PROXIES 255+#define MAINT_PERIOD_S 2+#define HOSTS_PATH "/etc/hosts"static struct {pthread_rwlock_t lock;struct pb_rule *rules; size_t nrules, caprules;+ struct pb_rule_view *views; size_t nviews;struct pb_proxy proxies[MAX_PROXIES]; size_t nproxies;uint32_t next_rule_id, next_proxy_id, default_proxy;- bool dns_via_proxy, traffic_logging, running;- atomic_bool has_domain_rules;+ bool running;+ atomic_bool dns_via_proxy, traffic_logging, has_domain_rules;+ pthread_t maint;+ bool maint_started, maint_stop, maint_kick;+ pthread_mutex_t maint_mu;+ pthread_cond_t maint_cv;+ uint64_t warned[16]; size_t nwarned;LogCallback log_cb;ConnectionCallback conn_cb;-} G = { .lock = PTHREAD_RWLOCK_INITIALIZER, .next_rule_id = 1, .next_proxy_id = 1, .dns_via_proxy = true };+} G = { .lock = PTHREAD_RWLOCK_INITIALIZER, .maint_mu = PTHREAD_MUTEX_INITIALIZER, .maint_cv = PTHREAD_COND_INITIALIZER,+ .next_rule_id = 1, .next_proxy_id = 1, .dns_via_proxy = true };-static pthread_mutex_t cb_lock = PTHREAD_MUTEX_INITIALIZER; // serialises user callbacks+static pthread_mutex_t cb_lock = PTHREAD_MUTEX_INITIALIZER;static void set_err(char *err, size_t n, const char *fmt, ...) __attribute__((format(printf, 3, 4)));static void set_err(char *err, size_t n, const char *fmt, ...)@@ -39,7 +51,6 @@ static void set_err(char *err, size_t n, const char *fmt, ...)va_end(ap);}-// ---- logging -----------------------------------------------------------------------------------------------------------void pb_core_log(const char *fmt, ...){char buf[1024];@@ -48,73 +59,75 @@ void pb_core_log(const char *fmt, ...)vsnprintf(buf, sizeof buf, fmt, ap);va_end(ap);pthread_mutex_lock(&cb_lock);- LogCallback cb = G.log_cb;- if (cb) cb(buf);+ if (G.log_cb) G.log_cb(buf);pthread_mutex_unlock(&cb_lock);}-static const char *proxy_type_name(ProxyType t) { return t == PROXY_TYPE_SOCKS5 ? "SOCKS5" : "HTTP"; }+static void strip_deleted(char *p)+{+ static const char suffix[] = " (deleted)";+ size_t n = strlen(p), s = sizeof suffix - 1;+ if (n > s && !strcmp(p + n - s, suffix)) p[n - s] = 0;+}-static void proc_name_of(uint32_t pid, const char *comm, char *out, size_t n)+static bool exe_path_of_pid(uint32_t pid, char *out, size_t n){- char lnk[64], path[512];- snprintf(lnk, sizeof lnk, "/proc/%u/exe", pid);- ssize_t r = readlink(lnk, path, sizeof path - 1);- if (r > 0) {- path[r] = 0;- const char *b = strrchr(path, '/');- snprintf(out, n, "%s", b ? b + 1 : path);- size_t l = strlen(out);- if (l > 10 && !strcmp(out + l - 10, " (deleted)")) out[l - 10] = 0;- return;- }- snprintf(out, n, "%s", comm && *comm ? comm : "unknown");+ char link[64];+ snprintf(link, sizeof link, "/proc/%u/exe", pid);+ ssize_t r = readlink(link, out, n - 1);+ if (r <= 0) { out[0] = 0; return false; }+ out[r] = 0;+ strip_deleted(out);+ return true;}static void emit_connection(uint32_t pid, const char *comm, int family, const uint8_t addr[16], uint16_t port, int action, uint32_t proxy_id){- if (!G.traffic_logging) return;- char name[512], ip[INET6_ADDRSTRLEN + 280], info[400];- proc_name_of(pid, comm, name, sizeof name);+ if (!atomic_load(&G.traffic_logging)) return;+ char path[4096], dest[INET6_ADDRSTRLEN + 280], info[400];+ const char *name = comm && *comm ? comm : "unknown";+ if (exe_path_of_pid(pid, path, sizeof path)) {+ const char *base = strrchr(path, '/');+ name = base ? base + 1 : path;+ }if (family == AF_INET) {- inet_ntop(AF_INET, addr + 12, ip, sizeof ip);- uint32_t h = ((uint32_t)addr[12] << 24) | ((uint32_t)addr[13] << 16) | ((uint32_t)addr[14] << 8) | addr[15];- char nm[1][256];- if (pb_dns_lookup(h, nm, 1) == 1) { // show the domain the application asked for, when we know it- size_t l = strlen(ip);- snprintf(ip + l, sizeof ip - l, " (%.*s)", (int)(sizeof ip - l - 4), nm[0]);+ inet_ntop(AF_INET, addr + 12, dest, sizeof dest);+ uint32_t ip = ((uint32_t)addr[12] << 24) | ((uint32_t)addr[13] << 16) | ((uint32_t)addr[14] << 8) | addr[15];+ char domain[1][256];+ if (pb_dns_lookup(ip, domain, 1) == 1) {+ size_t l = strlen(dest);+ snprintf(dest + l, sizeof dest - l, " (%.*s)", (int)(sizeof dest - l - 4), domain[0]);}- } else inet_ntop(AF_INET6, addr, ip, sizeof ip);- if (action == PB_ACT_PROXY) {- struct pb_proxy p;- if (pb_core_get_proxy(proxy_id, &p) == 0) snprintf(info, sizeof info, "%s %s:%u", proxy_type_name(p.type), p.host, p.port);- else snprintf(info, sizeof info, "PROXY");- } else snprintf(info, sizeof info, "%s", action == PB_ACT_BLOCK ? "BLOCK" : "DIRECT");+ } else {+ inet_ntop(AF_INET6, addr, dest, sizeof dest);+ }+ struct pb_proxy p;+ if (action == PB_ACT_PROXY && pb_core_get_proxy(proxy_id, &p) == 0)+ snprintf(info, sizeof info, "%s %s:%u", p.type == PROXY_TYPE_SOCKS5 ? "SOCKS5" : "HTTP", p.host, p.port);+ else+ snprintf(info, sizeof info, "%s", action == PB_ACT_PROXY ? "PROXY" : action == PB_ACT_BLOCK ? "BLOCK" : "DIRECT");pthread_mutex_lock(&cb_lock);- ConnectionCallback cb = G.conn_cb;- if (cb) cb(name, pid, ip, port, info);+ if (G.conn_cb) G.conn_cb(name, pid, dest, port, info);pthread_mutex_unlock(&cb_lock);}static void on_bpf_event(const struct pb_event *e){char comm[17];- memcpy(comm, e->comm, 16); comm[16] = 0;+ memcpy(comm, e->comm, 16);+ comm[16] = 0;emit_connection(e->pid, comm, e->family, e->addr, e->port, e->action, e->proxy_id);}-void pb_core_flow_event(const struct pb_orig *o, int action, const char *proxy_desc)+void pb_core_flow_event(const struct pb_orig *o, int action){- (void)proxy_desc;emit_connection(o->pid, NULL, o->family, o->addr, o->port, action, o->proxy_id);}-bool pb_core_dns_via_proxy(void) { return G.dns_via_proxy; }--// ---- proxies -------------------------------------------------------------------------------------------------------------static struct pb_proxy *find_proxy_locked(uint32_t id){- for (size_t i = 0; i < G.nproxies; i++) if (G.proxies[i].id == id) return &G.proxies[i];+ for (size_t i = 0; i < G.nproxies; i++)+ if (G.proxies[i].id == id) return &G.proxies[i];return NULL;}@@ -124,49 +137,40 @@ static struct pb_proxy *default_proxy_locked(void)return p ? p : (G.nproxies ? &G.proxies[0] : NULL);}+static struct pb_proxy *proxy_for_rule_locked(const struct pb_rule *r)+{+ struct pb_proxy *p = r->proxy_id ? find_proxy_locked(r->proxy_id) : NULL;+ return p ? p : default_proxy_locked();+}+int pb_core_get_proxy(uint32_t id, struct pb_proxy *out){- int rc = -1;pthread_rwlock_rdlock(&G.lock);struct pb_proxy *p = id ? find_proxy_locked(id) : NULL;if (!p) p = default_proxy_locked();- if (p) { *out = *p; rc = 0; }+ if (p) *out = *p;pthread_rwlock_unlock(&G.lock);- return rc;+ return p ? 0 : -1;}-static bool valid_proxy(const char *host, uint16_t port, char *err, size_t en)+static void maint_kick(void){- if (!host || !*host) { set_err(err, en, "proxy host is empty"); return false; }- if (strlen(host) > 253) { set_err(err, en, "proxy host too long"); return false; }- for (const char *c = host; *c; c++)- if (isspace((unsigned char)*c) || *c == '/' || *c == '@') { set_err(err, en, "proxy host contains invalid characters"); return false; }- if (!port) { set_err(err, en, "proxy port must be 1-65535"); return false; }- return true;+ pthread_mutex_lock(&G.maint_mu);+ G.maint_kick = true;+ pthread_cond_signal(&G.maint_cv);+ pthread_mutex_unlock(&G.maint_mu);}-static void fill_proxy(struct pb_proxy *p, const char *name, ProxyType type, const char *host, uint16_t port, const char *user, const char *pass)-{- snprintf(p->name, sizeof p->name, "%s", name && *name ? name : host);- p->type = type == PROXY_TYPE_HTTP ? PROXY_TYPE_HTTP : PROXY_TYPE_SOCKS5;- snprintf(p->host, sizeof p->host, "%s", host);- p->port = port;- snprintf(p->user, sizeof p->user, "%s", user ? user : "");- snprintf(p->pass, sizeof p->pass, "%s", pass ? pass : "");-}--// ---- DNS tap: arm kernel rules for addresses whose names match domain rules ----------------------------------------------------// Caller holds G.lock (read or write).+// Domain rules: arm the kernel for addresses whose DNS name matches a rule. Caller holds G.lock.static void arm_ip_locked(uint32_t ip, const char *const *names, int nnames){for (size_t i = 0; i < G.nrules; i++) {const struct pb_rule *r = &G.rules[i];- if (!r->enabled || !r->ndomains) continue;- for (int d = 0; d < r->ndomains; d++) {- bool hit = false;+ if (!r->enabled) continue;+ bool hit = false;+ for (int d = 0; d < r->ndomains && !hit; d++)for (int k = 0; k < nnames && !hit; k++) hit = pb_domain_match(r->domains[d], names[k]);- if (hit) { pb_bpf_dom_set((uint32_t)i, ip); break; }- }+ if (hit) pb_bpf_dom_set((uint32_t)i, ip);}}@@ -198,100 +202,219 @@ void pb_core_dns_observe(const uint8_t *msg, size_t len)pthread_rwlock_unlock(&G.lock);}-// ---- rule -> BPF sync -------------------------------------------------------------------------------------------------------static struct pb_rule_view *build_views_locked(size_t *n)+static void warn_udp_over_http_locked(void){- struct pb_rule_view *v = calloc(G.nrules ? G.nrules : 1, sizeof *v);- if (!v) return NULL;for (size_t i = 0; i < G.nrules; i++) {const struct pb_rule *r = &G.rules[i];- v[i].rule = r;- v[i].action = r->action;- if (r->action == RULE_ACTION_PROXY) {- struct pb_proxy *p = r->proxy_id ? find_proxy_locked(r->proxy_id) : NULL;- if (!p) p = default_proxy_locked();- if (!p) v[i].action = RULE_ACTION_BLOCK; // no usable proxy: fail closed- else { v[i].proxy_id = (uint16_t)p->id; v[i].udp_direct = p->type == PROXY_TYPE_HTTP; }- }+ if (!r->enabled || r->action != RULE_ACTION_PROXY || r->protocol == RULE_PROTOCOL_TCP) continue;+ const struct pb_proxy *p = proxy_for_rule_locked(r);+ if (!p || p->type != PROXY_TYPE_HTTP) continue;+ uint64_t key = ((uint64_t)r->id << 32) | p->id;+ bool seen = false;+ for (size_t k = 0; k < G.nwarned && !seen; k++) seen = G.warned[k] == key;+ if (seen) continue;+ if (G.nwarned < sizeof G.warned / sizeof *G.warned) G.warned[G.nwarned++] = key;+ pb_core_log("rule %u sends UDP to HTTP proxy '%s', which cannot carry UDP: that UDP traffic goes DIRECT", r->id, p->name);}- *n = G.nrules;- return v;}-static void sync_locked(void)+static void rebuild_views_locked(void){- if (!G.running) return;- size_t n;- struct pb_rule_view *v = build_views_locked(&n);- bool dom = false;- for (size_t i = 0; i < G.nrules; i++) dom |= G.rules[i].enabled && G.rules[i].ndomains > 0;- atomic_store(&G.has_domain_rules, dom);- if (v && pb_bpf_sync(v, n) != 0) pb_core_log("failed to apply rules to the kernel datapath");- free(v);- rearm_all_locked();- pb_bpf_set_flags(G.traffic_logging, G.dns_via_proxy);+ free(G.views);+ G.views = calloc(G.nrules ? G.nrules : 1, sizeof *G.views);+ G.nviews = G.views ? G.nrules : 0;+ bool domains = false;+ for (size_t i = 0; i < G.nviews; i++) {+ const struct pb_rule *r = &G.rules[i];+ struct pb_rule_view *v = &G.views[i];+ v->rule = r;+ v->action = r->action;+ domains |= r->enabled && r->ndomains > 0;+ if (r->action != RULE_ACTION_PROXY) continue;+ const struct pb_proxy *p = proxy_for_rule_locked(r);+ if (!p) v->action = RULE_ACTION_BLOCK; // no usable proxy: fail closed+ else { v->proxy_id = (uint16_t)p->id; v->udp_direct = p->type == PROXY_TYPE_HTTP; }+ }+ atomic_store(&G.has_domain_rules, domains);}-// ---- slow path --------------------------------------------------------------------------------------------------------------static bool exe_path_of_pid(uint32_t pid, char *out, size_t n)+static void sync_locked(void){- char lnk[64];- snprintf(lnk, sizeof lnk, "/proc/%u/exe", pid);- ssize_t r = readlink(lnk, out, n - 1);- if (r <= 0) { out[0] = 0; return false; }- out[r] = 0;- size_t l = strlen(out);- if (l > 10 && !strcmp(out + l - 10, " (deleted)")) out[l - 10] = 0;- return true;+ rebuild_views_locked();+ if (!G.running) return;+ if (pb_bpf_sync(G.views, G.nviews) != 0) pb_core_log("failed to apply rules to the kernel datapath");+ pb_bpf_set_flags(atomic_load(&G.traffic_logging), atomic_load(&G.dns_via_proxy));+ rearm_all_locked();+ warn_udp_over_http_locked();}void pb_core_decide(const struct pb_orig *o, struct pb_decision *out){- char path[512];- exe_path_of_pid(o->pid, path, sizeof path); // may be empty if the process is already gone- out->action = PB_ACT_DIRECT; out->proxy_id = 0;+ char path[4096];+ exe_path_of_pid(o->pid, path, sizeof path);+ out->action = PB_ACT_DIRECT;+ out->proxy_id = 0;pthread_rwlock_rdlock(&G.lock);- if (!pb_implicit_direct(o->family, o->addr, o->port, o->proto, G.dns_via_proxy)) {- char nbuf[PB_DNS_MAX_NAMES][256];- const char *nptr[PB_DNS_MAX_NAMES];+ if (!pb_implicit_direct(o->family, o->addr, o->port, o->proto, atomic_load(&G.dns_via_proxy))) {+ char names[PB_DNS_MAX_NAMES][256];+ const char *ptrs[PB_DNS_MAX_NAMES] = { 0 };int nn = 0;if (o->family == AF_INET && atomic_load(&G.has_domain_rules)) {- uint32_t h = ((uint32_t)o->addr[12] << 24) | ((uint32_t)o->addr[13] << 16) | ((uint32_t)o->addr[14] << 8) | o->addr[15];- nn = pb_dns_lookup(h, nbuf, PB_DNS_MAX_NAMES);- for (int k = 0; k < nn; k++) nptr[k] = nbuf[k];+ uint32_t ip = ((uint32_t)o->addr[12] << 24) | ((uint32_t)o->addr[13] << 16) | ((uint32_t)o->addr[14] << 8) | o->addr[15];+ nn = pb_dns_lookup(ip, names, PB_DNS_MAX_NAMES);+ for (int k = 0; k < nn; k++) ptrs[k] = names[k];}- int idx = pb_rules_eval(G.rules, G.nrules, path, o->family, o->addr, o->port, o->proto, nptr, nn);+ int idx = pb_rules_eval(G.rules, G.nrules, path, o->family, o->addr, o->port, o->proto, ptrs, nn);if (idx >= 0) {const struct pb_rule *r = &G.rules[idx];- if (r->action == RULE_ACTION_PROXY) {- struct pb_proxy *p = r->proxy_id ? find_proxy_locked(r->proxy_id) : NULL;- if (!p) p = default_proxy_locked();+ if (r->action != RULE_ACTION_PROXY) {+ out->action = r->action == RULE_ACTION_BLOCK ? PB_ACT_BLOCK : PB_ACT_DIRECT;+ } else {+ const struct pb_proxy *p = proxy_for_rule_locked(r);if (!p) out->action = PB_ACT_BLOCK;else if (o->proto == IPPROTO_UDP && p->type == PROXY_TYPE_HTTP) out->action = PB_ACT_DIRECT;else { out->action = PB_ACT_PROXY; out->proxy_id = p->id; }- } else out->action = r->action == RULE_ACTION_BLOCK ? PB_ACT_BLOCK : PB_ACT_DIRECT;+ }}}- if (o->exe_ino && path[0]) { // teach the kernel this binary so the next flow skips the relay- size_t n;- struct pb_rule_view *v = build_views_locked(&n);- if (v) { pb_bpf_learn(o, path, v, n); free(v); }- }+ if (o->exe_ino && path[0]) pb_bpf_learn(o, path, G.views, G.nviews);pthread_rwlock_unlock(&G.lock);}-int pb_core_take_tcp_orig(uint16_t client_port, struct pb_orig *out) { return pb_bpf_take_tcp_orig(client_port, out); }+int pb_core_take_tcp_orig(uint32_t client_ip_be, uint16_t client_port, struct pb_orig *out)+{+ return pb_bpf_take_tcp_orig(client_ip_be, client_port, out);+}+int pb_core_get_udp_flow(uint32_t flow_ip_be, struct pb_orig *out) { return pb_bpf_get_udp_flow(flow_ip_be, out); }-// ---- public API: proxies -----------------------------------------------------------------------------------------------+// ---- local proxy exemption and /etc/hosts -------------------------------------------------------------------------------+// A rule such as "*:...:PROXY" would also match the proxy's own outbound connections and send them back through itself, so+// the processes that listen on a configured local proxy address are never redirected.++struct host_cache { char host[256]; uint32_t ip_be; time_t at; };++static uint32_t resolve_proxy_ip(const char *host, struct host_cache *cache, size_t ncache, time_t now)+{+ struct in_addr a;+ if (inet_pton(AF_INET, host, &a) == 1) return a.s_addr;+ if (!strcmp(host, "localhost")) return htonl(INADDR_LOOPBACK);+ size_t slot = 0;+ for (size_t i = 0; i < ncache; i++) {+ if (!strcmp(cache[i].host, host)) { slot = i; break; }+ if (cache[i].at < cache[slot].at) slot = i;+ }+ if (strcmp(cache[slot].host, host) || now - cache[slot].at > 60) {+ struct addrinfo hints = { .ai_family = AF_INET, .ai_socktype = SOCK_STREAM }, *res = NULL;+ snprintf(cache[slot].host, sizeof cache[slot].host, "%.255s", host);+ cache[slot].at = now;+ cache[slot].ip_be = 0;+ if (getaddrinfo(host, NULL, &hints, &res) == 0 && res) {+ cache[slot].ip_be = ((struct sockaddr_in *)res->ai_addr)->sin_addr.s_addr;+ freeaddrinfo(res);+ }+ }+ return cache[slot].ip_be;+}++static void refresh_exempt(struct host_cache *cache, size_t ncache, uint32_t *last, size_t *nlast)+{+ struct { char host[256]; uint16_t port; } targets[MAX_PROXIES];+ size_t nt = 0;+ pthread_rwlock_rdlock(&G.lock);+ for (size_t i = 0; i < G.nproxies; i++) {+ snprintf(targets[nt].host, sizeof targets[nt].host, "%.255s", G.proxies[i].host);+ targets[nt++].port = G.proxies[i].port;+ }+ pthread_rwlock_unlock(&G.lock);++ uint32_t tgids[64];+ size_t n = 0;+ time_t now = time(NULL);+ for (size_t i = 0; i < nt && n < 64; i++) {+ uint32_t ip = resolve_proxy_ip(targets[i].host, cache, ncache, now);+ if (!ip || !pb_proc_is_local_ip(ip)) continue;+ uint32_t found[8];+ size_t nf = pb_proc_listeners(ip, targets[i].port, found, 8);+ for (size_t k = 0; k < nf && n < 64; k++) {+ bool dup = false;+ for (size_t j = 0; j < n && !dup; j++) dup = tgids[j] == found[k];+ if (!dup && found[k] != (uint32_t)getpid()) tgids[n++] = found[k];+ }+ }+ if (n != *nlast || memcmp(tgids, last, n * sizeof *tgids)) {+ pb_bpf_set_exempt(tgids, n);+ memcpy(last, tgids, n * sizeof *tgids);+ *nlast = n;+ }+}++static void reload_hosts_if_changed(time_t *mtime, off_t *size)+{+ struct stat st;+ if (stat(HOSTS_PATH, &st) != 0 || (st.st_mtime == *mtime && st.st_size == *size)) return;+ *mtime = st.st_mtime;+ *size = st.st_size;+ pb_dns_load_hosts(HOSTS_PATH, NULL);+ pthread_rwlock_rdlock(&G.lock);+ rearm_all_locked();+ pthread_rwlock_unlock(&G.lock);+}++static void *maint_loop(void *arg)+{+ (void)arg;+ struct host_cache cache[8] = { 0 };+ uint32_t last[64];+ size_t nlast = 0;+ time_t hosts_mtime = 0;+ off_t hosts_size = 0;+ pthread_mutex_lock(&G.maint_mu);+ while (!G.maint_stop) {+ G.maint_kick = false;+ pthread_mutex_unlock(&G.maint_mu);+ refresh_exempt(cache, 8, last, &nlast);+ reload_hosts_if_changed(&hosts_mtime, &hosts_size);+ pthread_mutex_lock(&G.maint_mu);+ struct timespec until;+ clock_gettime(CLOCK_REALTIME, &until);+ until.tv_sec += MAINT_PERIOD_S;+ while (!G.maint_stop && !G.maint_kick && pthread_cond_timedwait(&G.maint_cv, &G.maint_mu, &until) == 0) {}+ }+ pthread_mutex_unlock(&G.maint_mu);+ return NULL;+}++// ---- proxies -------------------------------------------------------------------------------------------------------------+static bool valid_proxy(const char *host, uint16_t port, char *err, size_t en)+{+ if (!host || !*host) { set_err(err, en, "proxy host is empty"); return false; }+ if (strlen(host) > 253) { set_err(err, en, "proxy host too long"); return false; }+ for (const char *c = host; *c; c++)+ if (isspace((unsigned char)*c) || *c == '/' || *c == '@') { set_err(err, en, "proxy host contains invalid characters"); return false; }+ if (!port) { set_err(err, en, "proxy port must be 1-65535"); return false; }+ return true;+}++static void fill_proxy(struct pb_proxy *p, const char *name, ProxyType type, const char *host, uint16_t port, const char *user, const char *pass)+{+ snprintf(p->name, sizeof p->name, "%s", name && *name ? name : host);+ p->type = type == PROXY_TYPE_HTTP ? PROXY_TYPE_HTTP : PROXY_TYPE_SOCKS5;+ snprintf(p->host, sizeof p->host, "%s", host);+ p->port = port;+ snprintf(p->user, sizeof p->user, "%s", user ? user : "");+ snprintf(p->pass, sizeof p->pass, "%s", pass ? pass : "");+}+uint32_t ProxyBridge_AddProxy(const char *name, ProxyType type, const char *host, uint16_t port, const char *user, const char *pass, char *err, size_t en){if (!valid_proxy(host, port, err, en)) return 0;- pthread_rwlock_wrlock(&G.lock);uint32_t id = 0;- if (G.nproxies >= MAX_PROXIES) set_err(err, en, "too many proxies (max %d)", MAX_PROXIES);- else {+ pthread_rwlock_wrlock(&G.lock);+ if (G.nproxies >= MAX_PROXIES) {+ set_err(err, en, "too many proxies (max %d)", MAX_PROXIES);+ } else {struct pb_proxy *p = &G.proxies[G.nproxies++];memset(p, 0, sizeof *p);p->id = id = G.next_proxy_id++;@@ -299,6 +422,7 @@ uint32_t ProxyBridge_AddProxy(const char *name, ProxyType type, const char *hostsync_locked();}pthread_rwlock_unlock(&G.lock);+ if (id) maint_kick();return id;}@@ -310,32 +434,35 @@ bool ProxyBridge_EditProxy(uint32_t id, const char *name, ProxyType type, constif (p) { fill_proxy(p, name, type, host, port, user, pass); sync_locked(); }else set_err(err, en, "unknown proxy id %u", id);pthread_rwlock_unlock(&G.lock);+ if (p) maint_kick();return p != NULL;}bool ProxyBridge_DeleteProxy(uint32_t id){- pthread_rwlock_wrlock(&G.lock);bool ok = false;- for (size_t i = 0; i < G.nproxies; i++)- if (G.proxies[i].id == id) {- memmove(&G.proxies[i], &G.proxies[i + 1], (G.nproxies - i - 1) * sizeof G.proxies[0]);- G.nproxies--;- if (G.default_proxy == id) G.default_proxy = 0;- ok = true;- break;- }+ pthread_rwlock_wrlock(&G.lock);+ for (size_t i = 0; i < G.nproxies && !ok; i++) {+ if (G.proxies[i].id != id) continue;+ memmove(&G.proxies[i], &G.proxies[i + 1], (G.nproxies - i - 1) * sizeof G.proxies[0]);+ G.nproxies--;+ if (G.default_proxy == id) G.default_proxy = 0;+ ok = true;+ }if (ok) sync_locked();pthread_rwlock_unlock(&G.lock);+ if (ok) maint_kick();return ok;}void ProxyBridge_ClearProxies(void){pthread_rwlock_wrlock(&G.lock);- G.nproxies = 0; G.default_proxy = 0;+ G.nproxies = 0;+ G.default_proxy = 0;sync_locked();pthread_rwlock_unlock(&G.lock);+ maint_kick();}void ProxyBridge_SetDefaultProxy(uint32_t id)@@ -350,14 +477,14 @@ bool ProxyBridge_SetProxyConfig(ProxyType type, const char *host, uint16_t port,{char err[256];pthread_rwlock_rdlock(&G.lock);- struct pb_proxy *d = default_proxy_locked();+ const struct pb_proxy *d = default_proxy_locked();uint32_t id = d ? d->id : 0;pthread_rwlock_unlock(&G.lock);if (id) return ProxyBridge_EditProxy(id, NULL, type, host, port, user, pass, err, sizeof err);return ProxyBridge_AddProxy("default", type, host, port, user, pass, err, sizeof err) != 0;}-// ---- public API: rules ---------------------------------------------------------------------------------------------------+// ---- rules ---------------------------------------------------------------------------------------------------------------bool ProxyBridge_ValidateRule(const char *process, const char *hosts, const char *ports, char *err, size_t en){struct pb_rule r;@@ -368,7 +495,8 @@ bool ProxyBridge_ValidateRule(const char *process, const char *hosts, const charstatic struct pb_rule *find_rule_locked(uint32_t id, size_t *idx){- for (size_t i = 0; i < G.nrules; i++) if (G.rules[i].id == id) { if (idx) *idx = i; return &G.rules[i]; }+ for (size_t i = 0; i < G.nrules; i++)+ if (G.rules[i].id == id) { if (idx) *idx = i; return &G.rules[i]; }return NULL;}@@ -376,20 +504,27 @@ uint32_t ProxyBridge_AddRule(const char *proc, const char *hosts, const char *po{struct pb_rule r;if (!pb_rule_parse(&r, proc, hosts, ports, err, en)) return 0;- r.enabled = true; r.protocol = protocol; r.action = action; r.proxy_id = proxy_id;- pthread_rwlock_wrlock(&G.lock);+ r.enabled = true;+ r.protocol = protocol;+ r.action = action;+ r.proxy_id = proxy_id;+uint32_t id = 0;- if (G.nrules >= PB_MAX_RULES) { set_err(err, en, "too many rules (max %d)", PB_MAX_RULES); pb_rule_free(&r); }- else {- if (G.nrules == G.caprules) {- size_t nc = G.caprules ? G.caprules * 2 : 32;- struct pb_rule *nr = realloc(G.rules, nc * sizeof *nr);- if (!nr) { pb_rule_free(&r); set_err(err, en, "out of memory"); pthread_rwlock_unlock(&G.lock); return 0; }- G.rules = nr; G.caprules = nc;- }+ pthread_rwlock_wrlock(&G.lock);+ if (G.nrules >= PB_MAX_RULES) {+ set_err(err, en, "too many rules (max %d)", PB_MAX_RULES);+ } else if (G.nrules == G.caprules) {+ size_t cap = G.caprules ? G.caprules * 2 : 32;+ struct pb_rule *grown = realloc(G.rules, cap * sizeof *grown);+ if (grown) { G.rules = grown; G.caprules = cap; }+ else set_err(err, en, "out of memory");+ }+ if (G.nrules < G.caprules && G.nrules < PB_MAX_RULES) {r.id = id = G.next_rule_id++;G.rules[G.nrules++] = r;sync_locked();+ } else {+ pb_rule_free(&r);}pthread_rwlock_unlock(&G.lock);return id;@@ -401,13 +536,21 @@ bool ProxyBridge_EditRule(uint32_t id, const char *proc, const char *hosts, consif (!pb_rule_parse(&r, proc, hosts, ports, err, en)) return false;pthread_rwlock_wrlock(&G.lock);struct pb_rule *old = find_rule_locked(id, NULL);- if (!old) { set_err(err, en, "unknown rule id %u", id); pb_rule_free(&r); pthread_rwlock_unlock(&G.lock); return false; }- r.id = id; r.enabled = old->enabled; r.protocol = protocol; r.action = action; r.proxy_id = proxy_id;- pb_rule_free(old);- *old = r;- sync_locked();+ if (!old) {+ set_err(err, en, "unknown rule id %u", id);+ pb_rule_free(&r);+ } else {+ r.id = id;+ r.enabled = old->enabled;+ r.protocol = protocol;+ r.action = action;+ r.proxy_id = proxy_id;+ pb_rule_free(old);+ *old = r;+ sync_locked();+ }pthread_rwlock_unlock(&G.lock);- return true;+ return old != NULL;}static bool set_enabled(uint32_t id, bool on)@@ -418,13 +561,14 @@ static bool set_enabled(uint32_t id, bool on)pthread_rwlock_unlock(&G.lock);return r != NULL;}+bool ProxyBridge_EnableRule(uint32_t id) { return set_enabled(id, true); }bool ProxyBridge_DisableRule(uint32_t id) { return set_enabled(id, false); }bool ProxyBridge_DeleteRule(uint32_t id){- pthread_rwlock_wrlock(&G.lock);size_t i;+ pthread_rwlock_wrlock(&G.lock);struct pb_rule *r = find_rule_locked(id, &i);if (r) {pb_rule_free(r);@@ -438,15 +582,15 @@ bool ProxyBridge_DeleteRule(uint32_t id)bool ProxyBridge_MoveRule(uint32_t id, int new_index){- pthread_rwlock_wrlock(&G.lock);size_t i;+ pthread_rwlock_wrlock(&G.lock);struct pb_rule *r = find_rule_locked(id, &i);if (r) {size_t to = new_index < 0 ? 0 : (size_t)new_index >= G.nrules ? G.nrules - 1 : (size_t)new_index;- struct pb_rule tmp = *r;- if (to < i) memmove(&G.rules[to + 1], &G.rules[to], (i - to) * sizeof tmp);- else if (to > i) memmove(&G.rules[i], &G.rules[i + 1], (to - i) * sizeof tmp);- G.rules[to] = tmp;+ struct pb_rule moved = *r;+ if (to < i) memmove(&G.rules[to + 1], &G.rules[to], (i - to) * sizeof moved);+ else if (to > i) memmove(&G.rules[i], &G.rules[i + 1], (to - i) * sizeof moved);+ G.rules[to] = moved;sync_locked();}pthread_rwlock_unlock(&G.lock);@@ -462,57 +606,76 @@ void ProxyBridge_ClearRules(void)pthread_rwlock_unlock(&G.lock);}-// ---- public API: runtime -----------------------------------------------------------------------------------------------------+// ---- runtime -------------------------------------------------------------------------------------------------------------void ProxyBridge_SetDnsViaProxy(bool enable){- pthread_rwlock_wrlock(&G.lock);- G.dns_via_proxy = enable;- pb_bpf_set_flags(G.traffic_logging, G.dns_via_proxy);- pthread_rwlock_unlock(&G.lock);+ atomic_store(&G.dns_via_proxy, enable);+ pb_bpf_set_flags(atomic_load(&G.traffic_logging), enable);}-void ProxyBridge_SetLogCallback(LogCallback cb) { pthread_mutex_lock(&cb_lock); G.log_cb = cb; pthread_mutex_unlock(&cb_lock); }-void ProxyBridge_SetConnectionCallback(ConnectionCallback cb) { pthread_mutex_lock(&cb_lock); G.conn_cb = cb; pthread_mutex_unlock(&cb_lock); }+void ProxyBridge_SetLogCallback(LogCallback cb)+{+ pthread_mutex_lock(&cb_lock);+ G.log_cb = cb;+ pthread_mutex_unlock(&cb_lock);+}++void ProxyBridge_SetConnectionCallback(ConnectionCallback cb)+{+ pthread_mutex_lock(&cb_lock);+ G.conn_cb = cb;+ pthread_mutex_unlock(&cb_lock);+}void ProxyBridge_SetTrafficLoggingEnabled(bool enable){- pthread_rwlock_wrlock(&G.lock);- G.traffic_logging = enable;- pb_bpf_set_flags(G.traffic_logging, G.dns_via_proxy);- pthread_rwlock_unlock(&G.lock);+ atomic_store(&G.traffic_logging, enable);+ pb_bpf_set_flags(enable, atomic_load(&G.dns_via_proxy));}void ProxyBridge_ClearConnectionLogs(void) {}+static bool proxies_missing_locked(void)+{+ for (size_t i = 0; i < G.nrules; i++) {+ const struct pb_rule *r = &G.rules[i];+ if (r->enabled && r->action == RULE_ACTION_PROXY && !proxy_for_rule_locked(r)) return true;+ }+ return false;+}+bool ProxyBridge_Start(void){pthread_rwlock_wrlock(&G.lock);if (G.running) { pthread_rwlock_unlock(&G.lock); return true; }- for (size_t i = 0; i < G.nrules; i++)- if (G.rules[i].enabled && G.rules[i].action == RULE_ACTION_PROXY && !default_proxy_locked() &&- !(G.rules[i].proxy_id && find_proxy_locked(G.rules[i].proxy_id))) {- pthread_rwlock_unlock(&G.lock);- pb_core_log("cannot start: a rule uses a proxy but no proxy is configured");- return false;- }- G.running = true; // pb_core_* callbacks may fire as soon as the relay is up+ if (proxies_missing_locked()) {+ pthread_rwlock_unlock(&G.lock);+ pb_core_log("cannot start: a rule uses a proxy but no proxy is configured");+ return false;+ }+ G.running = true; // relay callbacks may fire as soon as the relay is uppthread_rwlock_unlock(&G.lock);- bool started = false;- for (uint16_t base = PB_TCP_RELAY_PORT_DEFAULT; base < PB_TCP_RELAY_PORT_DEFAULT + 20 && !started; base += 2) {+ bool relay_up = false;+ for (uint16_t base = PB_TCP_RELAY_PORT_DEFAULT; base < PB_TCP_RELAY_PORT_DEFAULT + 20 && !relay_up; base += 2) {struct pb_relay_cfg rc = { .tcp_port = base, .udp_port = (uint16_t)(base + 1) };- started = pb_relay_start(&rc) == 0;+ relay_up = pb_relay_start(&rc) == 0;}- if (!started) { pthread_rwlock_wrlock(&G.lock); G.running = false; pthread_rwlock_unlock(&G.lock); return false; }-struct pb_bpf_cfg bc = { .tcp_port = pb_relay_tcp_port(), .udp_port = pb_relay_udp_port(), .self_tgid = (uint32_t)getpid(),- .log = G.traffic_logging, .dns_via_proxy = G.dns_via_proxy };- if (pb_bpf_start(&bc, on_bpf_event) != 0) {- pb_relay_stop();- pthread_rwlock_wrlock(&G.lock); G.running = false; pthread_rwlock_unlock(&G.lock);+ .log = atomic_load(&G.traffic_logging), .dns_via_proxy = atomic_load(&G.dns_via_proxy) };+ if (!relay_up || pb_bpf_start(&bc, on_bpf_event) != 0) {+ if (relay_up) pb_relay_stop();+ pthread_rwlock_wrlock(&G.lock);+ G.running = false;+ pthread_rwlock_unlock(&G.lock);return false;}- pb_dns_load_hosts("/etc/hosts", NULL); // static names are known without any DNS traffic++ pthread_mutex_lock(&G.maint_mu);+ G.maint_stop = false;+ pthread_mutex_unlock(&G.maint_mu);+ G.maint_started = pthread_create(&G.maint, NULL, maint_loop, NULL) == 0;+pthread_rwlock_wrlock(&G.lock);sync_locked();pthread_rwlock_unlock(&G.lock);@@ -525,10 +688,21 @@ bool ProxyBridge_Stop(void)pthread_rwlock_wrlock(&G.lock);bool was = G.running;G.running = false;+ G.nwarned = 0;pthread_rwlock_unlock(&G.lock);if (!was) return true;- pb_bpf_stop(); // detach first: no new flows get redirected- pb_relay_stop();++ if (G.maint_started) {+ pthread_mutex_lock(&G.maint_mu);+ G.maint_stop = true;+ pthread_cond_signal(&G.maint_cv);+ pthread_mutex_unlock(&G.maint_mu);+ pthread_join(G.maint, NULL);+ G.maint_started = false;+ }+ pb_bpf_detach(); // no new flows get redirected+ pb_relay_stop(); // relay threads may use the maps until they are gone+ pb_bpf_stop();pb_core_log("ProxyBridge stopped");return true;}diff --git a/Linux/src/ProxyBridge.h b/Linux/src/ProxyBridge.hindex a03ed15..89381dc 100644--- a/Linux/src/ProxyBridge.h+++ b/Linux/src/ProxyBridge.h@@ -11,6 +11,8 @@extern "C" {#endif+#define PB_API __attribute__((visibility("default")))+typedef void (*LogCallback)(const char* message);typedef void (*ConnectionCallback)(const char* process_name, uint32_t pid, const char* dest_ip, uint16_t dest_port, const char* proxy_info);@@ -34,14 +36,14 @@ typedef enum {/* ---- Proxy configurations -------------------------------------------------------------------------------------------* Any number of proxies can be registered. Ids are non-zero and stable until the proxy is deleted.* Returns 0 on failure (the reason is written to err, if given). */-uint32_t ProxyBridge_AddProxy(const char* name, ProxyType type, const char* host, uint16_t port,+PB_API uint32_t ProxyBridge_AddProxy(const char* name, ProxyType type, const char* host, uint16_t port,const char* username, const char* password, char* err, size_t err_size);-bool ProxyBridge_EditProxy(uint32_t proxy_id, const char* name, ProxyType type, const char* host, uint16_t port,+PB_API bool ProxyBridge_EditProxy(uint32_t proxy_id, const char* name, ProxyType type, const char* host, uint16_t port,const char* username, const char* password, char* err, size_t err_size);-bool ProxyBridge_DeleteProxy(uint32_t proxy_id); /* rules that used it fall back to the default proxy */-void ProxyBridge_ClearProxies(void);+PB_API bool ProxyBridge_DeleteProxy(uint32_t proxy_id); /* rules that used it fall back to the default proxy */+PB_API void ProxyBridge_ClearProxies(void);/* Which proxy a rule with proxy_id == 0 uses. 0 = the first proxy added. */-void ProxyBridge_SetDefaultProxy(uint32_t proxy_id);+PB_API void ProxyBridge_SetDefaultProxy(uint32_t proxy_id);/* ---- Rules ----------------------------------------------------------------------------------------------------------* Rules are evaluated in list order, first match wins. process_name: ';' or ',' separated globs matched against the@@ -50,33 +52,33 @@ void ProxyBridge_SetDefaultProxy(uint32_t proxy_id);* ("80;443;8000-9000", "" or "*" = any).* proxy_id applies when action == RULE_ACTION_PROXY; 0 = default proxy.* AddRule returns the new rule id, or 0 on validation failure (reason in err). */-uint32_t ProxyBridge_AddRule(const char* process_name, const char* target_hosts, const char* target_ports,+PB_API uint32_t ProxyBridge_AddRule(const char* process_name, const char* target_hosts, const char* target_ports,RuleProtocol protocol, RuleAction action, uint32_t proxy_id, char* err, size_t err_size);-bool ProxyBridge_EditRule(uint32_t rule_id, const char* process_name, const char* target_hosts, const char* target_ports,+PB_API bool ProxyBridge_EditRule(uint32_t rule_id, const char* process_name, const char* target_hosts, const char* target_ports,RuleProtocol protocol, RuleAction action, uint32_t proxy_id, char* err, size_t err_size);-bool ProxyBridge_EnableRule(uint32_t rule_id);-bool ProxyBridge_DisableRule(uint32_t rule_id);-bool ProxyBridge_DeleteRule(uint32_t rule_id);-bool ProxyBridge_MoveRule(uint32_t rule_id, int new_index); /* reorder: priority = position */-void ProxyBridge_ClearRules(void);+PB_API bool ProxyBridge_EnableRule(uint32_t rule_id);+PB_API bool ProxyBridge_DisableRule(uint32_t rule_id);+PB_API bool ProxyBridge_DeleteRule(uint32_t rule_id);+PB_API bool ProxyBridge_MoveRule(uint32_t rule_id, int new_index); /* reorder: priority = position */+PB_API void ProxyBridge_ClearRules(void);/* Validates a rule without adding it; returns true if valid, otherwise writes the reason to err. */-bool ProxyBridge_ValidateRule(const char* process_name, const char* target_hosts, const char* target_ports,+PB_API bool ProxyBridge_ValidateRule(const char* process_name, const char* target_hosts, const char* target_ports,char* err, size_t err_size);/* ---- Legacy single-proxy helper -------------------------------------------------------------------------------------* Sets (creating on first use) the default proxy. Equivalent to Add/EditProxy on the "default" entry. */-bool ProxyBridge_SetProxyConfig(ProxyType type, const char* proxy_ip, uint16_t proxy_port, const char* username, const char* password);+PB_API bool ProxyBridge_SetProxyConfig(ProxyType type, const char* proxy_ip, uint16_t proxy_port, const char* username, const char* password);/* ---- Runtime --------------------------------------------------------------------------------------------------------- */-void ProxyBridge_SetDnsViaProxy(bool enable);-void ProxyBridge_SetLogCallback(LogCallback callback);-void ProxyBridge_SetConnectionCallback(ConnectionCallback callback);-void ProxyBridge_SetTrafficLoggingEnabled(bool enable);-void ProxyBridge_ClearConnectionLogs(void);-bool ProxyBridge_Start(void); /* needs root (CAP_BPF/CAP_SYS_ADMIN) and a BTF kernel >= 5.11; returns false and logs why on failure */-bool ProxyBridge_Stop(void); /* keeps rules and proxies; Start() may be called again */-int ProxyBridge_TestConnection(const char* target_host, uint16_t target_port, char* result_buffer, size_t buffer_size);-int ProxyBridge_TestProxy(uint32_t proxy_id, const char* target_host, uint16_t target_port, char* result_buffer, size_t buffer_size);+PB_API void ProxyBridge_SetDnsViaProxy(bool enable);+PB_API void ProxyBridge_SetLogCallback(LogCallback callback);+PB_API void ProxyBridge_SetConnectionCallback(ConnectionCallback callback);+PB_API void ProxyBridge_SetTrafficLoggingEnabled(bool enable);+PB_API void ProxyBridge_ClearConnectionLogs(void);+PB_API bool ProxyBridge_Start(void); /* needs root (CAP_BPF/CAP_SYS_ADMIN) and a BTF kernel >= 5.11; returns false and logs why on failure */+PB_API bool ProxyBridge_Stop(void); /* keeps rules and proxies; Start() may be called again */+PB_API int ProxyBridge_TestConnection(const char* target_host, uint16_t target_port, char* result_buffer, size_t buffer_size);+PB_API int ProxyBridge_TestProxy(uint32_t proxy_id, const char* target_host, uint16_t target_port, char* result_buffer, size_t buffer_size);#ifdef __cplusplus}diff --git a/Linux/src/bpf/pb_bpf_shared.h b/Linux/src/bpf/pb_bpf_shared.hindex bb403e2..ef98709 100644--- a/Linux/src/bpf/pb_bpf_shared.h+++ b/Linux/src/bpf/pb_bpf_shared.h@@ -1,4 +1,4 @@-// Types shared between the BPF object and userspace (pb_bpf.c). Plain C, no kernel headers needed.+// Types shared by the BPF object and userspace.#ifndef PB_BPF_SHARED_H#define PB_BPF_SHARED_H@@ -15,48 +15,43 @@ typedef uint8_t pb_u8; typedef uint16_t pb_u16; typedef uint32_t pb_u32; typedef#define PB_BPF_MAX_V4 4#define PB_BPF_MAX_PORT 4-// cfg array slots-#define PB_CFG_ENABLED 0 // 1 when at least one rule is loaded-#define PB_CFG_SELF_TGID 1 // process that hosts the relay (never redirected)-#define PB_CFG_LOG 2 // 1 = emit events-#define PB_CFG_TCP_PORT 3-#define PB_CFG_UDP_PORT 4-#define PB_CFG_DNS_VIA_PROXY 5-#define PB_CFG_DNS_TAP 6 // 1 when a domain rule exists: port-53 flows of covered processes go through the relay-#define PB_CFG_NETNS_LO 7 // cookie of the network namespace the relay lives in; sockets in other namespaces are ignored-#define PB_CFG_NETNS_HI 8-#define PB_CFG_SLOTS 12--// brule flags#define PB_RF_ANY_HOST 0x01#define PB_RF_ANY_PORT 0x02-#define PB_RF_HOST_COMPLEX 0x04 // host pattern not representable: "maybe" for every destination-#define PB_RF_PORT_COMPLEX 0x08 // more port ranges than fit: "maybe" when the ports in the table do not match-#define PB_RF_HAS_V6 0x10 // rule has IPv6 patterns: "maybe" for IPv6 destinations-#define PB_RF_DOMAINS 0x40 // host list also contains domain patterns: answered by the dom_hit map (filled by the DNS tap)-#define PB_RF_UDP_DIRECT 0x20 // PROXY rule whose proxy cannot carry UDP (HTTP): UDP flows go direct+#define PB_RF_HOST_COMPLEX 0x04 // host pattern the kernel cannot express: "maybe" for every destination+#define PB_RF_PORT_COMPLEX 0x08 // more port ranges than fit: "maybe" when none of the stored ones match+#define PB_RF_HAS_V6 0x10 // IPv6 patterns present: "maybe" for IPv6 destinations+#define PB_RF_UDP_DIRECT 0x20 // PROXY rule whose proxy cannot carry UDP: UDP goes direct+#define PB_RF_DOMAINS 0x40 // answered through the dom_hit map filled by the DNS tap++#define PB_CLASS_DECIDE 0xffffffffu // pb_bclass.n: always take the slow path for this binary-#define PB_CLASS_DECIDE 0xffffffffu // pb_bclass.n value: always take the slow path for this binary+struct pb_cfg {+ pb_u32 enabled; // at least one rule is loaded+ pb_u32 self_tgid; // the process hosting the relay is never redirected+ pb_u32 log;+ pb_u32 dns_via_proxy;+ pb_u32 dns_tap; // a domain rule exists+ pb_u32 n_exempt; // entries in the exempt map+ pb_u16 tcp_port, udp_port;+ pb_u64 netns; // network namespace of the relay; other namespaces are ignored (0 = unknown)+};struct pb_exe_key { pb_u32 dev; pb_u32 pad; pb_u64 ino; };+struct pb_port_key { pb_u32 ip; pb_u32 port; }; // client source address (network order) and port+struct pb_dom_key { pb_u32 rule; pb_u32 ip; }; // ip in host orderstruct pb_brule {pb_u16 proxy_id;- pb_u8 action; // 0 proxy, 1 direct, 2 block- pb_u8 proto_mask; // 1 tcp, 2 udp- pb_u8 flags;- pb_u8 n_v4;- pb_u8 n_port;- pb_u8 pad;+ pb_u8 action; // 0 proxy, 1 direct, 2 block+ pb_u8 proto_mask; // 1 tcp, 2 udp+ pb_u8 flags, n_v4, n_port, pad;struct { pb_u32 lo, hi; } v4[PB_BPF_MAX_V4]; // host orderstruct { pb_u16 lo, hi; } port[PB_BPF_MAX_PORT]; // host order};-struct pb_dom_key { pb_u32 rule; pb_u32 ip; }; // ip in host order-struct pb_bclass {pb_u32 n;- pb_u32 tap; // 1: this binary is covered by a domain rule, so its DNS must be observed+ pb_u32 tap; // covered by a domain rule: its DNS must be observedpb_u32 rule[PB_RULES_PER_CLASS];};@@ -64,12 +59,8 @@ struct pb_event {pb_u32 pid;pb_u8 comm[16];pb_u8 addr[16];- pb_u16 port;- pb_u16 proxy_id;- pb_u8 family;- pb_u8 proto;- pb_u8 action; // PB_ACT_*- pb_u8 pad;+ pb_u16 port, proxy_id;+ pb_u8 family, proto, action, pad;};#endifdiff --git a/Linux/src/bpf/proxybridge.bpf.c b/Linux/src/bpf/proxybridge.bpf.cindex 839f57c..db8a033 100644--- a/Linux/src/bpf/proxybridge.bpf.c+++ b/Linux/src/bpf/proxybridge.bpf.c@@ -1,12 +1,11 @@-// ProxyBridge eBPF datapath: cgroup socket-address hooks that redirect selected processes' connect()/sendmsg() to the-// userspace relay and remember the original destination.+// cgroup socket-address hooks: redirect selected processes' connect()/sendmsg() to the userspace relay.#include <linux/types.h>#include <linux/bpf.h>#include <bpf/bpf_helpers.h>#include <bpf/bpf_endian.h>#include "pb_bpf_shared.h"-// Minimal kernel type stubs (CO-RE relocated against the running kernel's BTF; avoids shipping a 160k-line vmlinux.h).+// Minimal kernel types, relocated against the running kernel's BTF (CO-RE).#pragma clang attribute push(__attribute__((preserve_access_index)), apply_to = record)struct super_block { __u32 s_dev; };struct inode { struct super_block *i_sb; unsigned long i_ino; };@@ -39,49 +38,28 @@ struct pb_orig {__u64 exe_ino;};-struct { __uint(type, BPF_MAP_TYPE_ARRAY); __uint(max_entries, PB_CFG_SLOTS);- __type(key, __u32); __type(value, __u32); } cfg SEC(".maps");-struct { __uint(type, BPF_MAP_TYPE_HASH); __uint(max_entries, 16384);- __type(key, struct pb_exe_key); __type(value, __u32); } exe2class SEC(".maps");-struct { __uint(type, BPF_MAP_TYPE_ARRAY); __uint(max_entries, PB_MAX_CLASSES);- __type(key, __u32); __type(value, struct pb_bclass); } classes SEC(".maps");-struct { __uint(type, BPF_MAP_TYPE_ARRAY); __uint(max_entries, PB_MAX_RULES);- __type(key, __u32); __type(value, struct pb_brule); } brules SEC(".maps");-struct { __uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(max_entries, 32768);- __type(key, __u64); __type(value, struct pb_orig); } by_cookie SEC(".maps");-struct { __uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(max_entries, 32768);- __type(key, __u32); __type(value, struct pb_orig); } by_port SEC(".maps");-struct { __uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(max_entries, 32768);- __type(key, __u32); __type(value, struct pb_orig); } flows SEC(".maps");-struct { __uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(max_entries, 65536);- __type(key, struct pb_dom_key); __type(value, __u8); } dom_hit SEC(".maps"); // (rule, ip) pairs whose DNS name matches the rule-struct { __uint(type, BPF_MAP_TYPE_RINGBUF); __uint(max_entries, 256 * 1024); } events SEC(".maps");-struct { __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); __uint(max_entries, 8);- __type(key, __u32); __type(value, __u64); } stats SEC(".maps"); // 0 redirected 1 blocked 2 decide 3 evt dropped+volatile struct pb_cfg cfg;-static __always_inline void stat_inc(__u32 k)-{- __u64 *v = bpf_map_lookup_elem(&stats, &k);- if (v) (*v)++;-}+#define MAP(name, kind, entries, key_t, val_t) \+ struct { __uint(type, kind); __uint(max_entries, entries); __type(key, key_t); __type(value, val_t); } name SEC(".maps")-static __always_inline __u32 cfg_get(__u32 k)-{- __u32 *v = bpf_map_lookup_elem(&cfg, &k);- return v ? *v : 0;-}+MAP(exe2class, BPF_MAP_TYPE_HASH, 16384, struct pb_exe_key, __u32);+MAP(classes, BPF_MAP_TYPE_ARRAY, PB_MAX_CLASSES, __u32, struct pb_bclass);+MAP(brules, BPF_MAP_TYPE_ARRAY, PB_MAX_RULES, __u32, struct pb_brule);+MAP(exempt, BPF_MAP_TYPE_HASH, 64, __u32, __u8);+MAP(by_cookie, BPF_MAP_TYPE_LRU_HASH, 32768, __u64, struct pb_orig);+MAP(by_port, BPF_MAP_TYPE_LRU_HASH, 32768, struct pb_port_key, struct pb_orig);+MAP(flows, BPF_MAP_TYPE_LRU_HASH, 32768, __u32, struct pb_orig);+MAP(dom_hit, BPF_MAP_TYPE_LRU_HASH, 65536, struct pb_dom_key, __u8);+struct { __uint(type, BPF_MAP_TYPE_RINGBUF); __uint(max_entries, 256 * 1024); } events SEC(".maps");-// Containers/other network namespaces have their own loopback: redirecting them to our relay would break them.static __always_inline int foreign_netns(void *ctx){- __u64 want = ((__u64)cfg_get(PB_CFG_NETNS_HI) << 32) | cfg_get(PB_CFG_NETNS_LO);+ __u64 want = cfg.netns;return want && bpf_get_netns_cookie(ctx) != want;}-// ----------------------------------------------------------------------------------------------------------------------// rule evaluation-// ----------------------------------------------------------------------------------------------------------------------static __always_inline int rule_match(const struct pb_brule *r, __u32 ri, __u8 fam, __u32 ip4_host, __u16 port)+static __always_inline int rule_match(const struct pb_brule *r, __u32 ri, __u8 fam, __u32 ip4, __u16 port){int port_res = M_YES;if (!(r->flags & PB_RF_ANY_PORT)) {@@ -103,10 +81,10 @@ static __always_inline int rule_match(const struct pb_brule *r, __u32 ri, __u8 f#pragma unrollfor (int i = 0; i < PB_BPF_MAX_V4; i++) {if (i >= r->n_v4) break;- if (ip4_host >= r->v4[i].lo && ip4_host <= r->v4[i].hi) { host_res = M_YES; break; }+ if (ip4 >= r->v4[i].lo && ip4 <= r->v4[i].hi) { host_res = M_YES; break; }}if (host_res == M_NO && (r->flags & PB_RF_DOMAINS)) {- struct pb_dom_key dk = { .rule = ri, .ip = ip4_host };+ struct pb_dom_key dk = { .rule = ri, .ip = ip4 };if (bpf_map_lookup_elem(&dom_hit, &dk)) host_res = M_YES;}}@@ -114,51 +92,49 @@ static __always_inline int rule_match(const struct pb_brule *r, __u32 ri, __u8 freturn (host_res == M_MAYBE || port_res == M_MAYBE) ? M_MAYBE : M_YES;}-static __always_inline int implicit_direct(__u8 fam, const __u8 *a, __u16 port, __u8 proto)+static __always_inline int implicit_direct(const struct pb_orig *o){- if (fam == AF_INET) {+ const __u8 *a = o->addr;+ if (o->family == AF_INET) {if (a[12] == 127 || a[12] == 0 || a[12] >= 224) return 1;} else {- if (a[0] == 0xff) return 1;- if (a[0] == 0xfe && (a[1] & 0xc0) == 0x80) return 1;- int lo = 1;+ if (a[0] == 0xff || (a[0] == 0xfe && (a[1] & 0xc0) == 0x80)) return 1;+ int loopback = a[15] == 1;#pragma unroll- for (int i = 0; i < 15; i++) if (a[i]) lo = 0;- if (lo && a[15] == 1) return 1;+ for (int i = 0; i < 15; i++) if (a[i]) loopback = 0;+ if (loopback) return 1;}- if (proto == IPPROTO_UDP && (port == 67 || port == 68)) return 1;- if (port == 53 && !cfg_get(PB_CFG_DNS_VIA_PROXY)) return 1;- return 0;+ if (o->proto == IPPROTO_UDP && (o->port == 67 || o->port == 68)) return 1;+ return o->port == 53 && !cfg.dns_via_proxy;}-// Returns an ACT_*; for ACT_PROXY *proxy_id is set.-static __always_inline int decide(struct pb_orig *o, __u16 *proxy_id)+// Sets o->proxy_id for ACT_PROXY.+static __always_inline int decide(struct pb_orig *o){- if (!cfg_get(PB_CFG_ENABLED)) return ACT_DIRECT;- if (o->pid == cfg_get(PB_CFG_SELF_TGID)) return ACT_DIRECT;- int tap = o->port == 53 && cfg_get(PB_CFG_DNS_TAP);- if (!tap && implicit_direct(o->family, o->addr, o->port, o->proto)) return ACT_DIRECT;+ if (!cfg.enabled || o->pid == cfg.self_tgid) return ACT_DIRECT;+ if (cfg.n_exempt && bpf_map_lookup_elem(&exempt, &o->pid)) return ACT_DIRECT;+ int tap = o->port == 53 && cfg.dns_tap;+ if (!tap && implicit_direct(o)) return ACT_DIRECT;- struct task_struct *t = bpf_get_current_task_btf();- struct mm_struct *mm = t->mm;- if (!mm) return ACT_DIRECT; // kernel thread+ struct mm_struct *mm = bpf_get_current_task_btf()->mm;+ if (!mm) return ACT_DIRECT;struct pb_exe_key key = {};key.dev = mm->exe_file->f_inode->i_sb->s_dev;key.ino = mm->exe_file->f_inode->i_ino;- o->exe_dev = key.dev; o->exe_ino = key.ino; // lets userspace learn the exact kernel-side key+ o->exe_dev = key.dev;+ o->exe_ino = key.ino;if (!key.ino) return ACT_DECIDE;__u32 *cid = bpf_map_lookup_elem(&exe2class, &key);- if (!cid) return ACT_DECIDE; // binary not seen yet: relay classifies it+ if (!cid) return ACT_DECIDE;struct pb_bclass *c = bpf_map_lookup_elem(&classes, cid);if (!c || c->n > PB_RULES_PER_CLASS) return ACT_DECIDE;if (tap) {- // a domain rule covers this binary: its DNS answers must pass through the relay so names can be learnedif (c->tap) return ACT_DECIDE;- if (implicit_direct(o->family, o->addr, o->port, o->proto)) return ACT_DIRECT;+ if (implicit_direct(o)) return ACT_DIRECT;}- __u32 ip4 = (o->family == AF_INET) ? bpf_ntohl(*(const __u32 *)(o->addr + 12)) : 0;+ __u32 ip4 = o->family == AF_INET ? bpf_ntohl(*(const __u32 *)(o->addr + 12)) : 0;__u8 pbit = o->proto == IPPROTO_TCP ? 1 : 2;#pragma unrollfor (int i = 0; i < PB_RULES_PER_CLASS; i++) {@@ -170,47 +146,48 @@ static __always_inline int decide(struct pb_orig *o, __u16 *proxy_id)int m = rule_match(r, ri, o->family, ip4, o->port);if (m == M_NO) continue;if (m == M_MAYBE) return ACT_DECIDE;- if (r->action == ACT_PROXY) {- if (o->proto == IPPROTO_UDP && (r->flags & PB_RF_UDP_DIRECT)) return ACT_DIRECT;- *proxy_id = r->proxy_id;- }- return r->action;+ if (r->action != ACT_PROXY) return r->action;+ if (o->proto == IPPROTO_UDP && (r->flags & PB_RF_UDP_DIRECT)) return ACT_DIRECT;+ o->proxy_id = r->proxy_id;+ return ACT_PROXY;}return ACT_DIRECT;}-static __always_inline void emit(const struct pb_orig *o, int action, __u16 proxy_id)+static __always_inline void emit(const struct pb_orig *o, int action){- if (!cfg_get(PB_CFG_LOG)) return;+ if (!cfg.log) return;struct pb_event *e = bpf_ringbuf_reserve(&events, sizeof *e, 0);- if (!e) { stat_inc(3); return; }+ if (!e) return;e->pid = o->pid;bpf_get_current_comm(e->comm, sizeof e->comm);__builtin_memcpy(e->addr, o->addr, 16);- e->port = o->port; e->proxy_id = proxy_id;- e->family = o->family; e->proto = o->proto; e->action = action; e->pad = 0;+ e->port = o->port;+ e->proxy_id = o->proxy_id;+ e->family = o->family;+ e->proto = o->proto;+ e->action = action;+ e->pad = 0;bpf_ringbuf_submit(e, 0);}-// ----------------------------------------------------------------------------------------------------------------------// flow handling-// ---------------------------------------------------------------------------------------------------------------------static __always_inline void set_mapped_v4(__u32 *ip6, __u32 ip4_be){ip6[0] = 0; ip6[1] = 0; ip6[2] = bpf_htonl(0x0000ffff); ip6[3] = ip4_be;}-// Fills o from a sockaddr as seen in the hook. For v6 sockets a v4-mapped address is an IPv4 destination.static __always_inline void orig_from_v4(struct pb_orig *o, __u32 ip_be, __u16 port_be, __u8 proto){__builtin_memset(o, 0, sizeof *o);o->addr[10] = 0xff; o->addr[11] = 0xff;__builtin_memcpy(o->addr + 12, &ip_be, 4);o->port = bpf_ntohs(port_be);- o->family = AF_INET; o->proto = proto;+ o->family = AF_INET;+ o->proto = proto;o->pid = bpf_get_current_pid_tgid() >> 32;}+// A v4-mapped address on an IPv6 socket is an IPv4 destination.static __always_inline void orig_from_v6(struct pb_orig *o, const __u32 ip6[4], __u16 port_be, __u8 proto){__builtin_memset(o, 0, sizeof *o);@@ -218,11 +195,10 @@ static __always_inline void orig_from_v6(struct pb_orig *o, const __u32 ip6[4],o->port = bpf_ntohs(port_be);o->proto = proto;o->pid = bpf_get_current_pid_tgid() >> 32;- if (ip6[0] == 0 && ip6[1] == 0 && ip6[2] == bpf_htonl(0x0000ffff)) o->family = AF_INET;- else o->family = AF_INET6;+ o->family = (ip6[0] == 0 && ip6[1] == 0 && ip6[2] == bpf_htonl(0x0000ffff)) ? AF_INET : AF_INET6;}-// Deterministic loopback flow address (127.1-255.x.y) for a UDP destination; collisions are probed linearly.+// Loopback flow address 127.1-255.x.y standing for one UDP destination; the relay recovers the destination from it.static __always_inline __u32 udp_flow_addr(struct pb_orig *o){const __u32 *w = (const __u32 *)o->addr;@@ -236,58 +212,42 @@ static __always_inline __u32 udp_flow_addr(struct pb_orig *o)addr = bpf_htonl(0x7f000000 | (((h + i) & 0x00ffffff) | 0x00010000));struct pb_orig *ex = bpf_map_lookup_elem(&flows, &addr);if (!ex) { bpf_map_update_elem(&flows, &addr, o, BPF_NOEXIST); break; }- if (__builtin_memcmp(ex->addr, o->addr, 16) == 0 && ex->port == o->port && ex->proxy_id == o->proxy_id &&+ if (!__builtin_memcmp(ex->addr, o->addr, 16) && ex->port == o->port && ex->proxy_id == o->proxy_id &&ex->action == o->action && (o->action != ACT_DECIDE || ex->pid == o->pid)) break;}return addr;}-// 0 = leave the socket call untouched, 1 = it was redirected, -1 = block-static __always_inline int route(struct pb_orig *o, __u16 *proxy_id_out)+// 0: leave the call untouched, 1: redirected to the relay, -1: block.+static __always_inline int route(struct pb_orig *o){- __u16 pid16 = 0;- int act = decide(o, &pid16);- switch (act) {- case ACT_DIRECT:- emit(o, ACT_DIRECT, 0);- return 0;- case ACT_BLOCK:- emit(o, ACT_BLOCK, 0);- stat_inc(1);- return -1;- case ACT_PROXY:- o->action = ACT_PROXY; o->proxy_id = pid16;- emit(o, ACT_PROXY, pid16);- stat_inc(0);- break;- default:- o->action = ACT_DECIDE; o->proxy_id = 0;- stat_inc(2);- break;+ int act = decide(o);+ if (act == ACT_DIRECT || act == ACT_BLOCK) {+ emit(o, act);+ return act == ACT_BLOCK ? -1 : 0;}- *proxy_id_out = o->proxy_id;+ o->action = act;+ if (act == ACT_PROXY) emit(o, ACT_PROXY);+ else o->proxy_id = 0;return 1;}-// ---- TCP / connected UDP: connect4 / connect6 ------------------------------------------------------------------------SEC("cgroup/connect4")int pb_connect4(struct bpf_sock_addr *ctx){- if (foreign_netns(ctx)) return 1;- if (ctx->protocol != IPPROTO_TCP && ctx->protocol != IPPROTO_UDP) return 1;- struct pb_orig o; __u16 pid;+ if (foreign_netns(ctx) || (ctx->protocol != IPPROTO_TCP && ctx->protocol != IPPROTO_UDP)) return 1;+ struct pb_orig o;orig_from_v4(&o, ctx->user_ip4, ctx->user_port, ctx->protocol);- int r = route(&o, &pid);- if (r < 0) return 0;- if (r == 0) return 1;+ int r = route(&o);+ if (r <= 0) return r == 0;if (ctx->protocol == IPPROTO_TCP) {__u64 ck = bpf_get_socket_cookie(ctx);bpf_map_update_elem(&by_cookie, &ck, &o, BPF_ANY);ctx->user_ip4 = bpf_htonl(0x7f000001);- ctx->user_port = bpf_htons((__u16)cfg_get(PB_CFG_TCP_PORT));+ ctx->user_port = bpf_htons(cfg.tcp_port);} else {ctx->user_ip4 = udp_flow_addr(&o);- ctx->user_port = bpf_htons((__u16)cfg_get(PB_CFG_UDP_PORT));+ ctx->user_port = bpf_htons(cfg.udp_port);}return 1;}@@ -295,69 +255,59 @@ int pb_connect4(struct bpf_sock_addr *ctx)SEC("cgroup/connect6")int pb_connect6(struct bpf_sock_addr *ctx){- if (foreign_netns(ctx)) return 1;- if (ctx->protocol != IPPROTO_TCP && ctx->protocol != IPPROTO_UDP) return 1;+ if (foreign_netns(ctx) || (ctx->protocol != IPPROTO_TCP && ctx->protocol != IPPROTO_UDP)) return 1;__u32 ip6[4] = { ctx->user_ip6[0], ctx->user_ip6[1], ctx->user_ip6[2], ctx->user_ip6[3] };- struct pb_orig o; __u16 pid;+ struct pb_orig o;orig_from_v6(&o, ip6, ctx->user_port, ctx->protocol);- int r = route(&o, &pid);- if (r < 0) return 0;- if (r == 0) return 1;+ int r = route(&o);+ if (r <= 0) return r == 0;if (ctx->protocol == IPPROTO_TCP) {__u64 ck = bpf_get_socket_cookie(ctx);bpf_map_update_elem(&by_cookie, &ck, &o, BPF_ANY);set_mapped_v4(ctx->user_ip6, bpf_htonl(0x7f000001));- ctx->user_port = bpf_htons((__u16)cfg_get(PB_CFG_TCP_PORT));+ ctx->user_port = bpf_htons(cfg.tcp_port);} else {set_mapped_v4(ctx->user_ip6, udp_flow_addr(&o));- ctx->user_port = bpf_htons((__u16)cfg_get(PB_CFG_UDP_PORT));+ ctx->user_port = bpf_htons(cfg.udp_port);}return 1;}-// ---- unconnected UDP --------------------------------------------------------------------------------------------------SEC("cgroup/sendmsg4")int pb_sendmsg4(struct bpf_sock_addr *ctx){- if (foreign_netns(ctx)) return 1;- if (ctx->protocol != IPPROTO_UDP) return 1;- struct pb_orig o; __u16 pid;+ if (foreign_netns(ctx) || ctx->protocol != IPPROTO_UDP) return 1;+ struct pb_orig o;orig_from_v4(&o, ctx->user_ip4, ctx->user_port, IPPROTO_UDP);- int r = route(&o, &pid);- if (r < 0) return 0;- if (r == 0) return 1;+ int r = route(&o);+ if (r <= 0) return r == 0;ctx->user_ip4 = udp_flow_addr(&o);- ctx->user_port = bpf_htons((__u16)cfg_get(PB_CFG_UDP_PORT));+ ctx->user_port = bpf_htons(cfg.udp_port);return 1;}+// udpv6_sendmsg refuses a hook that rewrites a native IPv6 destination to a v4-mapped address and loopback has only ::1, so+// a native IPv6 flow that must be proxied fails closed (EPERM); the application falls back to IPv4 or TCP.SEC("cgroup/sendmsg6")int pb_sendmsg6(struct bpf_sock_addr *ctx){- if (foreign_netns(ctx)) return 1;- if (ctx->protocol != IPPROTO_UDP) return 1;+ if (foreign_netns(ctx) || ctx->protocol != IPPROTO_UDP) return 1;__u32 ip6[4] = { ctx->user_ip6[0], ctx->user_ip6[1], ctx->user_ip6[2], ctx->user_ip6[3] };- struct pb_orig o; __u16 pid;+ struct pb_orig o;orig_from_v6(&o, ip6, ctx->user_port, IPPROTO_UDP);- int r = route(&o, &pid);- if (r < 0) return 0;- if (r == 0) return 1;- // The kernel (udpv6_sendmsg) refuses a sendmsg6 program that rewrites a native IPv6 destination to a v4-mapped address,- // and loopback has only ::1 so a flow id cannot be encoded in the address. A flow that must be proxied therefore fails- // closed (EPERM; applications fall back to IPv4/TCP). Flows that merely need a userspace decision pass untouched.- if (o.action == ACT_PROXY) { stat_inc(1); return 0; }- return 1;+ int r = route(&o);+ if (r <= 0) return r == 0;+ return o.action != ACT_PROXY;}-// Replies arrive from the flow address; show the application the real peer.+// Replies come from the flow address; show the application the real peer.SEC("cgroup/recvmsg4")int pb_recvmsg4(struct bpf_sock_addr *ctx){- if (ctx->protocol != IPPROTO_UDP || ctx->user_port != bpf_htons((__u16)cfg_get(PB_CFG_UDP_PORT))) return 1;+ if (ctx->protocol != IPPROTO_UDP || ctx->user_port != bpf_htons(cfg.udp_port)) return 1;__u32 key = ctx->user_ip4;struct pb_orig *o = bpf_map_lookup_elem(&flows, &key);- if (!o) return 1;- if (o->family == AF_INET) {+ if (o && o->family == AF_INET) {ctx->user_ip4 = *(__u32 *)(o->addr + 12);ctx->user_port = bpf_htons(o->port);}@@ -367,7 +317,7 @@ int pb_recvmsg4(struct bpf_sock_addr *ctx)SEC("cgroup/recvmsg6")int pb_recvmsg6(struct bpf_sock_addr *ctx){- if (ctx->protocol != IPPROTO_UDP || ctx->user_port != bpf_htons((__u16)cfg_get(PB_CFG_UDP_PORT))) return 1;+ if (ctx->protocol != IPPROTO_UDP || ctx->user_port != bpf_htons(cfg.udp_port)) return 1;if (ctx->user_ip6[0] || ctx->user_ip6[1] || ctx->user_ip6[2] != bpf_htonl(0x0000ffff)) return 1;__u32 key = ctx->user_ip6[3];struct pb_orig *o = bpf_map_lookup_elem(&flows, &key);@@ -378,7 +328,7 @@ int pb_recvmsg6(struct bpf_sock_addr *ctx)return 1;}-// getpeername() on a redirected socket shows the original destination+// getpeername() on a redirected socket reports the original destination.SEC("cgroup/getpeername4")int pb_getpeername4(struct bpf_sock_addr *ctx){@@ -417,7 +367,7 @@ int pb_getpeername6(struct bpf_sock_addr *ctx)return 1;}-// Hand the original destination to the relay, keyed by the client's local port.+// Hands the original destination to the relay, keyed by the client's source address and port.SEC("sockops")int pb_sockops(struct bpf_sock_ops *s){@@ -425,8 +375,10 @@ int pb_sockops(struct bpf_sock_ops *s)__u64 ck = bpf_get_socket_cookie(s);struct pb_orig *o = bpf_map_lookup_elem(&by_cookie, &ck);if (!o) return 1;- __u32 lp = s->local_port;- bpf_map_update_elem(&by_port, &lp, o, BPF_ANY);+ struct pb_port_key k = { .ip = s->local_ip4, .port = s->local_port };+ if (s->family == AF_INET6 && !s->local_ip6[0] && !s->local_ip6[1] && s->local_ip6[2] == bpf_htonl(0x0000ffff))+ k.ip = s->local_ip6[3];+ bpf_map_update_elem(&by_port, &k, o, BPF_ANY);return 1;}diff --git a/Linux/src/pb_bpf.c b/Linux/src/pb_bpf.cindex d4bf74f..df73bb3 100644--- a/Linux/src/pb_bpf.c+++ b/Linux/src/pb_bpf.c@@ -3,14 +3,17 @@#include <dirent.h>#include <errno.h>#include <fcntl.h>+#include <poll.h>#include <pthread.h>#include <stdarg.h>+#include <stdatomic.h>#include <stdio.h>#include <stdlib.h>#include <string.h>+#include <sys/eventfd.h>#include <sys/resource.h>-#include <sys/stat.h>#include <sys/socket.h>+#include <sys/stat.h>#include <sys/statfs.h>#include <sys/sysmacros.h>#include <unistd.h>@@ -20,45 +23,46 @@#ifndef CGROUP2_SUPER_MAGIC#define CGROUP2_SUPER_MAGIC 0x63677270#endif+#ifndef SO_NETNS_COOKIE+#define SO_NETNS_COOKIE 71+#endif#define MAX_KNOWN_EXES 16384+#define MAX_EXEMPT 64-struct exe_ent { uint32_t dev; uint64_t ino; char path[240]; };+struct exe_ent { uint32_t dev; uint64_t ino; char *path; };static struct {pthread_mutex_t lock;struct proxybridge_bpf *skel;- int linkfds[16];- int nlinks;+ int linkfds[16], nlinks;struct ring_buffer *rb;pthread_t evt_thread;- bool evt_started;- volatile bool stop;+ bool evt_started, running;+ int stop_fd;pb_event_cb cb;- bool running;+ struct exe_ent *exes; size_t nexes;+ struct pb_bclass *cls; size_t ncls;+ struct pb_brule *br; size_t nbr;+} G = { .lock = PTHREAD_MUTEX_INITIALIZER, .stop_fd = -1 };- struct exe_ent *exes; size_t nexes; // executables we know about (kernel-side keys)- struct pb_bclass *cls; size_t ncls; // current class table (index = class id)- bool have_rules;-} G = { .lock = PTHREAD_MUTEX_INITIALIZER };+#define MAPFD(name) bpf_map__fd(G.skel->maps.name)-// ---- logging bridge -------------------------------------------------------------------------------------------------static int libbpf_print(enum libbpf_print_level lvl, const char *fmt, va_list ap){if (lvl == LIBBPF_DEBUG) return 0;char buf[1024];vsnprintf(buf, sizeof buf, fmt, ap);size_t n = strlen(buf);- while (n && (buf[n - 1] == '\n')) buf[--n] = 0;+ while (n && buf[n - 1] == '\n') buf[--n] = 0;if (n) pb_core_log("libbpf: %s", buf);return 0;}-// ---- cgroup2 root -----------------------------------------------------------------------------------------------------static int open_cgroup_root(void){- static const char *cands[] = { "/sys/fs/cgroup", "/sys/fs/cgroup/unified", NULL };- for (int i = 0; cands[i]; i++) {+ static const char *const cands[] = { "/sys/fs/cgroup", "/sys/fs/cgroup/unified" };+ for (size_t i = 0; i < sizeof cands / sizeof *cands; i++) {struct statfs sf;if (statfs(cands[i], &sf) == 0 && (unsigned long)sf.f_type == CGROUP2_SUPER_MAGIC)return open(cands[i], O_RDONLY | O_DIRECTORY | O_CLOEXEC);@@ -66,21 +70,13 @@ static int open_cgroup_root(void)return -1;}-// ---- cfg ----------------------------------------------------------------------------------------------------------------static void cfg_set(uint32_t slot, uint32_t val)-{- bpf_map_update_elem(bpf_map__fd(G.skel->maps.cfg), &slot, &val, BPF_ANY);-}--// ---- attach ------------------------------------------------------------------------------------------------------------+// ALLOW_MULTI lets us coexist with other sock_addr programs on the root cgroup.static bool attach(struct bpf_program *prog, enum bpf_attach_type type, int cgfd, bool optional){if (!bpf_program__autoload(prog)) return true;- // ALLOW_MULTI lets us coexist with other sock_addr programs on the root cgroup; fall back to a plain attachLIBBPF_OPTS(bpf_link_create_opts, opts, .flags = BPF_F_ALLOW_MULTI);int lfd = bpf_link_create(bpf_program__fd(prog), cgfd, type, &opts);- if (lfd < 0 && errno == EINVAL)- lfd = bpf_link_create(bpf_program__fd(prog), cgfd, type, NULL);+ if (lfd < 0 && errno == EINVAL) lfd = bpf_link_create(bpf_program__fd(prog), cgfd, type, NULL);if (lfd < 0) {if (optional) return true;pb_core_log("attach %s failed: %s", bpf_program__name(prog), strerror(errno));@@ -92,11 +88,9 @@ static bool attach(struct bpf_program *prog, enum bpf_attach_type type, int cgfdstatic void detach_all(void){- for (int i = 0; i < G.nlinks; i++) close(G.linkfds[i]);- G.nlinks = 0;+ while (G.nlinks) close(G.linkfds[--G.nlinks]);}-// ---- events ------------------------------------------------------------------------------------------------------------static int on_event(void *ctx, void *data, size_t len){(void)ctx;@@ -107,11 +101,64 @@ static int on_event(void *ctx, void *data, size_t len)static void *evt_loop(void *arg){(void)arg;- while (!G.stop) ring_buffer__poll(G.rb, 200);+ struct pollfd p[2] = { { ring_buffer__epoll_fd(G.rb), POLLIN, 0 }, { G.stop_fd, POLLIN, 0 } };+ while (poll(p, 2, -1) >= 0 || errno == EINTR) {+ if (p[1].revents) break;+ if (p[0].revents) ring_buffer__consume(G.rb);+ }return NULL;}-// ---- start / stop -----------------------------------------------------------------------------------------------------+static uint64_t netns_cookie(void)+{+ uint64_t cookie = 0;+ socklen_t len = sizeof cookie;+ int fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);+ if (fd >= 0) {+ if (getsockopt(fd, SOL_SOCKET, SO_NETNS_COOKIE, &cookie, &len) != 0) cookie = 0;+ close(fd);+ }+ return cookie;+}++static bool attach_all(int cgfd)+{+#define ATTACH(prog, type, optional) attach(G.skel->progs.prog, type, cgfd, optional)+ return ATTACH(pb_connect4, BPF_CGROUP_INET4_CONNECT, false) &&+ ATTACH(pb_connect6, BPF_CGROUP_INET6_CONNECT, true) &&+ ATTACH(pb_sendmsg4, BPF_CGROUP_UDP4_SENDMSG, false) &&+ ATTACH(pb_sendmsg6, BPF_CGROUP_UDP6_SENDMSG, true) &&+ ATTACH(pb_recvmsg4, BPF_CGROUP_UDP4_RECVMSG, false) &&+ ATTACH(pb_recvmsg6, BPF_CGROUP_UDP6_RECVMSG, true) &&+ ATTACH(pb_getpeername4, BPF_CGROUP_INET4_GETPEERNAME, true) &&+ ATTACH(pb_getpeername6, BPF_CGROUP_INET6_GETPEERNAME, true) &&+ ATTACH(pb_sockops, BPF_CGROUP_SOCK_OPS, false);+#undef ATTACH+}++// getpeername hooks need a newer kernel than the rest; load without them if the first attempt fails.+static int load_skeleton(void)+{+ G.skel = proxybridge_bpf__open();+ if (!G.skel) return -errno;+ int err = proxybridge_bpf__load(G.skel);+ if (!err) return 0;+ proxybridge_bpf__destroy(G.skel);+ G.skel = proxybridge_bpf__open();+ if (!G.skel) return -errno;+ bpf_program__set_autoload(G.skel->progs.pb_getpeername4, false);+ bpf_program__set_autoload(G.skel->progs.pb_getpeername6, false);+ return proxybridge_bpf__load(G.skel);+}++static void free_tables(void)+{+ for (size_t i = 0; i < G.nexes; i++) free(G.exes[i].path);+ free(G.exes); G.exes = NULL; G.nexes = 0;+ free(G.cls); G.cls = NULL; G.ncls = 0;+ free(G.br); G.br = NULL; G.nbr = 0;+}+int pb_bpf_start(const struct pb_bpf_cfg *cfg, pb_event_cb cb){pthread_mutex_lock(&G.lock);@@ -121,99 +168,85 @@ int pb_bpf_start(const struct pb_bpf_cfg *cfg, pb_event_cb cb)if (geteuid() != 0) { pb_core_log("ProxyBridge needs root (CAP_BPF/CAP_SYS_ADMIN) to load its eBPF programs"); goto out; }libbpf_set_print(libbpf_print);struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };- setrlimit(RLIMIT_MEMLOCK, &rl); // pre-5.11 kernels charge maps to memlock+ setrlimit(RLIMIT_MEMLOCK, &rl);cgfd = open_cgroup_root();if (cgfd < 0) { pb_core_log("cgroup v2 is not mounted (need a unified hierarchy at /sys/fs/cgroup)"); goto out; }- G.skel = proxybridge_bpf__open();- if (!G.skel) { pb_core_log("cannot open BPF object: %s", strerror(errno)); goto out; }- int err = proxybridge_bpf__load(G.skel);+ int err = load_skeleton();if (err) {- // getpeername hooks need kernel >= 5.8; retry without them- proxybridge_bpf__destroy(G.skel);- G.skel = proxybridge_bpf__open();- if (G.skel) {- bpf_program__set_autoload(G.skel->progs.pb_getpeername4, false);- bpf_program__set_autoload(G.skel->progs.pb_getpeername6, false);- err = proxybridge_bpf__load(G.skel);- }- if (err || !G.skel) { pb_core_log("loading the BPF programs failed (kernel needs BTF and cgroup sock_addr support, >= 5.11): %s", strerror(-err ? -err : errno)); goto out; }+ pb_core_log("loading the BPF programs failed (needs a kernel >= 5.11 with BTF and cgroup sock_addr support): %s", strerror(-err));+ goto out;}- { // sockets of other network namespaces (containers) must not be redirected to our loopback relay- int ns = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);- uint64_t cookie = 0; socklen_t cl = sizeof cookie;- if (ns >= 0 && getsockopt(ns, SOL_SOCKET, 71 /* SO_NETNS_COOKIE */, &cookie, &cl) == 0 && cookie) {- cfg_set(PB_CFG_NETNS_LO, (uint32_t)cookie);- cfg_set(PB_CFG_NETNS_HI, (uint32_t)(cookie >> 32));- } else pb_core_log("kernel has no SO_NETNS_COOKIE: connections from other network namespaces are not isolated");- if (ns >= 0) close(ns);- }- cfg_set(PB_CFG_SELF_TGID, cfg->self_tgid);- cfg_set(PB_CFG_TCP_PORT, cfg->tcp_port);- cfg_set(PB_CFG_UDP_PORT, cfg->udp_port);- cfg_set(PB_CFG_LOG, cfg->log);- cfg_set(PB_CFG_DNS_VIA_PROXY, cfg->dns_via_proxy);- cfg_set(PB_CFG_ENABLED, 0);-- bool ok = attach(G.skel->progs.pb_connect4, BPF_CGROUP_INET4_CONNECT, cgfd, false) &&- attach(G.skel->progs.pb_connect6, BPF_CGROUP_INET6_CONNECT, cgfd, true) &&- attach(G.skel->progs.pb_sendmsg4, BPF_CGROUP_UDP4_SENDMSG, cgfd, false) &&- attach(G.skel->progs.pb_sendmsg6, BPF_CGROUP_UDP6_SENDMSG, cgfd, true) &&- attach(G.skel->progs.pb_recvmsg4, BPF_CGROUP_UDP4_RECVMSG, cgfd, false) &&- attach(G.skel->progs.pb_recvmsg6, BPF_CGROUP_UDP6_RECVMSG, cgfd, true) &&- attach(G.skel->progs.pb_getpeername4, BPF_CGROUP_INET4_GETPEERNAME, cgfd, true) &&- attach(G.skel->progs.pb_getpeername6, BPF_CGROUP_INET6_GETPEERNAME, cgfd, true) &&- attach(G.skel->progs.pb_sockops, BPF_CGROUP_SOCK_OPS, cgfd, false);- if (!ok) goto out;+ volatile struct pb_cfg *c = &G.skel->bss->cfg;+ c->tcp_port = cfg->tcp_port;+ c->udp_port = cfg->udp_port;+ c->self_tgid = cfg->self_tgid;+ c->log = cfg->log;+ c->dns_via_proxy = cfg->dns_via_proxy;+ c->netns = netns_cookie();+ if (!c->netns) pb_core_log("kernel has no SO_NETNS_COOKIE: connections from other network namespaces are not isolated");++ if (!attach_all(cgfd)) goto out;G.cb = cb;- G.stop = false;- G.rb = ring_buffer__new(bpf_map__fd(G.skel->maps.events), on_event, NULL, NULL);- if (!G.rb) { pb_core_log("cannot create event ring buffer"); goto out; }- if (pthread_create(&G.evt_thread, NULL, evt_loop, NULL) != 0) { pb_core_log("cannot start event thread"); goto out; }- G.evt_started = true;- G.running = true;+ G.stop_fd = eventfd(0, EFD_CLOEXEC);+ G.rb = ring_buffer__new(MAPFD(events), on_event, NULL, NULL);+ if (G.stop_fd < 0 || !G.rb || pthread_create(&G.evt_thread, NULL, evt_loop, NULL) != 0) {+ pb_core_log("cannot start the event reader");+ goto out;+ }+ G.evt_started = G.running = true;rc = 0;out:if (cgfd >= 0) close(cgfd);if (rc != 0) {detach_all();if (G.rb) { ring_buffer__free(G.rb); G.rb = NULL; }+ if (G.stop_fd >= 0) { close(G.stop_fd); G.stop_fd = -1; }if (G.skel) { proxybridge_bpf__destroy(G.skel); G.skel = NULL; }}pthread_mutex_unlock(&G.lock);return rc;}-void pb_bpf_stop(void)+void pb_bpf_detach(void){pthread_mutex_lock(&G.lock);- if (G.skel) {- G.stop = true;- if (G.evt_started) { pthread_mutex_unlock(&G.lock); pthread_join(G.evt_thread, NULL); pthread_mutex_lock(&G.lock); G.evt_started = false; }- detach_all();- if (G.rb) { ring_buffer__free(G.rb); G.rb = NULL; }- proxybridge_bpf__destroy(G.skel);- G.skel = NULL;+ if (G.evt_started) {+ eventfd_write(G.stop_fd, 1);+ pthread_mutex_unlock(&G.lock);+ pthread_join(G.evt_thread, NULL);+ pthread_mutex_lock(&G.lock);+ G.evt_started = false;}- free(G.exes); G.exes = NULL; G.nexes = 0;- free(G.cls); G.cls = NULL; G.ncls = 0;- G.running = false;+ detach_all();pthread_mutex_unlock(&G.lock);}-bool pb_bpf_running(void) { return G.running; }+void pb_bpf_stop(void)+{+ pb_bpf_detach();+ pthread_mutex_lock(&G.lock);+ if (G.rb) { ring_buffer__free(G.rb); G.rb = NULL; }+ if (G.stop_fd >= 0) { close(G.stop_fd); G.stop_fd = -1; }+ if (G.skel) { proxybridge_bpf__destroy(G.skel); G.skel = NULL; }+ free_tables();+ G.running = false;+ pthread_mutex_unlock(&G.lock);+}void pb_bpf_set_flags(bool log, bool dns_via_proxy){pthread_mutex_lock(&G.lock);- if (G.skel) { cfg_set(PB_CFG_LOG, log); cfg_set(PB_CFG_DNS_VIA_PROXY, dns_via_proxy); }+ if (G.skel) {+ G.skel->bss->cfg.log = log;+ G.skel->bss->cfg.dns_via_proxy = dns_via_proxy;+ }pthread_mutex_unlock(&G.lock);}-// ---- executables --------------------------------------------------------------------------------------------------------static uint32_t kernel_dev(dev_t d) { return (major(d) << 20) | minor(d); }static struct exe_ent *exe_find(uint32_t dev, uint64_t ino)@@ -226,20 +259,21 @@ static struct exe_ent *exe_find(uint32_t dev, uint64_t ino)static struct exe_ent *exe_add(uint32_t dev, uint64_t ino, const char *path){struct exe_ent *e = exe_find(dev, ino);- if (e) { if (path && *path) snprintf(e->path, sizeof e->path, "%s", path); return e; }+ if (e) return e;if (G.nexes >= MAX_KNOWN_EXES) return NULL;- if (!G.exes) { G.exes = calloc(MAX_KNOWN_EXES, sizeof *G.exes); if (!G.exes) return NULL; }+ if (!G.exes && !(G.exes = calloc(MAX_KNOWN_EXES, sizeof *G.exes))) return NULL;+ char *copy = strdup(path ? path : "");+ if (!copy) return NULL;e = &G.exes[G.nexes++];- e->dev = dev; e->ino = ino;- snprintf(e->path, sizeof e->path, "%s", path ? path : "");+ e->dev = dev; e->ino = ino; e->path = copy;return e;}static void strip_deleted(char *p){- size_t n = strlen(p);- static const char suf[] = " (deleted)";- if (n > sizeof suf - 1 && !strcmp(p + n - (sizeof suf - 1), suf)) p[n - (sizeof suf - 1)] = 0;+ static const char suffix[] = " (deleted)";+ size_t n = strlen(p), s = sizeof suffix - 1;+ if (n > s && !strcmp(p + n - s, suffix)) p[n - s] = 0;}static void scan_proc(void)@@ -249,11 +283,11 @@ static void scan_proc(void)struct dirent *de;while ((de = readdir(d))) {if (de->d_name[0] < '1' || de->d_name[0] > '9') continue;- char lnk[300], path[240];- snprintf(lnk, sizeof lnk, "/proc/%.200s/exe", de->d_name);+ char link[300], path[4096];struct stat st;- if (stat(lnk, &st) != 0) continue;- ssize_t n = readlink(lnk, path, sizeof path - 1);+ snprintf(link, sizeof link, "/proc/%.200s/exe", de->d_name);+ if (stat(link, &st) != 0) continue;+ ssize_t n = readlink(link, path, sizeof path - 1);if (n <= 0) continue;path[n] = 0;strip_deleted(path);@@ -262,7 +296,6 @@ static void scan_proc(void)closedir(d);}-// ---- compilation -----------------------------------------------------------------------------------------------------------static void compile_rule(const struct pb_rule_view *v, struct pb_brule *b){const struct pb_rule *r = v->rule;@@ -273,42 +306,41 @@ static void compile_rule(const struct pb_rule_view *v, struct pb_brule *b)if (v->action == RULE_ACTION_PROXY && v->udp_direct) b->flags |= PB_RF_UDP_DIRECT;if (r->any_port) b->flags |= PB_RF_ANY_PORT;- else {- for (int i = 0; i < r->nports; i++) {- if (b->n_port < PB_BPF_MAX_PORT) { b->port[b->n_port].lo = r->ports[i].lo; b->port[b->n_port].hi = r->ports[i].hi; b->n_port++; }- else b->flags |= PB_RF_PORT_COMPLEX;- }+ for (int i = 0; i < r->nports; i++) {+ if (b->n_port < PB_BPF_MAX_PORT) { b->port[b->n_port].lo = r->ports[i].lo; b->port[b->n_port].hi = r->ports[i].hi; b->n_port++; }+ else b->flags |= PB_RF_PORT_COMPLEX;}- if (r->any_host) b->flags |= PB_RF_ANY_HOST;- else {- if (r->ndomains) b->flags |= PB_RF_DOMAINS;- for (int i = 0; i < r->nhosts; i++) {- const struct pb_host_pat *h = &r->hosts[i];- if (h->kind == PB_HOST_V4_RANGE && b->n_v4 < PB_BPF_MAX_V4) { b->v4[b->n_v4].lo = h->lo4; b->v4[b->n_v4].hi = h->hi4; b->n_v4++; }- else if (h->kind == PB_HOST_V6_RANGE) b->flags |= PB_RF_HAS_V6;- else b->flags |= PB_RF_HOST_COMPLEX; // box patterns / too many ranges: let the relay decide- }+ if (r->any_host) { b->flags |= PB_RF_ANY_HOST; return; }+ if (r->ndomains) b->flags |= PB_RF_DOMAINS;+ for (int i = 0; i < r->nhosts; i++) {+ const struct pb_host_pat *h = &r->hosts[i];+ if (h->kind == PB_HOST_V4_RANGE && b->n_v4 < PB_BPF_MAX_V4) { b->v4[b->n_v4].lo = h->lo4; b->v4[b->n_v4].hi = h->hi4; b->n_v4++; }+ else if (h->kind == PB_HOST_V6_RANGE) b->flags |= PB_RF_HAS_V6;+ else b->flags |= PB_RF_HOST_COMPLEX;}}-// a rule that cannot be skipped by later ones: every host, every port, both protocols-static bool rule_is_catchall(const struct pb_brule *b)+// A catch-all rule shadows every later one.+static bool is_catchall(const struct pb_brule *b){return (b->flags & PB_RF_ANY_HOST) && (b->flags & PB_RF_ANY_PORT) && b->proto_mask == 3;}-static int class_for(const struct pb_rule_view *v, const struct pb_brule *br, size_t n, const char *path, struct pb_bclass *out)+static void class_for(const struct pb_rule_view *v, const struct pb_brule *br, size_t n, const char *path, struct pb_bclass *out){memset(out, 0, sizeof *out);for (size_t i = 0; i < n; i++) {- if (!v[i].rule->enabled) continue;- if (!pb_rule_match_process(v[i].rule, path)) continue;+ if (!v[i].rule->enabled || !pb_rule_match_process(v[i].rule, path)) continue;if (pb_rule_has_domains(v[i].rule)) out->tap = 1;- if (out->n >= PB_RULES_PER_CLASS) { memset(out, 0, sizeof *out); out->n = PB_CLASS_DECIDE; out->tap = 1; return 0; }+ if (out->n >= PB_RULES_PER_CLASS) {+ memset(out->rule, 0, sizeof out->rule);+ out->n = PB_CLASS_DECIDE;+ out->tap = 1;+ return;+ }out->rule[out->n++] = (uint32_t)i;- if (rule_is_catchall(&br[i])) break; // nothing after a catch-all can apply+ if (is_catchall(&br[i])) return;}- return 0;}static int class_intern(const struct pb_bclass *c)@@ -320,9 +352,39 @@ static int class_intern(const struct pb_bclass *c)return (int)G.ncls++;}-static void write_class_slot(uint32_t id)+static void write_class(uint32_t id)+{+ bpf_map_update_elem(MAPFD(classes), &id, &G.cls[id], BPF_ANY);+}++static void install_exe(const struct exe_ent *e, const struct pb_rule_view *v, size_t n){- bpf_map_update_elem(bpf_map__fd(G.skel->maps.classes), &id, &G.cls[id], BPF_ANY);+ struct pb_bclass c;+ class_for(v, G.br, n, e->path, &c);+ struct pb_exe_key key = { .dev = e->dev, .ino = e->ino };+ int id = class_intern(&c);+ if (id < 0) { bpf_map_delete_elem(MAPFD(exe2class), &key); return; }+ uint32_t cid = (uint32_t)id;+ write_class((uint32_t)id);+ bpf_map_update_elem(MAPFD(exe2class), &key, &cid, BPF_ANY);+}++static size_t installed_keys(struct pb_exe_key **out)+{+ size_t n = 0, cap = 0;+ struct pb_exe_key *keys = NULL, cur, next;+ int fd = MAPFD(exe2class), rc = bpf_map_get_next_key(fd, NULL, &next);+ while (rc == 0) {+ if (n == cap) {+ struct pb_exe_key *grown = realloc(keys, (cap ? cap * 2 : 256) * sizeof *keys);+ if (!grown) break;+ keys = grown; cap = cap ? cap * 2 : 256;+ }+ keys[n++] = cur = next;+ rc = bpf_map_get_next_key(fd, &cur, &next);+ }+ *out = keys;+ return n;}int pb_bpf_sync(const struct pb_rule_view *v, size_t n)@@ -334,123 +396,100 @@ int pb_bpf_sync(const struct pb_rule_view *v, size_t n)struct pb_brule *br = calloc(n ? n : 1, sizeof *br);if (!G.cls) G.cls = calloc(PB_MAX_CLASSES, sizeof *G.cls);if (!br || !G.cls) { free(br); pthread_mutex_unlock(&G.lock); return -1; }+ free(G.br);+ G.br = br; G.nbr = n;- size_t active = 0;+ bool active = false, domains = false;for (size_t i = 0; i < n; i++) {compile_rule(&v[i], &br[i]);uint32_t k = (uint32_t)i;- bpf_map_update_elem(bpf_map__fd(G.skel->maps.brules), &k, &br[i], BPF_ANY);- if (v[i].rule->enabled) active++;+ bpf_map_update_elem(MAPFD(brules), &k, &br[i], BPF_ANY);+ if (v[i].rule->enabled) {+ active = true;+ domains |= pb_rule_has_domains(v[i].rule) != 0;+ }}scan_proc();- G.ncls = 0;memset(G.cls, 0, PB_MAX_CLASSES * sizeof *G.cls);- G.ncls = 1; // class 0 = no rule applies (direct)- int mapfd = bpf_map__fd(G.skel->maps.exe2class);-- // remember what was installed so entries for vanished binaries can be dropped- struct pb_exe_key k = {}, next;- struct pb_exe_key *old = NULL; size_t nold = 0, capold = 0;- int ret = bpf_map_get_next_key(mapfd, NULL, &next);- while (ret == 0) {- if (nold == capold) { capold = capold ? capold * 2 : 256; old = realloc(old, capold * sizeof *old); if (!old) break; }- old[nold++] = next;- k = next;- ret = bpf_map_get_next_key(mapfd, &k, &next);- }-- for (size_t i = 0; i < G.nexes; i++) {- struct pb_bclass c;- class_for(v, br, n, G.exes[i].path, &c);- int id = class_intern(&c);- struct pb_exe_key key = { .dev = G.exes[i].dev, .ino = G.exes[i].ino };- if (id < 0) { bpf_map_delete_elem(mapfd, &key); continue; } // out of classes: slow path- uint32_t cid = (uint32_t)id;- bpf_map_update_elem(mapfd, &key, &cid, BPF_ANY);- }- for (size_t i = 0; i < G.ncls; i++) write_class_slot((uint32_t)i);- for (size_t i = 0; i < nold; i++)- if (!exe_find(old[i].dev, old[i].ino)) bpf_map_delete_elem(mapfd, &old[i]);- free(old);- free(br);-- bool domains = false;- for (size_t i = 0; i < n; i++) domains |= v[i].rule->enabled && pb_rule_has_domains(v[i].rule);- cfg_set(PB_CFG_DNS_TAP, domains ? 1 : 0);- G.have_rules = active > 0;- cfg_set(PB_CFG_ENABLED, G.have_rules ? 1 : 0);+ G.ncls = 1; // class 0: no rule applies+ struct pb_exe_key *stale;+ size_t nstale = installed_keys(&stale);+ for (size_t i = 0; i < G.nexes; i++) install_exe(&G.exes[i], v, n);+ write_class(0);+ for (size_t i = 0; i < nstale; i++)+ if (!exe_find(stale[i].dev, stale[i].ino)) bpf_map_delete_elem(MAPFD(exe2class), &stale[i]);+ free(stale);++ G.skel->bss->cfg.dns_tap = domains;+ G.skel->bss->cfg.enabled = active;pthread_mutex_unlock(&G.lock);return 0;}void pb_bpf_learn(const struct pb_orig *o, const char *exe_path, const struct pb_rule_view *v, size_t n){- if (!o->exe_ino || n > PB_MAX_RULES) return;+ if (!o->exe_ino) return;pthread_mutex_lock(&G.lock);- if (!G.skel || !G.cls) { pthread_mutex_unlock(&G.lock); return; }- struct exe_ent *known = exe_find(o->exe_dev, o->exe_ino);- struct exe_ent *e = known ? NULL : exe_add(o->exe_dev, o->exe_ino, exe_path); // already classified: nothing to learn- if (e) {- struct pb_brule *br = calloc(n ? n : 1, sizeof *br);- if (br) {- for (size_t i = 0; i < n; i++) compile_rule(&v[i], &br[i]);- struct pb_bclass c;- class_for(v, br, n, e->path, &c);- int id = class_intern(&c);- if (id >= 0) {- write_class_slot((uint32_t)id);- struct pb_exe_key key = { .dev = e->dev, .ino = e->ino };- uint32_t cid = (uint32_t)id;- bpf_map_update_elem(bpf_map__fd(G.skel->maps.exe2class), &key, &cid, BPF_ANY);- }- free(br);- }+ if (G.skel && G.cls && n == G.nbr && !exe_find(o->exe_dev, o->exe_ino)) {+ struct exe_ent *e = exe_add(o->exe_dev, o->exe_ino, exe_path);+ if (e) install_exe(e, v, n);}pthread_mutex_unlock(&G.lock);}-// ---- lookups for the relay --------------------------------------------------------------------------------------------------int pb_bpf_take_tcp_orig(uint16_t client_port, struct pb_orig *out)+void pb_bpf_set_exempt(const uint32_t *tgids, size_t n){- uint32_t key = client_port;- int fd = G.skel ? bpf_map__fd(G.skel->maps.by_port) : -1;- if (fd < 0 || bpf_map_lookup_elem(fd, &key, out) != 0) return -1;- bpf_map_delete_elem(fd, &key);- return 0;-}--int pb_bpf_get_udp_flow(uint32_t flow_ip_be, struct pb_orig *out)-{- int fd = G.skel ? bpf_map__fd(G.skel->maps.flows) : -1;- return (fd >= 0 && bpf_map_lookup_elem(fd, &flow_ip_be, out) == 0) ? 0 : -1;+ pthread_mutex_lock(&G.lock);+ if (!G.skel) { pthread_mutex_unlock(&G.lock); return; }+ int fd = MAPFD(exempt);+ uint32_t cur, next, stale[MAX_EXEMPT];+ size_t nstale = 0;+ for (int rc = bpf_map_get_next_key(fd, NULL, &next); rc == 0 && nstale < MAX_EXEMPT; rc = bpf_map_get_next_key(fd, &cur, &next)) {+ cur = next;+ bool keep = false;+ for (size_t i = 0; i < n && !keep; i++) keep = tgids[i] == cur;+ if (!keep) stale[nstale++] = cur;+ }+ for (size_t i = 0; i < nstale; i++) bpf_map_delete_elem(fd, &stale[i]);+ uint8_t one = 1;+ size_t count = n < MAX_EXEMPT ? n : MAX_EXEMPT;+ for (size_t i = 0; i < count; i++) bpf_map_update_elem(fd, &tgids[i], &one, BPF_ANY);+ G.skel->bss->cfg.n_exempt = (uint32_t)count;+ pthread_mutex_unlock(&G.lock);}-// ---- domain rules ------------------------------------------------------------------------------------------------------------void pb_bpf_dom_set(uint32_t rule_idx, uint32_t ip_host){if (!G.skel) return;struct pb_dom_key k = { .rule = rule_idx, .ip = ip_host };uint8_t one = 1;- bpf_map_update_elem(bpf_map__fd(G.skel->maps.dom_hit), &k, &one, BPF_ANY);+ bpf_map_update_elem(MAPFD(dom_hit), &k, &one, BPF_ANY);}void pb_bpf_dom_clear(void){if (!G.skel) return;- int fd = bpf_map__fd(G.skel->maps.dom_hit);+ int fd = MAPFD(dom_hit);struct pb_dom_key k, next;- int rc = bpf_map_get_next_key(fd, NULL, &next);- while (rc == 0) {+ for (int rc = bpf_map_get_next_key(fd, NULL, &next); rc == 0;) {k = next;rc = bpf_map_get_next_key(fd, &k, &next);bpf_map_delete_elem(fd, &k);}}-void pb_bpf_set_dns_tap(bool on)+int pb_bpf_take_tcp_orig(uint32_t client_ip_be, uint16_t client_port, struct pb_orig *out){- pthread_mutex_lock(&G.lock);- if (G.skel) cfg_set(PB_CFG_DNS_TAP, on ? 1 : 0);- pthread_mutex_unlock(&G.lock);+ if (!G.skel) return -1;+ struct pb_port_key key = { .ip = client_ip_be, .port = client_port };+ int fd = MAPFD(by_port);+ if (bpf_map_lookup_elem(fd, &key, out) != 0) return -1;+ bpf_map_delete_elem(fd, &key);+ return 0;+}++int pb_bpf_get_udp_flow(uint32_t flow_ip_be, struct pb_orig *out)+{+ return G.skel && bpf_map_lookup_elem(MAPFD(flows), &flow_ip_be, out) == 0 ? 0 : -1;}diff --git a/Linux/src/pb_bpf.h b/Linux/src/pb_bpf.hindex 2a4c7da..56abe6b 100644--- a/Linux/src/pb_bpf.h+++ b/Linux/src/pb_bpf.h@@ -1,4 +1,4 @@-// eBPF backend: loads/attaches the datapath, compiles rules into BPF maps, reads flow events.+// eBPF backend: loads and attaches the datapath, compiles rules into BPF maps, delivers flow events.#ifndef PB_BPF_H#define PB_BPF_H@@ -7,40 +7,41 @@#include "bpf/pb_bpf_shared.h"struct pb_bpf_cfg {- uint16_t tcp_port, udp_port; // relay ports (already bound by the relay)- uint32_t self_tgid; // process hosting the relay; never redirected+ uint16_t tcp_port, udp_port;+ uint32_t self_tgid;bool log;bool dns_via_proxy;};-// One rule as seen by the compiler: the parsed rule plus its resolved proxy.+// A rule as seen by the compiler: the parsed rule plus its effective action and proxy.struct pb_rule_view {const struct pb_rule *rule;- int action; // effective action (PROXY with no usable proxy has already become BLOCK)- uint16_t proxy_id; // resolved (0 for DIRECT/BLOCK)- bool udp_direct; // PROXY rule whose proxy is HTTP: UDP goes direct+ int action; // PROXY with no usable proxy has already become BLOCK+ uint16_t proxy_id;+ bool udp_direct; // the proxy cannot carry UDP};typedef void (*pb_event_cb)(const struct pb_event *e);-// Returns 0 on success; on failure returns -1 after logging the reason (kernel too old, not root, no cgroup2, verifier...).+// Returns 0, or -1 after logging why (not root, kernel too old, no cgroup2, verifier...).int pb_bpf_start(const struct pb_bpf_cfg *cfg, pb_event_cb cb);+// Detaches the hooks and stops the event reader; the maps stay valid until pb_bpf_stop() (relay threads may still look up).+void pb_bpf_detach(void);void pb_bpf_stop(void);-bool pb_bpf_running(void);void pb_bpf_set_flags(bool log, bool dns_via_proxy);-// Recompiles the rule set (and rescans /proc for running executables). Returns -1 if it does not fit (too many rules).+// Recompiles the rule set and rescans /proc for running executables. -1 if it does not fit.int pb_bpf_sync(const struct pb_rule_view *v, size_t n);-// Slow-path learning: install the class for the exact executable key the kernel reported in `o`, using the same rule set-// that decide() just evaluated.+// Installs the class of the executable the kernel reported in `o` (slow-path learning); no-op for known binaries.void pb_bpf_learn(const struct pb_orig *o, const char *exe_path, const struct pb_rule_view *v, size_t n);+// Processes (tgids) whose traffic is never redirected, e.g. the local proxy itself.+void pb_bpf_set_exempt(const uint32_t *tgids, size_t n);-// Domain rules: (rule index, address) pairs whose DNS name matches. Set by the DNS tap before the answer reaches the client.+// (rule, address) pairs whose DNS name matches a domain rule.void pb_bpf_dom_set(uint32_t rule_idx, uint32_t ip_host);void pb_bpf_dom_clear(void);-void pb_bpf_set_dns_tap(bool on);-int pb_bpf_take_tcp_orig(uint16_t client_port, struct pb_orig *out);+int pb_bpf_take_tcp_orig(uint32_t client_ip_be, uint16_t client_port, struct pb_orig *out);int pb_bpf_get_udp_flow(uint32_t flow_ip_be, struct pb_orig *out);#endifdiff --git a/Linux/src/pb_dns.c b/Linux/src/pb_dns.cindex 8906d48..c78050a 100644--- a/Linux/src/pb_dns.c+++ b/Linux/src/pb_dns.c@@ -95,7 +95,6 @@ static void add_mapping(uint32_t ip, char names[][256], int nn, struct pb_dns_re}}-// ---- wire format -----------------------------------------------------------------------------------------------------// Reads a (possibly compressed) name at *off into out (lower-case, dotted). Advances *off past the name as stored at that// position. Returns false on malformed data.@@ -150,7 +149,6 @@ int pb_dns_observe(const uint8_t *m, size_t len, struct pb_dns_result *res)}uint32_t ips[64]; int nips = 0;- // first pass collects the chain of names (CNAME owners/targets and A owners), second pass assigns them to every addressstruct { size_t rdata; uint16_t type, rdlen; char owner[256]; } rr[128];int nrr = 0;for (int i = 0; i < an; i++) {@@ -163,12 +161,10 @@ int pb_dns_observe(const uint8_t *m, size_t len, struct pb_dns_result *res)off = rd + rdlen;}for (int i = 0; i < nrr; i++) {- bool addname = false;char target[256];if (rr[i].type == 5) { // CNAME: owner and target are both names of the final addresssize_t o2 = rr[i].rdata;if (read_name(m, len, &o2, target, sizeof target)) {- addname = true;for (int pass = 0; pass < 2; pass++) {const char *nm = pass ? target : rr[i].owner;bool dup = false;@@ -184,7 +180,6 @@ int pb_dns_observe(const uint8_t *m, size_t len, struct pb_dns_result *res)if (!dup && nn < PB_DNS_MAX_NAMES) strcpy(names[nn++], rr[i].owner);}}- (void)addname;}if (!nips || !nn) return 0;diff --git a/Linux/src/pb_internal.h b/Linux/src/pb_internal.hindex 83e72f0..7a15989 100644--- a/Linux/src/pb_internal.h+++ b/Linux/src/pb_internal.h@@ -1,10 +1,4 @@-// Internal interfaces shared by the ProxyBridge Linux modules (eBPF backend).-//-// proxybridge.bpf.c kernel side: rewrites connect()/sendmsg() destinations to the relay-// pb_rules.c rule store, validation, full userspace matcher-// pb_bpf.c loads/attaches BPF, compiles rules into BPF maps, reads events-// pb_relay.c userspace relay: TCP (SOCKS5 / HTTP CONNECT), UDP (SOCKS5 UDP ASSOCIATE), DIRECT-// ProxyBridge.c public API glue+// Interfaces between the ProxyBridge modules: core (ProxyBridge.c, pb_bpf.c), kernel program, relay (pb_relay.c).#ifndef PB_INTERNAL_H#define PB_INTERNAL_H@@ -14,108 +8,87 @@#include <sys/socket.h>#include "ProxyBridge.h"-#define PB_TCP_RELAY_PORT_DEFAULT 24010 // outside the default ephemeral range 32768-60999+#define PB_TCP_RELAY_PORT_DEFAULT 24010 // outside the default ephemeral port range#define PB_UDP_RELAY_PORT_DEFAULT 24011-// ----------------------------------------------------------------------------------------------// Decision values-// ----------------------------------------------------------------------------------------------#define PB_ACT_PROXY 0 // matches RuleAction+#define PB_ACT_PROXY 0 // same values as RuleAction#define PB_ACT_DIRECT 1#define PB_ACT_BLOCK 2-#define PB_ACT_DECIDE 3 // kernel could not decide: relay must call pb_core_decide()+#define PB_ACT_DECIDE 3 // the kernel could not decide: the relay calls pb_core_decide()-// ----------------------------------------------------------------------------------------------// Original destination record. Produced by the BPF programs, looked up by the relay.-// Layout is shared with the BPF object: keep in sync with proxybridge.bpf.c (struct pb_orig).-// ---------------------------------------------------------------------------------------------+// Original destination of a redirected flow; layout shared with proxybridge.bpf.c.struct pb_orig {- uint8_t addr[16]; // original destination, network order. IPv4 is stored as ::ffff:a.b.c.d- uint16_t port; // original destination port, host order- uint16_t proxy_id; // valid when action == PB_ACT_PROXY+ uint8_t addr[16]; // network order; IPv4 as ::ffff:a.b.c.d+ uint16_t port; // host order+ uint16_t proxy_id;uint32_t pid; // tgid of the process that opened the flow- uint8_t family; // AF_INET or AF_INET6 (of the ORIGINAL destination)+ uint8_t family; // AF_INET or AF_INET6 of the original destinationuint8_t proto; // IPPROTO_TCP or IPPROTO_UDP- uint8_t action; // PB_ACT_PROXY or PB_ACT_DECIDE (DIRECT/BLOCK never reach the relay from the kernel)+ uint8_t action; // PB_ACT_PROXY or PB_ACT_DECIDEuint8_t pad;- uint32_t exe_dev; // kernel-side (dev, inode) of the process's executable (valid for PB_ACT_DECIDE flows)+ uint32_t exe_dev; // kernel-side identity of the executable (PB_ACT_DECIDE flows)uint32_t exe_pad;uint64_t exe_ino;};-// Result of a userspace decision (slow path).struct pb_decision {- int action; // PB_ACT_PROXY / PB_ACT_DIRECT / PB_ACT_BLOCK- uint32_t proxy_id; // for PB_ACT_PROXY+ int action; // PB_ACT_PROXY, PB_ACT_DIRECT or PB_ACT_BLOCK+ uint32_t proxy_id;};-// A configured upstream proxy (snapshot copy handed to the relay; the relay owns the copy).struct pb_proxy {uint32_t id;- ProxyType type; // PROXY_TYPE_HTTP / PROXY_TYPE_SOCKS5+ ProxyType type;char name[64];- char host[256]; // IP literal or hostname (relay must resolve it, with a timeout, outside the epoll loop)+ char host[256]; // IP literal or host nameuint16_t port;- char user[256]; // empty string = no auth+ char user[256]; // empty = no authenticationchar pass[256];};-// ----------------------------------------------------------------------------------------------// Services the CORE provides to the relay (implemented in pb_bpf.c / ProxyBridge.c)-// ---------------------------------------------------------------------------------------------+// ---- provided by the core -----// TCP: original destination for a relayed connection, keyed by the *client's* source port as seen by the relay-// (accept() peer port; peer address is 127.0.0.1). Consumes (deletes) the entry. Returns 0 on success.-int pb_core_take_tcp_orig(uint16_t client_port, struct pb_orig *out);+// Original destination of a relayed TCP connection, keyed by the client's source address and port as accept() reports them.+// Consumes the entry; 0 on success.+int pb_core_take_tcp_orig(uint32_t client_ip_be, uint16_t client_port, struct pb_orig *out);-// UDP: original destination for a datagram, keyed by the loopback address it was sent to (IP_PKTINFO ipi_addr, network-// order). Does not delete (flows are shared and LRU-evicted). Returns 0 on success.+// Original destination behind a UDP flow address (the IP_PKTINFO destination of a datagram). Does not consume.int pb_core_get_udp_flow(uint32_t flow_ip_be, struct pb_orig *out);-// Slow-path decision for a pb_orig with action == PB_ACT_DECIDE (evaluates the full rule set for o->pid).+// Full rule evaluation for a PB_ACT_DECIDE flow.void pb_core_decide(const struct pb_orig *o, struct pb_decision *out);-// Copies the proxy config with this id (or the default proxy when id == 0). Returns 0 on success, -1 if unknown.+// Copy of the proxy with this id, or of the default proxy for id 0. 0 on success.int pb_core_get_proxy(uint32_t id, struct pb_proxy *out);-// Logging / events. Both thread-safe, may be called from any relay thread.void pb_core_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));-// One event per relayed flow after the final action is known (proxy_desc e.g. "SOCKS5 127.0.0.1:1080" / "DIRECT" / "BLOCK").-void pb_core_flow_event(const struct pb_orig *o, int action, const char *proxy_desc);-// DNS tap. The relay calls this for every DNS message travelling server->client on a flow whose ORIGINAL destination port is 53:-// the payload of each UDP reply datagram, or each complete TCP-DNS message (2-byte length prefix already stripped). It must be-// called BEFORE the message is delivered to the client, because the core uses it to arm kernel rules for the addresses in the-// answer. Thread-safe and cheap when no domain rules exist (returns immediately).+// Reports a relayed flow once its final action is known.+void pb_core_flow_event(const struct pb_orig *o, int action);++// DNS tap: called for every DNS message travelling server-to-client on a flow whose original port is 53 (UDP payload, or one+// complete TCP message without its length prefix), before the client receives it.void pb_core_dns_observe(const uint8_t *msg, size_t len);-// Whether DNS (UDP/TCP port 53) should be sent through the proxy even if rules say DIRECT is not set. Informational.-bool pb_core_dns_via_proxy(void);+// ---- provided by the relay -----// ----------------------------------------------------------------------------------------------// Services the RELAY provides to the core (implemented in pb_relay.c)-// ---------------------------------------------------------------------------------------------struct pb_relay_cfg {- uint16_t tcp_port; // listen port on 127.0.0.1 (0 = PB_TCP_RELAY_PORT_DEFAULT)- uint16_t udp_port; // UDP listen port, bound with SO_BINDTODEVICE "lo" (0 = default)- int max_tcp_conns; // hard cap on concurrent relayed TCP connections (0 = 32768)+ uint16_t tcp_port; // 0 = default+ uint16_t udp_port; // 0 = default+ int max_tcp_conns; // 0 = 32768int tcp_idle_timeout_s; // 0 = 300int udp_idle_timeout_s; // 0 = 60- int handshake_timeout_s; // proxy connect + handshake budget (0 = 10)+ int handshake_timeout_s; // 0 = 10};-// Binds the sockets (returns -1 and logs via pb_core_log on failure, leaving nothing running), starts the worker threads.+// Returns -1 (after logging) and leaves nothing running on failure.int pb_relay_start(const struct pb_relay_cfg *cfg);-// Stops all threads, closes every fd (listeners, client/upstream sockets, epoll, eventfds). Safe to call twice. After it-// returns, pb_relay_start() must work again (no leaked listeners).+// Stops every thread and closes every fd; safe to call twice and to start again afterwards.void pb_relay_stop(void);-// Actual ports in use (valid after a successful start).uint16_t pb_relay_tcp_port(void);uint16_t pb_relay_udp_port(void);-// Synchronous proxy test used by ProxyBridge_TestConnection: connects to `target_host:target_port` THROUGH `proxy` and sends-// an HTTP HEAD/GET if port is 80/443-ish (caller decides); returns bytes of response in buf (NUL-terminated) or -1 on error with-// a human readable reason in buf. Must not depend on relay_start(). 10 second budget.+// Blocking test of a proxy: tunnels to target_host:target_port and writes a one-line result (or the error) to buf. 0 on success.int pb_relay_test_proxy(const struct pb_proxy *proxy, const char *target_host, uint16_t target_port, char *buf, size_t buflen);#endifdiff --git a/Linux/src/pb_proc.c b/Linux/src/pb_proc.cnew file mode 100644index 0000000..93c8fc3--- /dev/null+++ b/Linux/src/pb_proc.c@@ -0,0 +1,77 @@+#include <arpa/inet.h>+#include <dirent.h>+#include <ifaddrs.h>+#include <netinet/in.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <unistd.h>+#include "pb_proc.h"++#define MAX_INODES 8++static size_t listen_inodes(uint32_t ip_be, uint16_t port, uint64_t *inodes)+{+ FILE *f = fopen("/proc/net/tcp", "r");+ if (!f) return 0;+ char line[512];+ size_t n = 0;+ if (!fgets(line, sizeof line, f)) { fclose(f); return 0; }+ while (n < MAX_INODES && fgets(line, sizeof line, f)) {+ unsigned addr, lport, state;+ unsigned long long inode;+ // sl local rem st tx:rx tr:when retrnsmt uid timeout inode+ if (sscanf(line, " %*d: %x:%x %*x:%*x %x %*x:%*x %*x:%*x %*x %*d %*d %llu", &addr, &lport, &state, &inode) != 4) continue;+ if (state == 0x0A && lport == port && inode && (addr == ip_be || addr == 0)) inodes[n++] = inode;+ }+ fclose(f);+ return n;+}++static bool pid_has_socket(const char *pid, uint64_t inode)+{+ char dir[300], link[400], want[40], got[64];+ snprintf(dir, sizeof dir, "/proc/%.200s/fd", pid);+ snprintf(want, sizeof want, "socket:[%llu]", (unsigned long long)inode);+ DIR *d = opendir(dir);+ if (!d) return false;+ struct dirent *de;+ bool found = false;+ while (!found && (de = readdir(d))) {+ if (de->d_name[0] == '.') continue;+ snprintf(link, sizeof link, "%s/%.40s", dir, de->d_name);+ ssize_t r = readlink(link, got, sizeof got - 1);+ if (r > 0) { got[r] = 0; found = !strcmp(got, want); }+ }+ closedir(d);+ return found;+}++size_t pb_proc_listeners(uint32_t ip_be, uint16_t port, uint32_t *tgids, size_t max)+{+ uint64_t inodes[MAX_INODES];+ size_t ni = listen_inodes(ip_be, port, inodes), n = 0;+ if (!ni) return 0;+ DIR *d = opendir("/proc");+ if (!d) return 0;+ struct dirent *de;+ while (n < max && (de = readdir(d))) {+ if (de->d_name[0] < '1' || de->d_name[0] > '9') continue;+ for (size_t i = 0; i < ni; i++)+ if (pid_has_socket(de->d_name, inodes[i])) { tgids[n++] = (uint32_t)strtoul(de->d_name, NULL, 10); break; }+ }+ closedir(d);+ return n;+}++bool pb_proc_is_local_ip(uint32_t ip_be)+{+ if ((ntohl(ip_be) >> 24) == 127) return true;+ struct ifaddrs *list, *a;+ if (getifaddrs(&list) != 0) return false;+ bool local = false;+ for (a = list; a && !local; a = a->ifa_next)+ local = a->ifa_addr && a->ifa_addr->sa_family == AF_INET && ((struct sockaddr_in *)a->ifa_addr)->sin_addr.s_addr == ip_be;+ freeifaddrs(list);+ return local;+}diff --git a/Linux/src/pb_proc.h b/Linux/src/pb_proc.hnew file mode 100644index 0000000..c5e4986--- /dev/null+++ b/Linux/src/pb_proc.h@@ -0,0 +1,15 @@+// /proc helpers: which processes listen on a local TCP port, and which addresses belong to this host.+#ifndef PB_PROC_H+#define PB_PROC_H++#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>++// tgids of processes with a TCP socket in LISTEN state on `port` bound to `ip_be` or to 0.0.0.0. Returns the count (<= max).+size_t pb_proc_listeners(uint32_t ip_be, uint16_t port, uint32_t *tgids, size_t max);++// True for 127.0.0.0/8 and for any IPv4 address configured on a local interface.+bool pb_proc_is_local_ip(uint32_t ip_be);++#endifdiff --git a/Linux/src/pb_rules.c b/Linux/src/pb_rules.cindex e6a4bdf..de231af 100644--- a/Linux/src/pb_rules.c+++ b/Linux/src/pb_rules.c@@ -18,8 +18,6 @@ static void set_err(char *err, size_t n, const char *fmt, ...)va_end(ap);}-// ---- tokenising -------------------------------------------------------------------------------------------------------// Splits on ';' or ',' and trims whitespace. Returns the number of tokens (<= max) or -1 if there are more than max.static int split_list(const char *s, char tokens[][256], int max){@@ -42,8 +40,6 @@ static int split_list(const char *s, char tokens[][256], int max)return n;}-// ---- glob -------------------------------------------------------------------------------------------------------------bool pb_glob_match(const char *p, const char *s){const char *star = NULL, *ss = s;@@ -57,8 +53,6 @@ bool pb_glob_match(const char *p, const char *s)return *p == 0;}-// ---- parsing helpers --------------------------------------------------------------------------------------------------static bool parse_uint(const char *s, size_t len, unsigned max, unsigned *out){if (!len || len > 5) return false;@@ -75,7 +69,6 @@ static bool parse_uint(const char *s, size_t len, unsigned max, unsigned *out)static bool parse_ipv4(const char *s, uint32_t *out){struct in_addr a;- // inet_pton rejects leading garbage / short forms, which is what we want for validationif (inet_pton(AF_INET, s, &a) != 1) return false;*out = ntohl(a.s_addr);return true;@@ -111,7 +104,6 @@ static bool v6_prefix_range(const uint8_t *base, unsigned prefix, uint8_t *lo, ustatic bool looks_like_domain(const char *tok){- // anything that is not purely IP-ish: contains a letter (other than none), '?' or a '*' attached to lettersfor (const char *c = tok; *c; c++)if (isalpha((unsigned char)*c) || *c == '_' || *c == '?') return true;return false;@@ -147,7 +139,7 @@ bool pb_domain_match(const char *pattern, const char *name)static bool parse_host_token(const char *tok, struct pb_host_pat *p, char *err, size_t errlen){memset(p, 0, sizeof *p);- if (strchr(tok, ':')) { // ---- IPv6+ if (strchr(tok, ':')) {char buf[256];snprintf(buf, sizeof buf, "%s", tok);char *slash = strchr(buf, '/'), *dash = strchr(buf, '-');@@ -176,7 +168,7 @@ bad6:const char *slash = strchr(tok, '/'), *dash = strchr(tok, '-');uint32_t a, b;char buf[256];- if (slash) { // ---- IPv4 CIDR+ if (slash) {snprintf(buf, sizeof buf, "%.*s", (int)(slash - tok), tok);unsigned pre;if (!parse_ipv4(buf, &a) || !parse_uint(slash + 1, strlen(slash + 1), 32, &pre)) goto bad4;@@ -186,14 +178,13 @@ bad6:}int dots_before = 0;for (const char *c = tok; dash && c < dash; c++) dots_before += *c == '.';- if (dash && dots_before == 3) { // ---- IPv4 a.b.c.d-e.f.g.h+ if (dash && dots_before == 3) {snprintf(buf, sizeof buf, "%.*s", (int)(dash - tok), tok);if (!parse_ipv4(buf, &a) || !parse_ipv4(dash + 1, &b)) goto bad4;if (a > b) { set_err(err, errlen, "IPv4 range '%s' has start > end", tok); return false; }p->kind = PB_HOST_V4_RANGE; p->lo4 = a; p->hi4 = b;return true;}- // ---- IPv4 with per-octet '*' or 'lo-hi'const char *s = tok;for (int i = 0; i < 4; i++) {const char *e = strchr(s, '.');@@ -202,10 +193,10 @@ bad6:if (!parse_octet(s, len, &p->box_lo[i], &p->box_hi[i])) goto bad4;s = e ? e + 1 : s + len;}- // exact address or a contiguous prefix box collapses to a numeric range+ // a box whose wildcard octets form a suffix collapses to a numeric range{int i = 0;- while (i < 4 && p->box_lo[i] == p->box_hi[i]) i++; // leading fixed octets+ while (i < 4 && p->box_lo[i] == p->box_hi[i]) i++;bool contiguous = true;if (i < 4) {for (int j = i + 1; j < 4; j++)@@ -248,8 +239,6 @@ static bool parse_port_token(const char *tok, struct pb_port_range *r, char *errreturn true;}-// ---- public: parse / free / clone -------------------------------------------------------------------------------------void pb_rule_free(struct pb_rule *r){free(r->procs); free(r->hosts); free(r->ports); free(r->domains);@@ -257,24 +246,6 @@ void pb_rule_free(struct pb_rule *r)r->nprocs = r->nhosts = r->nports = r->ndomains = 0;}-bool pb_rule_clone(struct pb_rule *dst, const struct pb_rule *src)-{- *dst = *src;- dst->procs = NULL; dst->hosts = NULL; dst->ports = NULL; dst->domains = NULL;- if (src->nprocs && !(dst->procs = malloc(sizeof(*dst->procs) * (size_t)src->nprocs))) goto oom;- if (src->nhosts && !(dst->hosts = malloc(sizeof(*dst->hosts) * (size_t)src->nhosts))) goto oom;- if (src->nports && !(dst->ports = malloc(sizeof(*dst->ports) * (size_t)src->nports))) goto oom;- if (src->ndomains && !(dst->domains = malloc(sizeof(*dst->domains) * (size_t)src->ndomains))) goto oom;- if (src->nprocs) memcpy(dst->procs, src->procs, sizeof(*dst->procs) * (size_t)src->nprocs);- if (src->nhosts) memcpy(dst->hosts, src->hosts, sizeof(*dst->hosts) * (size_t)src->nhosts);- if (src->nports) memcpy(dst->ports, src->ports, sizeof(*dst->ports) * (size_t)src->nports);- if (src->ndomains) memcpy(dst->domains, src->domains, sizeof(*dst->domains) * (size_t)src->ndomains);- return true;-oom:- pb_rule_free(dst);- return false;-}-static bool is_any(const char *s){while (isspace((unsigned char)*s)) s++;@@ -299,7 +270,6 @@ bool pb_rule_parse(struct pb_rule *out, const char *process, const char *hosts,char (*tok)[256] = malloc(sizeof(char[256]) * PB_MAX_PATTERNS);if (!tok) { set_err(err, errlen, "out of memory"); return false; }- // processif (is_any(process)) out->any_proc = true;else {int n = split_list(process, tok, PB_MAX_PATTERNS);@@ -313,7 +283,6 @@ bool pb_rule_parse(struct pb_rule *out, const char *process, const char *hosts,if (out->any_proc) { free(out->procs); out->procs = NULL; out->nprocs = 0; }}- // hostsif (is_any(hosts)) out->any_host = true;else {int n = split_list(hosts, tok, PB_MAX_PATTERNS);@@ -334,7 +303,6 @@ bool pb_rule_parse(struct pb_rule *out, const char *process, const char *hosts,if (out->any_host) { free(out->hosts); free(out->domains); out->hosts = NULL; out->domains = NULL; out->nhosts = out->ndomains = 0; }}- // portsif (is_any(ports)) out->any_port = true;else {int n = split_list(ports, tok, PB_MAX_PATTERNS);@@ -358,8 +326,6 @@ fail:return false;}-// ---- matching ---------------------------------------------------------------------------------------------------------bool pb_rule_match_process(const struct pb_rule *r, const char *exe_path){if (r->any_proc) return true;diff --git a/Linux/src/pb_rules.h b/Linux/src/pb_rules.hindex 4c18df4..02cec44 100644--- a/Linux/src/pb_rules.h+++ b/Linux/src/pb_rules.h@@ -39,7 +39,6 @@ struct pb_rule {// On failure returns false and writes a human readable reason to err. On success the caller must pb_rule_free().bool pb_rule_parse(struct pb_rule *out, const char *process, const char *hosts, const char *ports, char *err, size_t errlen);void pb_rule_free(struct pb_rule *r);-bool pb_rule_clone(struct pb_rule *dst, const struct pb_rule *src); // deep copybool pb_glob_match(const char *pattern, const char *str);bool pb_rule_match_process(const struct pb_rule *r, const char *exe_path);diff --git a/Linux/src/tests/rules_test.c b/Linux/src/tests/rules_test.cindex bc1b1c9..5934631 100644--- a/Linux/src/tests/rules_test.c+++ b/Linux/src/tests/rules_test.c@@ -92,9 +92,6 @@ int main(void)r = R("", "github.com;*.github.com", ""); CHECK(r.ndomains == 2); pb_rule_free(&r);CHECK(pb_domain_match("a?c.com", "abc.com")); CHECK(!pb_domain_match("a?c.com", "abbc.com")); CHECK(pb_domain_match("*", "x.y"));CHECK(bad("", "bad name.com", ""));- {- struct pb_rule c; r = R("curl", "*.example.com", "80"); CHECK(pb_rule_clone(&c, &r) && c.ndomains == 1 && !strcmp(c.domains[0], "*.example.com")); pb_rule_free(&c); pb_rule_free(&r);- }printf(fails ? "RULES TESTS FAILED (%d)\n" : "rules tests passed\n", fails);return fails != 0;}