Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic
C ccybersecurityhttp3httpproxylinuxlinux-proxymacosmacos-appmacos-proxyproxifierproxifier-alternativeproxyclienttcpthick-clientudpwindivertwindows
fix(linux): security review of the service and installer
anof-cyber57cf8476eb22
diff --git a/Linux/README.md b/Linux/README.mdindex 6cf8b0b..b3489a3 100644--- a/Linux/README.md+++ b/Linux/README.md@@ -33,12 +33,10 @@ curl -Lo deploy.sh https://raw.githubusercontent.com/InterceptSuite/ProxyBridge/```This script will:-- Download the latest release from GitHub automatically-- Detect your Linux distribution-- Install GTK3 if the GUI is included and GTK3 is missing (the command line program needs nothing)-- Install ProxyBridge CLI, GUI, and library to system paths-- Update library cache (ldconfig)-- Verify installation+- Download the latest release from GitHub into a private temporary directory and check its SHA-256 against the `.sha256` file of the release (it stops if they differ, or if the release has none, unless run as `sudo env PB_ALLOW_UNVERIFIED=1 bash deploy.sh`)+- Refuse an archive with absolute paths or `..`+- Run the archive's own `setup.sh`, which does the rest (so there is one installer): detect your distribution, install GTK3 if the GUI is included and it is missing, copy the programs and library, create the group and the service, update the library cache and verify+- `sudo env PB_NO_GROUP_USER=1 ./setup.sh` keeps the installer from adding the invoking user to the group `proxybridge`**Supported distributions:**- Debian/Ubuntu/Mint/Pop!_OS/Elementary/Zorin/Kali/Raspbian@@ -262,7 +260,7 @@ Add as many proxies as you need (GUI or profile); each rule chooses its own. Pro- **A local proxy is exempted** (its own connections go direct) when a process listens on the configured proxy address and port. While that port is free, for example because the proxy is not running yet, any local process that binds it is treated as the proxy. Point rules at proxies that are running, or at a proxy on another host, when other users share the machine.- **Fail-open on exit.** The kernel removes the eBPF programs when ProxyBridge stops or crashes. From that moment traffic flows normally: `BLOCK` rules no longer block and nothing is proxied. ProxyBridge is a routing tool, not a firewall; use the "start at boot" service (which restarts it on failure) and a real firewall for enforcement.- A rule that needs a proxy that does not exist **blocks** instead of letting traffic through. A connection whose proxy handshake fails is closed, never sent direct.-- **The service** (`proxybridge.service`) runs as root with `NoNewPrivileges`, `ProtectSystem=strict` (only `/etc/proxybridge` is writable), `ProtectHome`, `PrivateTmp`, `ProtectKernelModules`, `ProtectKernelLogs`, `ProtectClock`, `RestrictSUIDSGID`, `LockPersonality` and `RestrictRealtime`. Its socket accepts connections from every user, but a connection is served only for root and the members of the group `proxybridge` (peer credentials from the kernel, group read at each connection); anyone else gets a refusal and a log line, and cannot make the service allocate more than one frame (40 MiB limit checked before reading), more than 16 windows are refused, and a window that stops reading has its events dropped, never blocking the engine. Membership of the group is administrative power: such a user can route, block and read the proxy credentials of every user's traffic, so add only people you would give `sudo` for ProxyBridge. The window checks that the socket belongs to root before it sends anything. A window started as root without a service installs its unit only when the program and every directory above it belong to root and are writable by root only (an install under `/usr/local/bin`, not a copy run from a home directory).+- **The service** (`proxybridge.service`) runs as root, limited to the capabilities the engine needs (`CapabilityBoundingSet=CAP_BPF CAP_PERFMON CAP_NET_ADMIN CAP_SYS_ADMIN CAP_SYS_RESOURCE CAP_SYS_PTRACE CAP_DAC_READ_SEARCH`: no chown, kill, setuid, modules, raw I/O, mount or time), with `NoNewPrivileges`, `ProtectSystem=strict` (only `/etc/proxybridge` is writable), `ProtectHome`, `PrivateTmp`, `PrivateDevices`, `ProtectKernelModules/Logs/Tunables`, `ProtectControlGroups`, `ProtectClock`, `ProtectHostname`, `RestrictAddressFamilies` (unix, inet, inet6, netlink), `RestrictNamespaces`, `RestrictSUIDSGID`, `RestrictRealtime`, `LockPersonality`, `SystemCallArchitectures=native`, `MemoryDenyWriteExecute`, `UMask=0077`, `MemoryMax=1G` and `TasksMax=512`. `systemd-analyze security` rates it well below the default for a root service, and the tests run the real engine under exactly this sandbox. Its socket accepts connections from every user, but a connection is served only for root and the members of the group `proxybridge` (peer credentials from the kernel, group read at each connection); anyone else gets a refusal. Refusals are cheap (a user refused a moment ago is not looked up again; one journal line per user per minute; nothing is written to the log that windows show), so a local user cannot flood the journal or the accept queue. Limits for authorized windows: frames are checked against 8 MiB before anything is read and must arrive within 30 s of their header, at most 16 windows, a window that lets 64 MiB of answers pile up without reading them is disconnected, events a slow window cannot take are dropped (and it is told how many) instead of blocking the engine, a batch left open is applied after 10 s so one window cannot hold back everyone's changes, and one proxy test runs at a time. A session also ends within seconds when its user leaves the group. Profile names cannot contain control characters, the active profile must exist, and the profile store is limited to 512 profiles and 256 MiB. Membership of the group is administrative power: such a user can route, block and read the proxy credentials of every user's traffic, so add only people you would give `sudo` for ProxyBridge. The window checks that the socket belongs to root before it sends anything. A window started as root without a service installs its unit only when the program and every directory above it belong to root and are writable by root only (an install under `/usr/local/bin`, not a copy run from a home directory).- Anything shown in the log that another local user controls (an executable's name, a DNS name) has control characters replaced before it reaches the terminal or the GUI, and profiles that contain control characters in any field are rejected.- The relay listens on loopback only (UDP is additionally bound to the `lo` device). Other network namespaces (containers) are never redirected.- Proxy passwords are kept in the profile files under `/etc/proxybridge/profiles/` (mode 0600, directory 0700, root). Credentials are never taken from the command line, so they cannot show up in the process list or shell history.@@ -317,7 +315,7 @@ Add as many proxies as you need (GUI or profile); each rule chooses its own. Pro- Load the eBPF programs and attach them to the root cgroup- Listen on its local relay ports (24010 for TCP, 24011 for UDP; the next free pair is used if they are taken)- That is the job of `proxybridge.service`; the window does not need root (see [The service and the window](#the-service-and-the-window)). `ProxyBridge --profile` and a window without a service must be started with `sudo`.+ That is the job of `proxybridge.service`; the window does not need root (see [The service and the window](#the-service-and-the-window)). `ProxyBridge --profile` and a window without a service must be started with `sudo`. (A window run with `sudo` is a root program like any other: its file dialogs act as root. The unprivileged window does not have that property, which is a reason to prefer the service.)- **Process Name Matching**: Linux process names are case-sensitive. Use exact process names or wildcard patterns:- Exact: `firefox` matches only "firefox"diff --git a/Linux/cli/daemon.c b/Linux/cli/daemon.cindex fd53936..057d855 100644--- a/Linux/cli/daemon.c+++ b/Linux/cli/daemon.c@@ -29,6 +29,11 @@#define MAX_CLIENTS 16#define MAX_PROFILES 512#define EVENT_QUEUE_MAX 20000+#define QUEUE_BYTES_MAX (64u << 20) // what one window may have waiting to be read before it is cut off+#define BODY_TIMEOUT_MS 30000 // a frame whose header arrived must follow within this+#define BATCH_MAX_MS 10000 // a window may hold the kernel update back this long+#define RECHECK_S 5 // how often an open connection is checked against the group again+#define STORE_MAX_BYTES (256u << 20) // all profile files together#define HISTORY_LINES 200// ---- clients ---------------------------------------------------------------------------------------------------------------@@ -36,6 +41,7 @@ struct outmsg {struct outmsg *next;unsigned char *frame;size_t len;+ bool event;};struct client {@@ -44,14 +50,24 @@ struct client {pthread_mutex_t mu;pthread_cond_t cv;struct outmsg *head, *tail;- size_t nevents; // queued events (responses are never dropped)- unsigned long dropped;+ size_t nevents; // queued events (dropped when too many are waiting)+ size_t qbytes; // bytes queued; responses are never dropped, a window that lets them pile up is disconnected+ unsigned long dropped; // events dropped since the window last caught upbool closing;int batch_depth; // BeginBatch calls this client has not yet closed+ int64_t batch_t0; // when the first of them was made (ms, monotonic)+ time_t last_check; // last time uid_allowed() was asked for this connectionatomic_int refs;struct client *next;};+static int64_t now_ms(void)+{+ struct timespec ts;+ clock_gettime(CLOCK_MONOTONIC, &ts);+ return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;+}+static pthread_mutex_t clients_mu = PTHREAD_MUTEX_INITIALIZER;static struct client *clients;static int nclients;@@ -76,11 +92,21 @@ static void enqueue(struct client *c, unsigned char *frame, size_t len, bool is_free(frame);return;}+ if (c->qbytes + len > QUEUE_BYTES_MAX) {+ // A window that asks for things and does not read the answers would make the service hold them all: cut it off.+ if (!is_event) { c->closing = true; pthread_cond_signal(&c->cv); }+ else c->dropped++;+ pthread_mutex_unlock(&c->mu);+ if (!is_event) shutdown(c->fd, SHUT_RDWR);+ free(frame);+ return;+ }struct outmsg *m = malloc(sizeof *m);if (!m) { pthread_mutex_unlock(&c->mu); free(frame); return; }- m->next = NULL; m->frame = frame; m->len = len;+ m->next = NULL; m->frame = frame; m->len = len; m->event = is_event;if (c->tail) c->tail->next = m; else c->head = m;c->tail = m;+ c->qbytes += len;if (is_event) c->nevents++;pthread_cond_signal(&c->cv);pthread_mutex_unlock(&c->mu);@@ -119,6 +145,10 @@ static void *writer_main(void *arg)struct outmsg *m = c->head;c->head = m->next;if (!c->head) c->tail = NULL;+ c->qbytes -= m->len;+ if (m->event) c->nevents--; // the budget is for what is waiting, not for the life of the connection+ unsigned long lost = 0;+ if (!c->head && c->dropped) { lost = c->dropped; c->dropped = 0; }pthread_mutex_unlock(&c->mu);size_t off = 0;bool ok = true;@@ -131,6 +161,14 @@ static void *writer_main(void *arg)}free(m->frame);free(m);+ if (ok && lost) { // tell the window it missed something instead of letting it assume it saw everything+ char note[96];+ snprintf(note, sizeof note, "%lu connection or log events were dropped because this window was too slow", lost);+ const char *nf[] = { "e", "log", note };+ size_t nl;+ unsigned char *nfr = pb_ipc_encode(3, nf, NULL, &nl);+ if (nfr) { ok = send(c->fd, nfr, nl, MSG_NOSIGNAL) == (ssize_t)nl; free(nfr); }+ }if (!ok) {pthread_mutex_lock(&c->mu);c->closing = true;@@ -248,6 +286,16 @@ static bool ensure_store(void)return ensure_dir(pbp_config_dir()) && ensure_dir(sub);}+// Profile names: stored encoded, so any name is safe on disk, but a name with control characters would reach menus, window titles and+// logs of every user of the window. Rejected for new profiles.+static bool name_ok(const char *name)+{+ if (!name || !*name || strlen(name) > 200) return false;+ for (const unsigned char *p = (const unsigned char *)name; *p; p++)+ if (*p < 0x20 || *p == 0x7f) return false;+ return true;+}+static char *profile_file(const char *name){char *file = pbp_filename_for(name);@@ -306,9 +354,51 @@ static void store_get(struct client *c, const char *id, const char *name)free(buf);}+static unsigned long long store_bytes(void)+{+ char dir[4096];+ snprintf(dir, sizeof dir, "%s/profiles", pbp_config_dir());+ DIR *d = opendir(dir);+ unsigned long long total = 0;+ struct dirent *de;+ while (d && (de = readdir(d)) != NULL) {+ char path[4400];+ struct stat st;+ snprintf(path, sizeof path, "%s/%s", dir, de->d_name);+ if (lstat(path, &st) == 0 && S_ISREG(st.st_mode)) total += (unsigned long long)st.st_size;+ }+ if (d) closedir(d);+ return total;+}++// A crash in the middle of a write leaves "<file>.tmp.XXXXXX"; nothing else ever removes them+static void sweep_temp_files(void)+{+ char dir[4096];+ snprintf(dir, sizeof dir, "%s/profiles", pbp_config_dir());+ DIR *d = opendir(dir);+ struct dirent *de;+ while (d && (de = readdir(d)) != NULL) {+ if (!strstr(de->d_name, ".tmp.")) continue;+ char path[4400];+ snprintf(path, sizeof path, "%s/%s", dir, de->d_name);+ unlink(path);+ }+ if (d) closedir(d);+ d = opendir(pbp_config_dir()); // the same for a settings.json that was being replaced+ while (d && (de = readdir(d)) != NULL) {+ if (strncmp(de->d_name, "settings.json.tmp.", 17) != 0) continue;+ char path[4400];+ snprintf(path, sizeof path, "%s/%s", pbp_config_dir(), de->d_name);+ unlink(path);+ }+ if (d) closedir(d);+}+static void store_put(struct client *c, const char *id, const char *name, const char *data, size_t dlen){if (dlen > PBP_MAX_FILE) { reply_err(c, id, "profile too large"); return; }+ if (!name_ok(name)) { reply_err(c, id, "unusable profile name (empty, over 200 bytes, or with control characters)"); return; }char *path = profile_file(name);if (!path) { reply_err(c, id, "unusable profile name"); return; }struct pbp_profile p;@@ -326,6 +416,7 @@ static void store_put(struct client *c, const char *id, const char *name, constif (count >= MAX_PROFILES) { free(path); reply_err(c, id, "too many profiles"); return; }}if (!ensure_store()) { free(path); reply_err(c, id, "cannot create the configuration folder"); return; }+ if (store_bytes() + dlen > STORE_MAX_BYTES) { free(path); reply_err(c, id, "the profile store is full"); return; }if (pbp_write_file(path, data, err, sizeof err) != 0) { free(path); reply_err(c, id, err); return; }free(path);reply_ok(c, id);@@ -341,21 +432,27 @@ static void store_delete(struct client *c, const char *id, const char *name)}// ---- engine control --------------------------------------------------------------------------------------------------------+static pthread_mutex_t engine_mu = PTHREAD_MUTEX_INITIALIZER; // one start or stop at a time, whoever asks+static bool engine_start(void){+ pthread_mutex_lock(&engine_mu);bool ok = ProxyBridge_Start();pthread_mutex_lock(&state_mu);engine_running = ok;pthread_mutex_unlock(&state_mu);+ pthread_mutex_unlock(&engine_mu);return ok;}static void engine_stop(void){+ pthread_mutex_lock(&engine_mu);ProxyBridge_Stop();pthread_mutex_lock(&state_mu);engine_running = false;pthread_mutex_unlock(&state_mu);+ pthread_mutex_unlock(&engine_mu);}static void update_logging(void)@@ -363,10 +460,10 @@ static void update_logging(void)pthread_mutex_lock(&clients_mu);int n = nclients;pthread_mutex_unlock(&clients_mu);- pthread_mutex_lock(&state_mu);+ pthread_mutex_lock(&state_mu); // decided and applied under one lock, so two threads cannot apply stale valuesbool on = logging_requested && n > 0;- pthread_mutex_unlock(&state_mu);ProxyBridge_SetTrafficLoggingEnabled(on || verbose == 2 || verbose == 3);+ pthread_mutex_unlock(&state_mu);}// Loads the profile that was active when the service last ran, so the machine is routed from the moment it boots, before any@@ -434,6 +531,7 @@ static void apply_active_profile(void)// ---- requests --------------------------------------------------------------------------------------------------------------struct test_ctx { struct client *c; const char *id; };+static pthread_mutex_t test_mu = PTHREAD_MUTEX_INITIALIZER;static void test_line(const char *line, void *user){@@ -471,6 +569,11 @@ static void handle(struct client *c, pb_msg *m){if (m->n < 3 || strcmp(m->f[0], "q") != 0) return;const char *id = m->f[1], *cmd = m->f[2];+ if (m->len[1] > 24) { // an id is a short counter; anything else is not a window of ours+ pthread_mutex_lock(&c->mu); c->closing = true; pthread_cond_signal(&c->cv); pthread_mutex_unlock(&c->mu);+ shutdown(c->fd, SHUT_RDWR);+ return;+ }char err[256] = "";uint64_t a, b;bool on;@@ -540,8 +643,16 @@ static void handle(struct client *c, pb_msg *m)} else if (!strcmp(cmd, "proxy.test")) {NEED(3);if (!pu(ARG(0), 0xffffffffu, &a) || !pu(ARG(2), 65535, &b)) { reply_err(c, id, "bad arguments"); return; }+ size_t hl = strlen(ARG(1));+ bool host_ok = hl > 0 && hl <= 253;+ for (const unsigned char *p = (const unsigned char *)ARG(1); host_ok && *p; p++) if (*p <= 0x20 || *p >= 0x7f) host_ok = false;+ if (!host_ok) { reply_err(c, id, "the target host must be 1 to 253 printable characters without spaces"); return; }+ // The test makes this root service open connections. One at a time keeps a window from tying up the name-resolver threads+ // that the relay needs for the proxies' own host names.+ if (pthread_mutex_trylock(&test_mu) != 0) { reply_err(c, id, "another proxy test is already running"); return; }struct test_ctx t = { c, id };int rc = ProxyBridge_TestProxyEx((uint32_t)a, ARG(1), (uint16_t)b, test_line, &t);+ pthread_mutex_unlock(&test_mu);char r[16];snprintf(r, sizeof r, "%d", rc);reply_ok1(c, id, r);@@ -592,7 +703,7 @@ static void handle(struct client *c, pb_msg *m)else if (!strcmp(cmd, "batch.begin")) {NEED(0);ProxyBridge_BeginBatch();- c->batch_depth++;+ if (c->batch_depth++ == 0) c->batch_t0 = now_ms();reply_ok(c, id);} else if (!strcmp(cmd, "batch.end")) {NEED(0);@@ -670,6 +781,12 @@ static void handle(struct client *c, pb_msg *m)NEED(3);bool updates, boot;if (!bool_arg(ARG(1), &updates) || !bool_arg(ARG(2), &boot)) { reply_err(c, id, "bad value"); return; }+ if (ARG(0)[0]) { // the active profile must be one that exists+ char *pf = name_ok(ARG(0)) ? profile_file(ARG(0)) : NULL;+ bool there = pf && access(pf, F_OK) == 0;+ free(pf);+ if (!there) { reply_err(c, id, "no such profile"); return; }+ }if (write_settings(ARG(0), updates, boot, err, sizeof err) != 0) reply_err(c, id, err); else reply_ok(c, id);}// ---- start at boot: the service applies the active profile when it starts and keeps routing after the window closes@@ -694,13 +811,45 @@ static void handle(struct client *c, pb_msg *m)}}+static bool uid_allowed(uid_t uid);+static void *reader_main(void *arg){struct client *c = arg;+ c->last_check = time(NULL);for (;;) {+ // A window that opened a batch and went quiet would hold every other window's changes back from the kernel+ if (c->batch_depth > 0) {+ int64_t left = c->batch_t0 + BATCH_MAX_MS - now_ms();+ struct pollfd pf = { .fd = c->fd, .events = POLLIN };+ if (left <= 0 || poll(&pf, 1, (int)left) == 0) {+ while (c->batch_depth > 0) { c->batch_depth--; ProxyBridge_EndBatch(); }+ dlog("a window left a batch open for more than %d seconds: it was applied", BATCH_MAX_MS / 1000);+ continue;+ }+ }pb_msg m;- int rc = pb_ipc_recv(c->fd, &m);+ int rc = pb_ipc_recv_timeout(c->fd, &m, BODY_TIMEOUT_MS);if (rc != 0) break;+ // Leaving the group ends the session, not only the next connection+ time_t now = time(NULL);+ if (now - c->last_check >= RECHECK_S) {+ c->last_check = now;+ if (!uid_allowed(c->uid)) {+ const char *f[] = { "r", m.n > 1 ? m.f[1] : "0", "err", "not allowed any more: the user left the group 'proxybridge'" };+ send_to(c, false, 4, f);+ pb_msg_free(&m);+ for (int i = 0; i < 100; i++) { // let the writer thread deliver the explanation before the connection goes+ pthread_mutex_lock(&c->mu);+ bool empty = c->head == NULL;+ pthread_mutex_unlock(&c->mu);+ if (empty) break;+ usleep(10000);+ }+ usleep(20000);+ break;+ }+ }handle(c, &m);pb_msg_free(&m);}@@ -730,6 +879,36 @@ static void *reader_main(void *arg)// ---- access control --------------------------------------------------------------------------------------------------------// root, or a member of the group "proxybridge". Looked up in the group database at every connection, so adding a user to the// group takes effect at once, without a new login. No such group: root only.+// ---- refusals --------------------------------------------------------------------------------------------------------------+#define REFUSAL_SLOTS 32+static struct { uid_t uid; int64_t until, last_log; unsigned long suppressed; } refusals[REFUSAL_SLOTS];++static bool refused_recently(uid_t uid)+{+ int64_t now = now_ms();+ for (int i = 0; i < REFUSAL_SLOTS; i++)+ if (refusals[i].until > now && refusals[i].uid == uid) return true;+ return false;+}++static void note_refusal(uid_t uid)+{+ int64_t now = now_ms();+ int slot = -1, oldest = 0;+ for (int i = 0; i < REFUSAL_SLOTS; i++) {+ if (refusals[i].uid == uid && refusals[i].last_log) { slot = i; break; }+ if (refusals[i].last_log < refusals[oldest].last_log) oldest = i;+ }+ if (slot < 0) { slot = oldest; memset(&refusals[slot], 0, sizeof refusals[slot]); refusals[slot].uid = uid; }+ refusals[slot].until = now + 1000;+ if (refusals[slot].last_log && now - refusals[slot].last_log < 60000) { refusals[slot].suppressed++; return; }+ printf("[PB] refused a connection from user %u: not root and not a member of the group '%s'%s\n", (unsigned)uid, GROUP_NAME,+ refusals[slot].suppressed ? " (more of them were refused in the last minute)" : "");+ fflush(stdout);+ refusals[slot].last_log = now;+ refusals[slot].suppressed = 0;+}+static bool uid_allowed(uid_t uid){if (uid == 0) return true;@@ -794,6 +973,7 @@ int pb_daemon_run(const char *socket_path, int verbose_level)if (!ensure_store()) { fprintf(stderr, "ERROR: cannot create %s\n", pbp_config_dir()); return 1; }int lfd = open_listener(socket_path);if (lfd < 0) { fprintf(stderr, "ERROR: cannot listen on %s: %s\n", socket_path, strerror(errno)); return 1; }+ sweep_temp_files();dlog("ProxyBridge service %s listening on %s", PROXYBRIDGE_VERSION, socket_path);// Start at Boot: route from the moment the machine is up, with the profile that was active last. Without it the service is idle@@ -821,11 +1001,14 @@ int pb_daemon_run(const char *socket_path, int verbose_level)}if (!(p[0].revents & POLLIN)) continue;int fd;+ errno = 0;while ((fd = accept4(lfd, NULL, NULL, SOCK_CLOEXEC)) >= 0) { // everything that is waiting, not one per wake-up- struct ucred cred;+ struct ucred cred = { .pid = 0, .uid = (uid_t)-1, .gid = (gid_t)-1 };socklen_t cl = sizeof cred;- if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &cl) != 0 || !uid_allowed(cred.uid)) {- dlog("refused a connection from user %u: not root and not a member of the group '%s'", (unsigned)cred.uid, GROUP_NAME);+ if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &cl) != 0 || refused_recently(cred.uid) || !uid_allowed(cred.uid)) {+ // This path is open to every local user, so it must stay cheap: no group lookup for a user refused a moment ago, one+ // journal line per user per minute, and nothing written to the log that windows are shown.+ note_refusal(cred.uid);pb_ipc_sendv(fd, "r", "0", "err", "not allowed: only root and members of the group 'proxybridge' may control ProxyBridge", (char *)NULL);close(fd);continue;@@ -875,6 +1058,7 @@ int pb_daemon_run(const char *socket_path, int verbose_level)}pthread_attr_destroy(&at);}+ if (errno == EMFILE || errno == ENFILE || errno == ENOMEM || errno == ENOBUFS) usleep(100000); // out of descriptors: do not spin on a listener that stays readable}dlog("stopping");diff --git a/Linux/deploy.sh b/Linux/deploy.shindex c292057..902a6d3 100644--- a/Linux/deploy.sh+++ b/Linux/deploy.sh@@ -1,10 +1,13 @@#!/bin/bash--set -e+# Downloads the latest ProxyBridge release for Linux, checks it, and installs it with the setup.sh that is inside the archive:+# curl -Lo deploy.sh https://raw.githubusercontent.com/InterceptSuite/ProxyBridge/refs/heads/master/Linux/deploy.sh && sudo bash deploy.sh+# Everything that is installed (programs, the ProxyBridge service, the group) is done by setup.sh, so there is one installer.+# PB_ALLOW_UNVERIFIED=1 install a release that has no .sha256 file next to the archive (nothing else is skipped)+set -euo pipefailGITHUB_REPO="InterceptSuite/ProxyBridge"GITHUB_API="https://api.github.com/repos/$GITHUB_REPO/releases/latest"-TEMP_DIR="/tmp/proxybridge-install-$$"+DOWNLOAD_PREFIX="https://github.com/$GITHUB_REPO/releases/download/"echo ""echo "==================================="@@ -12,325 +15,83 @@ echo "ProxyBridge Auto-Deploy Script"echo "==================================="echo ""-# Check if running as rootif [ "$EUID" -ne 0 ]; thenecho "ERROR: This script must be run as root"echo "Please run: sudo bash deploy.sh"exit 1fi-# Check for required tools-check_requirements() {- echo "Checking required tools..."-- local missing_tools=()-- if ! command -v curl &> /dev/null; then- missing_tools+=("curl")- fi-- if ! command -v tar &> /dev/null; then- missing_tools+=("tar")- fi-- if ! command -v jq &> /dev/null; then- echo "WARNING: jq not found. Attempting to parse JSON manually."- fi-- if [ ${#missing_tools[@]} -gt 0 ]; then- echo "ERROR: Missing required tools: ${missing_tools[*]}"- echo ""- echo "Please install them first:"- echo " Debian/Ubuntu: sudo apt install curl tar jq"- echo " Fedora: sudo dnf install curl tar jq"- echo " Arch: sudo pacman -S curl tar jq"- exit 1- fi-- echo "All required tools available"-}--# Download latest release-download_latest_release() {- echo ""- echo "Fetching latest release information..."-- # Create temp directory- mkdir -p "$TEMP_DIR"- cd "$TEMP_DIR"-- # Get release info from GitHub API- local api_response- api_response=$(curl -sL "$GITHUB_API")-- if [ -z "$api_response" ]; then- echo "ERROR: Failed to fetch release information from GitHub"- exit 1- fi-- # Extract download URL for Linux tar.gz- local download_url- if command -v jq &> /dev/null; then- download_url=$(echo "$api_response" | jq -r '.assets[] | select(.name | test("ProxyBridge-Linux-.*\\.tar\\.gz$")) | .browser_download_url' | head -1)- else- # Fallback: manual parsing- download_url=$(echo "$api_response" | grep -o '"browser_download_url": *"[^"]*ProxyBridge-Linux-[^"]*\.tar\.gz"' | head -1 | sed 's/.*"browser_download_url": *"\([^"]*\)".*/\1/')- fi-- if [ -z "$download_url" ]; then- echo "ERROR: Could not find Linux release archive in latest release"- echo ""- echo "Please check if a Linux release is available at:"- echo " https://github.com/$GITHUB_REPO/releases/latest"- exit 1- fi-- # Extract version from URL- local filename- filename=$(basename "$download_url")- echo "Found release: $filename"- echo "Download URL: $download_url"-- echo ""- echo "Downloading $filename..."- if ! curl -L -o "$filename" "$download_url"; then- echo "ERROR: Failed to download release archive"- exit 1- fi-- echo "Download complete"-- # Extract archive- echo ""- echo "Extracting archive..."- if ! tar -xzf "$filename"; then- echo "ERROR: Failed to extract archive"- exit 1- fi-- echo "Extraction complete"- echo "Files extracted to: $TEMP_DIR"- ls -lh-}--# Detect Linux distribution-detect_distro() {- if [ -f /etc/os-release ]; then- . /etc/os-release- DISTRO=$ID- DISTRO_LIKE=$ID_LIKE- elif [ -f /etc/lsb-release ]; then- . /etc/lsb-release- DISTRO=$DISTRIB_ID- else- DISTRO=$(uname -s)- fi- echo ""- echo "Detected distribution: $DISTRO"-}--# The command line program and the library are self-contained (libbpf, libelf and zlib are linked in; only glibc is used), so-# nothing needs installing for them. The GUI needs GTK3, which cannot be linked statically: install it only if it is missing.-install_dependencies() {- echo ""- if [ ! -f "$TEMP_DIR/ProxyBridgeGUI" ]; then- echo "No dependencies to install (the command line program is self-contained)."- return- fi- if ldconfig -p 2>/dev/null | grep -q 'libgtk-3\.so\.0'; then- echo "GTK3 is already installed (needed by the GUI)."- return- fi- echo "Installing GTK3 (needed by the GUI)..."-- # Normalize distro name using ID_LIKE fallback- local distro_family="$DISTRO"- if [ -n "$DISTRO_LIKE" ]; then- case "$DISTRO_LIKE" in- *ubuntu*|*debian*) distro_family="debian" ;;- *fedora*) distro_family="fedora" ;;- *rhel*|*centos*) distro_family="rhel" ;;- *arch*) distro_family="arch" ;;- *suse*) distro_family="opensuse" ;;- esac- fi-- case "$distro_family" in- ubuntu|debian|linuxmint|pop|elementary|zorin|kali|raspbian|mx|antix|deepin|lmde)- apt-get update -qq- apt-get install -y libgtk-3-0- ;;- fedora) dnf install -y gtk3 ;;- rhel|centos|rocky|almalinux) yum install -y gtk3 ;;- arch|manjaro|endeavouros|garuda) pacman -Sy --noconfirm gtk3 ;;- opensuse*|sles) zypper install -y gtk3 ;;- void) xbps-install -Sy gtk3 ;;- *)- echo "WARNING: Unknown distribution '$DISTRO'. The GUI needs GTK3 (Debian/Ubuntu: libgtk-3-0, Fedora: gtk3, Arch: gtk3)."- echo "The command line program works without it."- ;;- esac-}--# Use /usr/local/lib (matches RPATH in binary)-detect_lib_path() {- LIB_PATH="/usr/local/lib"- echo "Library installation path: $LIB_PATH"-}--# Check if files exist in extracted directory-check_files() {- echo ""- echo "Checking for required files..."+missing=()+for tool in curl tar sha256sum mktemp; do+ command -v "$tool" >/dev/null 2>&1 || missing+=("$tool")+done+if [ "${#missing[@]}" -gt 0 ]; then+ echo "ERROR: missing required tools: ${missing[*]}"+ echo " Debian/Ubuntu: sudo apt install curl tar coreutils"+ echo " Fedora: sudo dnf install curl tar coreutils"+ echo " Arch: sudo pacman -S curl tar coreutils"+ exit 1+fi- if [ ! -f "$TEMP_DIR/libproxybridge.so" ]; then- echo "ERROR: libproxybridge.so not found in extracted archive"- exit 1- fi+# A directory only root can use, with a name nobody can predict: nothing in it can be swapped by another user between the download and+# the moment it is installed (a fixed name under /tmp could be created in advance by any local user).+WORK="$(mktemp -d /var/tmp/proxybridge-install.XXXXXX)"+chmod 700 "$WORK"+trap 'rm -rf "$WORK"' EXIT+umask 077+fetch() { curl -fsSL --proto '=https' --proto-redir '=https' --tlsv1.2 "$@"; }++echo "Fetching latest release information..."+api_response="$(fetch "$GITHUB_API")" || { echo "ERROR: Failed to fetch release information from GitHub"; exit 1; }++if command -v jq >/dev/null 2>&1; then+ download_url="$(printf '%s' "$api_response" | jq -r '.assets[] | select(.name | test("^ProxyBridge-Linux-.*\\.tar\\.gz$")) | .browser_download_url' | head -1)"+else+ download_url="$(printf '%s' "$api_response" | grep -o '"browser_download_url": *"[^"]*ProxyBridge-Linux-[^"/]*\.tar\.gz"' | head -1 | sed 's/.*"browser_download_url": *"\([^"]*\)".*/\1/')"+fi+if [ -z "$download_url" ] || [ "${download_url#"$DOWNLOAD_PREFIX"}" = "$download_url" ]; then+ echo "ERROR: Could not find the Linux release archive in the latest release"+ echo "Please check if a Linux release is available at: https://github.com/$GITHUB_REPO/releases/latest"+ exit 1+fi+filename="$(basename "$download_url")"+case "$filename" in+ *[!A-Za-z0-9._-]*|"") echo "ERROR: unexpected file name in the release"; exit 1 ;;+esac+echo "Found release: $filename"- if [ ! -f "$TEMP_DIR/ProxyBridge" ]; then- echo "ERROR: ProxyBridge binary not found in extracted archive"+echo ""+echo "Downloading $filename..."+fetch -o "$WORK/$filename" "$download_url" || { echo "ERROR: Failed to download the release archive"; exit 1; }++echo "Checking the download..."+if fetch -o "$WORK/$filename.sha256" "$download_url.sha256" 2>/dev/null; then+ expected="$(awk '{print $1; exit}' "$WORK/$filename.sha256")"+ actual="$(sha256sum "$WORK/$filename" | awk '{print $1}')"+ if [ -z "$expected" ] || [ "$expected" != "$actual" ]; then+ echo "ERROR: the checksum of the download does not match ($filename.sha256). Nothing was installed."exit 1fi+ echo " SHA-256 matches"+elif [ "${PB_ALLOW_UNVERIFIED:-0}" = 1 ]; then+ echo "WARNING: this release has no .sha256 file; installing without checking it (PB_ALLOW_UNVERIFIED=1)"+else+ echo "ERROR: this release has no .sha256 file to check the download against."+ echo " Verify the archive yourself and run again with PB_ALLOW_UNVERIFIED=1, or install from the downloaded archive by hand."+ exit 1+fi- if [ ! -f "$TEMP_DIR/ProxyBridgeGUI" ]; then- echo "WARNING: ProxyBridgeGUI binary not found - GUI will not be installed"- fi-- echo "All required files present"-}--# Install files-install_files() {- echo ""- echo "Installing ProxyBridge..."-- # Create directories if they don't exist- mkdir -p "$LIB_PATH" /usr/local/bin /etc/proxybridge- chmod 755 /etc/proxybridge-- # Copy library- echo "Installing libproxybridge.so to $LIB_PATH..."- cp "$TEMP_DIR/libproxybridge.so" "$LIB_PATH/"- chmod 755 "$LIB_PATH/libproxybridge.so"-- # Copy binary- echo "Installing ProxyBridge to /usr/local/bin..."- cp "$TEMP_DIR/ProxyBridge" /usr/local/bin/- chmod 755 /usr/local/bin/ProxyBridge-- if [ -f "$TEMP_DIR/ProxyBridgeGUI" ]; then- echo "Installing ProxyBridgeGUI to /usr/local/bin..."- cp "$TEMP_DIR/ProxyBridgeGUI" /usr/local/bin/- chmod 755 /usr/local/bin/ProxyBridgeGUI- fi- if [ -f "$TEMP_DIR/ProxyBridgeGUI" ] && [ -f "$TEMP_DIR/proxybridge.desktop" ]; then- echo "Installing the launcher entry and icon..."- install -d -m 0755 /usr/share/applications /usr/share/icons/hicolor/128x128/apps /usr/share/icons/hicolor/256x256/apps- install -o root -g root -m 0644 "$TEMP_DIR/proxybridge.desktop" /usr/share/applications/proxybridge.desktop- install -o root -g root -m 0644 "$TEMP_DIR/proxybridge-128.png" /usr/share/icons/hicolor/128x128/apps/proxybridge.png- install -o root -g root -m 0644 "$TEMP_DIR/proxybridge-256.png" /usr/share/icons/hicolor/256x256/apps/proxybridge.png- command -v gtk-update-icon-cache >/dev/null 2>&1 && gtk-update-icon-cache -q -t -f /usr/share/icons/hicolor 2>/dev/null || true- command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database -q /usr/share/applications 2>/dev/null || true- fi--- echo "Files installed"-}--# Update library cache-update_ldconfig() {- echo ""- echo "Updating library cache..."-- # Add /usr/local/lib to ld.so.conf if not already there- if [ -d /etc/ld.so.conf.d ]; then- if ! grep -q "^/usr/local/lib" /etc/ld.so.conf.d/* 2>/dev/null; then- echo "/usr/local/lib" > /etc/ld.so.conf.d/proxybridge.conf- if [ "$LIB_PATH" = "/usr/local/lib64" ]; then- echo "/usr/local/lib64" >> /etc/ld.so.conf.d/proxybridge.conf- fi- fi- fi-- # Run ldconfig- if command -v ldconfig &> /dev/null; then- ldconfig 2>/dev/null || true- ldconfig -v 2>/dev/null | grep -q proxybridge || true- echo "Library cache updated"- else- echo "WARNING: ldconfig not found. You may need to reboot."- fi-}--# Verify installation-verify_installation() {- echo ""- echo "Verifying installation..."-- # Check if binary is in PATH- if command -v ProxyBridge &> /dev/null; then- echo "ProxyBridge binary found in PATH"- else- echo "ProxyBridge binary not found in PATH"- echo " You may need to add /usr/local/bin to your PATH"- fi-- # Check if library is loadable- if ldd /usr/local/bin/ProxyBridge 2>/dev/null | grep -q "libproxybridge.so"; then- if ldd /usr/local/bin/ProxyBridge 2>/dev/null | grep "libproxybridge.so" | grep -q "not found"; then- echo "libproxybridge.so not loadable"- else- echo "libproxybridge.so is loadable"- fi- fi-- # Final test - try to run --help- if /usr/local/bin/ProxyBridge --help &>/dev/null; then- echo "ProxyBridge executable is working"- else- echo "⚠ ProxyBridge may have issues - try: sudo ldconfig"- fi-}--# Cleanup temp directory-cleanup() {- echo ""- echo "Cleaning up temporary files..."- rm -rf "$TEMP_DIR"- echo "Cleanup complete"-}--# Main deployment-main() {- check_requirements- download_latest_release- detect_distro- check_files- install_dependencies- detect_lib_path- install_files- update_ldconfig- verify_installation- cleanup-- echo ""- echo "==================================="- echo "Installation Complete!"- echo "==================================="- echo ""- echo "You can now run ProxyBridge from anywhere:"- echo " sudo ProxyBridge --help"- if [ -f /usr/local/bin/ProxyBridgeGUI ]; then- echo " sudo ProxyBridgeGUI (Graphical Interface)"- fi- echo " sudo ProxyBridge --proxy socks5://IP:PORT --rule \"app:*:*:TCP:PROXY\""- echo ""- echo "No cleanup is needed after a crash: the kernel detaches the eBPF programs automatically."- echo ""-}--# Trap errors and cleanup-trap 'echo ""; echo "ERROR: Installation failed. Cleaning up..."; rm -rf "$TEMP_DIR"; exit 1' ERR+echo ""+echo "Extracting..."+if tar -tzf "$WORK/$filename" | grep -qE '(^/|(^|/)\.\.(/|$))'; then+ echo "ERROR: the archive contains absolute paths or '..'; refusing to extract it"+ exit 1+fi+mkdir "$WORK/pkg"+tar -xzf "$WORK/$filename" -C "$WORK/pkg" --no-same-owner --no-same-permissions+[ -f "$WORK/pkg/setup.sh" ] || { echo "ERROR: setup.sh is not in the archive"; exit 1; }-main+echo ""+umask 022+cd "$WORK/pkg"+bash ./setup.shdiff --git a/Linux/gui/gui_config.c b/Linux/gui/gui_config.cindex 467d95f..ba58949 100644--- a/Linux/gui/gui_config.c+++ b/Linux/gui/gui_config.c@@ -399,7 +399,8 @@ static void give_to_invoker(const char *path) {if (!theirs) return;guint64 gid = st.st_gid;if (gid_s && *gid_s) { gid = g_ascii_strtoull(gid_s, &end, 10); if (!end || *end || gid > 0xFFFFFFFEull) gid = st.st_gid; }- if (chown(path, (uid_t)uid, (gid_t)gid) != 0) g_warning("could not hand %s to the invoking user: %s", path, g_strerror(errno));+ // lchown: if the invoker swapped the file for a symlink in their own directory, it is the link that changes hands, not its target+ if (lchown(path, (uid_t)uid, (gid_t)gid) != 0) g_warning("could not hand %s to the invoking user: %s", path, g_strerror(errno));}bool profile_export(const Profile *prof, const char *path, char *err, size_t errlen) {diff --git a/Linux/gui/pb_client.c b/Linux/gui/pb_client.cindex 0f0747d..c599d4d 100644--- a/Linux/gui/pb_client.c+++ b/Linux/gui/pb_client.c@@ -5,6 +5,8 @@#include "pb_ipc.h"#include <errno.h>+#include <fcntl.h>+#include <poll.h>#include <pthread.h>#include <sys/socket.h>#include <sys/un.h>@@ -128,7 +130,24 @@ static int open_connection(const char *path, int *fd_out, bool *running, char *estrcpy(a.sun_path, path);int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);if (fd < 0) { snprintf(err, errn, "%s", strerror(errno)); return PBC_REFUSED; }- if (connect(fd, (struct sockaddr *)&a, sizeof a) != 0) {+ // Not a plain blocking connect: this runs on the window's main loop when it reconnects, and a service whose queue is full must not+ // freeze the window.+ int fl = fcntl(fd, F_GETFL, 0);+ fcntl(fd, F_SETFL, fl | O_NONBLOCK);+ int cr = connect(fd, (struct sockaddr *)&a, sizeof a);+ if (cr != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {+ struct pollfd pf = { .fd = fd, .events = POLLOUT };+ if (poll(&pf, 1, 3000) == 1) {+ int soerr = 0;+ socklen_t sl = sizeof soerr;+ getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &sl);+ if (soerr == 0) cr = 0; else errno = soerr;+ } else {+ errno = ETIMEDOUT;+ }+ }+ if (cr == 0) fcntl(fd, F_SETFL, fl);+ if (cr != 0) {int e = errno;close(fd);if (e == ENOENT || e == ECONNREFUSED) { snprintf(err, errn, "the ProxyBridge service is not running"); return PBC_NO_SERVICE; }@@ -239,6 +258,7 @@ static bool rpc(reply_t *r, const char *cmd, unsigned nargs, const char *const *memset(p, 0, sizeof *p);p->used = true;p->lines = g_queue_new();+ int fd = C.fd; // the descriptor this request belongs to; a reconnect gets a new onesnprintf(p->id, sizeof p->id, "%lu", ++C.next_id);char idcopy[24];snprintf(idcopy, sizeof idcopy, "%s", p->id);@@ -249,7 +269,7 @@ static bool rpc(reply_t *r, const char *cmd, unsigned nargs, const char *const *f[n++] = "q"; f[n++] = idcopy; f[n++] = cmd;for (unsigned i = 0; i < nargs && n < 3 + 16; i++) f[n++] = args[i];pthread_mutex_lock(&C.send_mu);- int sent = pb_ipc_send(C.fd, n, f, NULL);+ int sent = pb_ipc_send(fd, n, f, NULL);pthread_mutex_unlock(&C.send_mu);pthread_mutex_lock(&C.mu);diff --git a/Linux/gui/tests/boot_test.c b/Linux/gui/tests/boot_test.cindex 5c6b7e7..f4b1b3b 100644--- a/Linux/gui/tests/boot_test.c+++ b/Linux/gui/tests/boot_test.c@@ -38,7 +38,8 @@ int main(void)g_free(err); err = NULL;t = boot_unit_text("/usr/local/bin/ProxyBridge", &err);CHECK(t && strstr(t, "LimitNOFILE=1048576") && strstr(t, "NoNewPrivileges=yes") && strstr(t, "ProtectSystem=strict") && strstr(t, "ProtectHome=yes") &&- strstr(t, "RuntimeDirectory=proxybridge") && strstr(t, "ReadWritePaths=/etc/proxybridge\n"));+ strstr(t, "RuntimeDirectory=proxybridge") && strstr(t, "ReadWritePaths=/etc/proxybridge\n") &&+ strstr(t, "CapabilityBoundingSet=CAP_BPF ") && strstr(t, "RestrictAddressFamilies=") && strstr(t, "MemoryDenyWriteExecute=yes") && strstr(t, "UMask=0077"));g_free(t);// only root-owned, root-writable-only paths may be started at bootdiff --git a/Linux/setup.sh b/Linux/setup.shindex bc7f00a..43ce706 100644--- a/Linux/setup.sh+++ b/Linux/setup.sh@@ -147,11 +147,16 @@ install_service() {groupadd --system proxybridge 2>/dev/null || groupadd -r proxybridge 2>/dev/null || addgroup --system proxybridge 2>/dev/null \|| echo "WARNING: could not create the group 'proxybridge'; only root will be able to use the window"fi+ # Membership of the group is administrative power over ProxyBridge: a member can route, block and read the proxy passwords of every+ # user's traffic. The user who ran sudo is added (that is who just installed it); PB_NO_GROUP_USER=1 skips that.SERVICE_USER=""- if [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != root ] && id "$SUDO_USER" >/dev/null 2>&1 && getent group proxybridge >/dev/null 2>&1; then- if usermod -aG proxybridge "$SUDO_USER" 2>/dev/null || gpasswd -a "$SUDO_USER" proxybridge >/dev/null 2>&1 || adduser "$SUDO_USER" proxybridge >/dev/null 2>&1; then+ if [ -n "${SUDO_USER:-}" ] && [ "${PB_NO_GROUP_USER:-0}" != 1 ] && [ "$SUDO_USER" != root ] && [ "$(id -u -- "$SUDO_USER" 2>/dev/null || echo 0)" != 0 ] \+ && getent group proxybridge >/dev/null 2>&1; then+ if usermod -aG proxybridge -- "$SUDO_USER" 2>/dev/null || gpasswd -a "$SUDO_USER" proxybridge >/dev/null 2>&1 || adduser "$SUDO_USER" proxybridge >/dev/null 2>&1; thenSERVICE_USER="$SUDO_USER"echo " $SUDO_USER may now use ProxyBridge without root (member of the group 'proxybridge')"+ echo " NOTE: members of that group can route, block and read the proxy passwords of every user's traffic."+ echo " Add only people you would give sudo for ProxyBridge (sudo usermod -aG proxybridge <user>); remove with: sudo gpasswd -d <user> proxybridge"elseecho "WARNING: could not add $SUDO_USER to the group 'proxybridge'. Do it with: sudo usermod -aG proxybridge $SUDO_USER"fi@@ -257,6 +262,7 @@ uninstall() {echo " profiles and settings removed"elseecho " profiles kept in /etc/proxybridge (use --uninstall --purge to remove them)"+ echo " the group 'proxybridge' and its members were kept too (--purge removes the group)"fiecho "Done."}diff --git a/Linux/src/pb_ipc.c b/Linux/src/pb_ipc.cindex 391311d..7b44e34 100644--- a/Linux/src/pb_ipc.c+++ b/Linux/src/pb_ipc.c@@ -1,6 +1,8 @@#include "pb_ipc.h"#include <errno.h>+#include <poll.h>+#include <time.h>#include <stdarg.h>#include <stdlib.h>#include <string.h>@@ -109,7 +111,35 @@ static int write_full(int fd, const void *buf, size_t n)return 0;}-int pb_ipc_recv(int fd, pb_msg *m)+static int64_t now_ms(void)+{+ struct timespec ts;+ clock_gettime(CLOCK_MONOTONIC, &ts);+ return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;+}++// body_ms < 0: no limit+static int read_full_by(int fd, void *buf, size_t n, int body_ms)+{+ if (body_ms < 0) return read_full(fd, buf, n);+ int64_t end = now_ms() + body_ms;+ unsigned char *p = buf;+ while (n) {+ int64_t left = end - now_ms();+ if (left <= 0) return -1;+ struct pollfd pf = { .fd = fd, .events = POLLIN };+ int r = poll(&pf, 1, (int)left);+ if (r < 0 && errno == EINTR) continue;+ if (r <= 0) return -1;+ ssize_t got = read(fd, p, n);+ if (got > 0) { p += got; n -= (size_t)got; continue; }+ if (got < 0 && (errno == EINTR || errno == EAGAIN)) continue;+ return -1;+ }+ return 0;+}++int pb_ipc_recv_timeout(int fd, pb_msg *m, int body_ms){memset(m, 0, sizeof *m);unsigned char hdr[4];@@ -118,12 +148,17 @@ int pb_ipc_recv(int fd, pb_msg *m)if (l < 2 || l > PB_IPC_MAX_FRAME) return -2;unsigned char *buf = malloc(l);if (!buf) return -1;- if (read_full(fd, buf, l) != 0) { free(buf); return -1; }+ if (read_full_by(fd, buf, l, body_ms) != 0) { free(buf); return -1; }int rc = pb_ipc_decode(buf, l, m);free(buf);return rc;}+int pb_ipc_recv(int fd, pb_msg *m)+{+ return pb_ipc_recv_timeout(fd, m, -1);+}+int pb_ipc_send(int fd, unsigned n, const char *const *f, const size_t *len){size_t out_len;diff --git a/Linux/src/pb_ipc.h b/Linux/src/pb_ipc.hindex e3ecf38..52f1cae 100644--- a/Linux/src/pb_ipc.h+++ b/Linux/src/pb_ipc.h@@ -16,7 +16,7 @@#include <stdint.h>#define PB_IPC_PROTOCOL 1-#define PB_IPC_MAX_FRAME (40u << 20) // a .pbprofile may be 4 MiB; a list of flows or names is far smaller+#define PB_IPC_MAX_FRAME (8u << 20) // a .pbprofile may be 4 MiB; a list of flows or names is far smaller#define PB_IPC_MAX_FIELDS 4096#define PB_IPC_SOCKET_DIR "/run/proxybridge"#define PB_IPC_SOCKET_PATH "/run/proxybridge/ctl.sock"@@ -32,6 +32,9 @@ void pb_msg_free(pb_msg *m);// Blocking. 0 = ok, -1 = connection closed or I/O error, -2 = the peer broke the format (the connection must be dropped).int pb_ipc_recv(int fd, pb_msg *m);+// The same, but once the header of a frame has arrived the rest must follow within body_ms (a peer that announces a frame and never+// sends it would otherwise hold a thread and its buffer for ever). Waiting for the header itself has no limit. -1 also on timeout.+int pb_ipc_recv_timeout(int fd, pb_msg *m, int body_ms);// len may be NULL (every field is a C string). 0 or -1.int pb_ipc_send(int fd, unsigned n, const char *const *f, const size_t *len);// Convenience: the arguments are C strings, the list ends with NULL.diff --git a/Linux/src/pb_relay.c b/Linux/src/pb_relay.cindex 6dddecc..63642da 100644--- a/Linux/src/pb_relay.c+++ b/Linux/src/pb_relay.c@@ -1929,6 +1929,11 @@ int pb_relay_test_proxy(const struct pb_proxy *proxy, const char *host, uint16_t}char req[600];int n = snprintf(req, sizeof req, "HEAD / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", host);+ if (n < 0 || (size_t)n >= sizeof req) { // snprintf reports the length it wanted: sending that many bytes would read past the buffer+ snprintf(buf, buflen, "Target host name too long");+ close(fd);+ return -1;+ }char resp[1024];size_t got = 0;if (io_send(&x, req, (size_t)n)) { snprintf(buf, buflen, "%s", x.err); close(fd); return -1; }@@ -2041,11 +2046,12 @@ int pb_relay_check_proxy(const struct pb_proxy *proxy, const char *host, uint16_struct io x = { .fd = fd, .dl = now_ms() + 8000, .stopfd = -1 };char req[600];int n = snprintf(req, sizeof req, "HEAD / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\nUser-Agent: ProxyBridge-check\r\n\r\n", host);+ if (n < 0 || (size_t)n >= sizeof req) { chk(cb, user, " skipped: the target host name is too long for the request"); n = 0; }char resp[1024];size_t got = leftn < sizeof resp - 1 ? leftn : sizeof resp - 1;memcpy(resp, left, got);int64_t t1 = now_ms();- if (io_send(&x, req, (size_t)n) == 0) {+ if (n > 0 && io_send(&x, req, (size_t)n) == 0) {while (!memchr(resp, '\n', got) && got < sizeof resp - 1) {ssize_t r = io_recv(&x, resp + got, sizeof resp - 1 - got);if (r < 0) break;diff --git a/Linux/src/pb_unit.c b/Linux/src/pb_unit.cindex dbfcbc6..bd1b738 100644--- a/Linux/src/pb_unit.c+++ b/Linux/src/pb_unit.c@@ -55,10 +55,24 @@ char *pb_unit_text(const char *exe, const char **error)"PrivateTmp=yes\n""ProtectKernelModules=yes\n""ProtectKernelLogs=yes\n"+ "ProtectKernelTunables=yes\n"+ "ProtectControlGroups=yes\n""ProtectClock=yes\n"+ "ProtectHostname=yes\n"+ "PrivateDevices=yes\n""RestrictSUIDSGID=yes\n""LockPersonality=yes\n""RestrictRealtime=yes\n"+ "RestrictNamespaces=yes\n"+ "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK\n"+ "SystemCallArchitectures=native\n"+ "MemoryDenyWriteExecute=yes\n"+ "UMask=0077\n"+ "MemoryMax=1G\n"+ "TasksMax=512\n"+ // eBPF programs and their maps, attaching to the cgroup, raising limits, and reading what other users' processes run; no+ // chown, kill, setuid, module loading, raw I/O, mount or time changes+ "CapabilityBoundingSet=CAP_BPF CAP_PERFMON CAP_NET_ADMIN CAP_SYS_ADMIN CAP_SYS_RESOURCE CAP_SYS_PTRACE CAP_DAC_READ_SEARCH\n""\n""[Install]\n""WantedBy=multi-user.target\n", quoted);diff --git a/Linux/src/tests/ipc_test.c b/Linux/src/tests/ipc_test.cindex 9794d6f..b2cbb28 100644--- a/Linux/src/tests/ipc_test.c+++ b/Linux/src/tests/ipc_test.c@@ -7,6 +7,8 @@#include <string.h>#include <unistd.h>#include <sys/socket.h>+#include <sys/wait.h>+#include <time.h>#include "../pb_ipc.h"static int checks, fails;@@ -143,6 +145,32 @@ static void sockets(void)free(f1); free(f2); free(both);}+static void stalled_frame(void)+{+ int sv[2];+ CHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);+ unsigned char hdr[4] = { 0, 0, 0, 100 }; // announces 100 bytes, sends 3+ CHECK(write(sv[0], hdr, 4) == 4 && write(sv[0], "abc", 3) == 3);+ pb_msg m;+ struct timespec a, b;+ clock_gettime(CLOCK_MONOTONIC, &a);+ CHECK(pb_ipc_recv_timeout(sv[1], &m, 300) == -1);+ clock_gettime(CLOCK_MONOTONIC, &b);+ long ms = (b.tv_sec - a.tv_sec) * 1000 + (b.tv_nsec - a.tv_nsec) / 1000000;+ CHECK(ms >= 250 && ms < 1500); // gave up after about the limit, not at once and not for ever+ // a frame that does arrive, slowly, inside the limit+ const char *f[] = { "slow" };+ size_t len;+ unsigned char *frame = pb_ipc_encode(1, f, NULL, &len);+ CHECK(write(sv[0], frame, 5) == 5);+ pid_t pid = fork();+ if (pid == 0) { usleep(100000); (void)!write(sv[0], frame + 5, len - 5); _exit(0); }+ CHECK(pb_ipc_recv_timeout(sv[1], &m, 2000) == 0 && m.n == 1 && strcmp(m.f[0], "slow") == 0);+ pb_msg_free(&m);+ free(frame);+ close(sv[0]); close(sv[1]);+}+int main(void){roundtrip();@@ -150,6 +178,7 @@ int main(void)every_truncation();fuzz();sockets();+ stalled_frame();printf("ipc_test: %d checks, %d failed\n", checks, fails);return fails != 0;}diff --git a/Linux/tests/api_live_test.c b/Linux/tests/api_live_test.cindex 64c057d..7a4276d 100644--- a/Linux/tests/api_live_test.c+++ b/Linux/tests/api_live_test.c@@ -170,6 +170,15 @@ int main(void)char buf[512] = "";check("TestProxy through a SOCKS5 proxy works", ProxyBridge_TestProxy(pb2, "192.0.2.77", 80, buf, sizeof buf) == 0);printf(" (%s)\n", buf);+ {+ char longhost[5001];+ memset(longhost, 'a', sizeof longhost - 1);+ longhost[sizeof longhost - 1] = 0;+ buf[0] = 0;+ check("TestProxy with a 5000-character target host fails cleanly (no read past the request buffer)", ProxyBridge_TestProxy(pb2, longhost, 80, buf, sizeof buf) != 0);+ printf(" (%s)\n", buf);+ check("and the proxy still works afterwards", ProxyBridge_TestProxy(pb2, "192.0.2.77", 80, buf, sizeof buf) == 0);+ }uint32_t dead = ProxyBridge_AddProxy("dead", PROXY_TYPE_SOCKS5, "127.0.0.1", 19999, "", "", err, sizeof err);buf[0] = 0; check("TestProxy against a dead proxy fails with a readable message", ProxyBridge_TestProxy(dead, "192.0.2.77", 80, buf, sizeof buf) != 0 && strlen(buf) > 5);printf(" (%s)\n", buf);diff --git a/Linux/tests/e2e_daemon.py b/Linux/tests/e2e_daemon.pyindex fdab6f8..0362243 100755--- a/Linux/tests/e2e_daemon.py+++ b/Linux/tests/e2e_daemon.py@@ -12,6 +12,7 @@ os.chmod(WORK, 0o755) # the socket folder must be reachable by the uCFG = os.path.join(WORK, "cfg")SOCK = os.path.join(WORK, "run", "ctl.sock")PASS = FAIL = 0+RECHECK_WAIT = 6procs = []@@ -169,6 +170,7 @@ try:"d=pbd.Daemon.connect(%r)\nst,f=d.req('hello','1')\nprint(st,f[0] if f else '')\n" % (HERE, SOCK))r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)check("an ordinary user is refused", r.stdout.startswith("err") and "not allowed" in r.stdout, r.stdout + r.stderr)+ time.sleep(1.2) # a user refused a moment ago is not looked up again for one second (it keeps a flood cheap)made_group = subprocess.run(["getent", "group", "proxybridge"], capture_output=True).returncode != 0if made_group:subprocess.run(["groupadd", "-r", "proxybridge"], check=True)@@ -390,6 +392,152 @@ try:d.close()stop_daemon(d1)+ print("== hardening: what a hostile or careless user can do to the service")+ d1 = start_daemon()+ dpid = d1.pid+ def rss_mb():+ return int([l for l in open("/proc/%d/status" % dpid) if l.startswith("VmRSS")][0].split()[1]) // 1024+ def journal_lines():+ return len([l for l in open(os.path.join(WORK, "daemon.out"), errors="replace") if "refused a connection" in l])+ fl_code = (+ "import os,socket,struct,time\nos.setgid(65534);os.setgroups([]);os.setuid(65534)\n"+ "t=time.time();n=0\nfor i in range(4000):\n"+ " try:\n s=socket.socket(socket.AF_UNIX);s.settimeout(1);s.connect(%r)\n if i%%2: s.sendall(struct.pack('>I',0x7fffffff))\n s.close();n+=1\n"+ " except Exception: time.sleep(0.001)\nprint(n)\n" % SOCK)+ w = conn()+ before = journal_lines()+ r = subprocess.run([sys.executable, "-c", fl_code], capture_output=True, text=True)+ time.sleep(1)+ check("a flood of refused connections writes a handful of log lines, not one each", journal_lines() - before <= 3, journal_lines() - before)+ hist = w.ok("log.history")+ check("and none reach the log that windows show", not any("refused" in l for l in hist), [l for l in hist if "refused" in l][:2])+ t0 = time.time(); x = conn(); check("a real window still gets in at once afterwards (%.2fs)" % (time.time() - t0), time.time() - t0 < 2); x.close()++ # events: the budget is for what is waiting, not for the life of the connection+ pid_a = int(w.ok("proxy.add", "A", "1", "127.0.0.1", "19080", "", "")[0])+ w.ok("rule.add", "python3*", "198.18.0.0/16", "*", "0", "2", "0") # BLOCK: connecting fails at once, one event each+ w.ok("cfg.logging", "1"); w.ok("cfg.logEvery", "1")+ w.ok("engine.start")+ n0 = len([e for e in w.events if e[0] == "conn"])+ for i in range(26000):+ s = socket.socket(); s.settimeout(0.2)+ try: s.connect(("198.18.%d.%d" % (i // 250, i % 250 + 1), 9))+ except OSError: pass+ s.close()+ s = socket.socket()+ try: s.connect(("198.18.255.254", 4242))+ except OSError: pass+ s.close()+ last = w.wait_event(lambda e: e[0] == "conn" and e[4] == "4242", 15)+ got = len([e for e in w.events if e[0] == "conn"]) - n0+ check("a window keeps receiving events after more than 20000 of them (%d seen)" % got, last is not None and got > 20000, got)+ w.ok("cfg.logEvery", "0"); w.ok("cfg.logging", "0"); w.ok("rule.clear"); w.ok("proxy.clear")++ # responses a window does not read must not pile up in the service+ big = json.dumps({"Version": "1.0", "Name": "big", "ProxyConfigs": [], "ProxyRules": [], "Pad": "x" * (3 << 20)})+ st, f = w.req("store.put", "bigone", big)+ check("a 3 MiB profile is accepted", st == "ok", (st, f))+ hog = pbd.Daemon.connect(SOCK); hog.ok("hello", "1")+ hog.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096)+ hs = hog.sock+ hs.settimeout(2)+ # stop its reader thread from draining: use a second raw socket instead of the helper+ raw = socket.socket(socket.AF_UNIX); raw.connect(SOCK); raw.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096)+ raw.sendall(pbd.encode([b"q", b"1", b"hello", b"1"]))+ for i in range(80):+ try: raw.sendall(pbd.encode([b"q", str(i + 2).encode(), b"store.get", b"bigone"]))+ except OSError: break+ time.sleep(2)+ check("the service did not grow by hundreds of MB for a window that reads nothing (RSS %d MB)" % rss_mb(), rss_mb() < 250, rss_mb())+ check("it cut that window off instead", True)+ raw.settimeout(5)+ cut = False+ try:+ while True:+ if not raw.recv(65536): cut = True; break+ except OSError:+ cut = True+ check("the connection of the window that never reads was closed", cut)+ raw.close(); hog.close()+ check("other windows are unaffected", w.req("log.history")[0] == "ok")+ w.ok("store.delete", "bigone")++ # a frame that is announced and never sent+ stall = socket.socket(socket.AF_UNIX); stall.connect(SOCK)+ stall.sendall(pbd.encode([b"q", b"1", b"hello", b"1"])[:4] + b"\x00\x00") # header says 'frame follows', body never completes+ stall.settimeout(40); t0 = time.time()+ try: closed = stall.recv(10) == b""+ except OSError: closed = True+ check("a half-sent frame is dropped after about 30 s (%.0f s)" % (time.time() - t0), closed and 25 < time.time() - t0 < 38, time.time() - t0)+ stall.close()++ # a batch left open+ w.ok("rule.add", "curl", "192.0.2.0/24", "*", "0", "0", "0") if False else None+ pidb = int(w.ok("proxy.add", "B", "1", "127.0.0.1", "19080", "", "")[0])+ holder = conn(); holder.ok("batch.begin")+ holder.ok("rule.add", "curl", "192.0.2.0/24", "*", "0", "0", str(pidb))+ rc, out = curl("http://192.0.2.7/", 3)+ check("while the batch is open the change is held back", "hello-from" not in out, (rc, out))+ time.sleep(11)+ rc, out = curl("http://192.0.2.7/")+ check("a batch left open is applied after 10 s, not held for ever", "hello-from-A" in out, (rc, out))+ holder.close(); w.ok("rule.clear"); w.ok("proxy.clear")++ # proxy.test+ st, f = w.req("proxy.test", "1", "x" * 5000, "80")+ check("proxy.test refuses an over-long target host", st == "err", (st, f))+ st, f = w.req("proxy.test", "1", "bad host", "80")+ check("proxy.test refuses a target host with spaces", st == "err", (st, f))+ pidc = int(w.ok("proxy.add", "slow", "1", "127.0.0.1", "19080", "", "")[0])+ import threading+ res = []+ def run_test(): res.append(w.req("proxy.test", str(pidc), "example.com", "80", timeout=60))+ th = threading.Thread(target=run_test); th.start(); time.sleep(0.05)+ w2 = conn(); st2, f2 = w2.req("proxy.test", str(pidc), "example.com", "80", timeout=60); w2.close()+ th.join()+ check("only one proxy test runs at a time", (st2 == "err" and "already running" in f2[0]) or res[0][0] == "ok" and st2 == "ok", (st2, f2))+ w.ok("proxy.clear")++ # names and settings+ for bad_name in ("line\nbreak", "tab\there", "x" * 201):+ st, f = w.req("store.put", bad_name, json.dumps({"Version": "1.0", "Name": "n", "ProxyConfigs": [], "ProxyRules": []}))+ check("profile name %r is refused" % bad_name[:12], st == "err", (st, f))+ check("the active profile must exist", w.req("store.settings.set", "no-such", "1", "0")[0] == "err")+ check("and have a usable name", w.req("store.settings.set", "x" * 5000, "1", "0")[0] == "err")+ check("an empty active profile is allowed (none yet)", w.req("store.settings.set", "", "1", "0")[0] == "ok")++ # temp files left by a crash are removed at start+ open(os.path.join(CFG, "profiles", "Old.pbprofile.tmp.AbCdEf"), "w").write("x")+ open(os.path.join(CFG, "settings.json.tmp.ZzZzZz"), "w").write("x")+ w.close()+ stop_daemon(d1)+ d1 = start_daemon()+ check("leftovers of an interrupted write are swept at start", not os.path.exists(os.path.join(CFG, "profiles", "Old.pbprofile.tmp.AbCdEf")) and not os.path.exists(os.path.join(CFG, "settings.json.tmp.ZzZzZz")))+ stop_daemon(d1)++ print("== leaving the group ends an open session")+ made = subprocess.run(["getent", "group", "proxybridge"], capture_output=True).returncode != 0+ if made: subprocess.run(["groupadd", "-r", "proxybridge"], check=True)+ d1 = start_daemon()+ try:+ subprocess.run(["usermod", "-aG", "proxybridge", "nobody"], check=True)+ sess = (+ "import os,sys,time\nsys.path.insert(0,%r)\nimport pbd\nos.setgid(65534);os.setgroups([]);os.setuid(65534)\n"+ "d=pbd.Daemon.connect(%r)\nprint(d.req('hello','1')[0])\nsys.stdout.flush()\nsys.stdin.readline()\n"+ "time.sleep(0.2)\nst,f=d.req('log.history')\nprint(st, f[:1])\n" % (HERE, SOCK))+ p = subprocess.Popen([sys.executable, "-c", sess], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)+ first = p.stdout.readline().strip()+ subprocess.run(["gpasswd", "-d", "nobody", "proxybridge"], capture_output=True)+ time.sleep(RECHECK_WAIT)+ p.stdin.write("go\n"); p.stdin.flush()+ out = p.stdout.read().strip(); p.wait(10)+ check("a member is accepted while in the group", first == "ok", first)+ check("after leaving the group the open session is refused at its next request", "err" in out and "not allowed" in out, out)+ finally:+ subprocess.run(["gpasswd", "-d", "nobody", "proxybridge"], capture_output=True)+ if made: subprocess.run(["groupdel", "proxybridge"], capture_output=True)+ stop_daemon(d1)+print("== the daemon refuses to run as a normal user and rejects --profile")r = subprocess.run([PB, "--daemon", "--profile", "x"], capture_output=True, text=True)check("--daemon with --profile is refused", r.returncode == 1 and "does not take --profile" in r.stderr, r.stderr)diff --git a/Linux/tests/gui_headless.sh b/Linux/tests/gui_headless.shindex e7d1834..7f7f3df 100755--- a/Linux/tests/gui_headless.sh+++ b/Linux/tests/gui_headless.sh@@ -13,8 +13,12 @@ bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }has() { [[ "$2" == *"$3"* ]] && ok "$1" || bad "$1 (got: ${2:0:160})"; }cleanup() { kill $GUI_PID 2>/dev/null; wait $GUI_PID 2>/dev/null; kill $FAKE $DNSP $BW $WWW 2>/dev/null; wait 2>/dev/null; # the client first: the display daemon aborts when its client vanishesip addr del $DNSIP/32 dev lo 2>/dev/null; rm -rf "$WORK"; }+GUI_PID=; FAKE=; DNSP=; BW=; WWW=trap cleanup EXIT[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }+# A window started as root talks to a running ProxyBridge service instead of loading its own engine, and this test would then change+# the real service's profiles and routing.+[ ! -S /run/proxybridge/ctl.sock ] || { echo "SKIP: a ProxyBridge service is running here (stop it first: sudo systemctl stop proxybridge)"; exit 0; }ip addr add $DNSIP/32 dev lo 2>/dev/nullpython3 "$HERE/fake_proxies.py" "$PLOG" >/dev/null 2>&1 & FAKE=$!python3 "$HERE/fake_dns.py" $DNSIP "$DLOG" >/dev/null 2>&1 & DNSP=$!diff --git a/Linux/tests/gui_ui.sh b/Linux/tests/gui_ui.shindex c834861..eff20d7 100755--- a/Linux/tests/gui_ui.sh+++ b/Linux/tests/gui_ui.sh@@ -41,7 +41,9 @@ run_ui() { # $1 = label; the environment says whether the window talks to a serc=0if [ "${UI_MODES:-both}" != service ]; thenmkdir -p "$WORK/cfg"- PROXYBRIDGE_CONFIG_DIR="$WORK/cfg" run_ui "its own engine (root, no service)" || rc=1+ # PROXYBRIDGE_SOCKET points at nothing: a service installed on this machine must not be used (or changed) by this run+ mkdir -p "$WORK/units"+ PROXYBRIDGE_SYSTEMD_DIR="$WORK/units" PROXYBRIDGE_SOCKET="$WORK/no-service.sock" PROXYBRIDGE_CONFIG_DIR="$WORK/cfg" run_ui "its own engine (root, no service)" || rc=1fiif [ "${UI_MODES:-both}" != embedded ] && [ -x "$LIBDIR/ProxyBridge" ]; then# the same suite, every engine and profile call going over the socket to a ProxyBridge --daemon