Skip to content

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

feat(linux): ProxyBridge service (root) and an unprivileged window that talks to it over a socket

anof-cybere34cec0efe13
diff --git a/Linux/cli/Makefile b/Linux/cli/Makefile
index d763cd2..8ba08b0 100644
--- a/Linux/cli/Makefile
+++ b/Linux/cli/Makefile
@@ -21,7 +21,7 @@ LIBS = -lproxybridge -lpthread
endif
TARGET = $(BUILD_DIR)/ProxyBridge
-OBJECTS = $(BUILD_DIR)/main.o $(BUILD_DIR)/pb_profile.o
+OBJECTS = $(BUILD_DIR)/main.o $(BUILD_DIR)/daemon.o $(BUILD_DIR)/pb_profile.o $(BUILD_DIR)/pb_ipc.o $(BUILD_DIR)/pb_unit.o
all: $(TARGET)
@@ -34,6 +34,12 @@ $(TARGET): $(OBJECTS)
$(BUILD_DIR)/%.o: %.c | $(BUILD_DIR)
$(CC) $(CFLAGS) -c $< -o $@
+$(BUILD_DIR)/pb_unit.o: ../src/pb_unit.c ../src/pb_unit.h | $(BUILD_DIR)
+ $(CC) $(CFLAGS) -c $< -o $@
+
+$(BUILD_DIR)/pb_ipc.o: ../src/pb_ipc.c ../src/pb_ipc.h | $(BUILD_DIR)
+ $(CC) $(CFLAGS) -c $< -o $@
+
$(BUILD_DIR)/pb_profile.o: ../profile/pb_profile.c ../profile/pb_profile.h | $(BUILD_DIR)
$(CC) $(CFLAGS) -c $< -o $@
diff --git a/Linux/cli/daemon.c b/Linux/cli/daemon.c
new file mode 100644
index 0000000..fd53936
--- /dev/null
+++ b/Linux/cli/daemon.c
@@ -0,0 +1,885 @@
+#define _GNU_SOURCE
+#include "daemon.h"
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <grp.h>
+#include <poll.h>
+#include <pthread.h>
+#include <pwd.h>
+#include <signal.h>
+#include <stdarg.h>
+#include <stdatomic.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/un.h>
+#include <sys/signalfd.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "../src/ProxyBridge.h"
+#include "../src/pb_ipc.h"
+#include "../profile/pb_profile.h"
+
+#define GROUP_NAME "proxybridge"
+#define MAX_CLIENTS 16
+#define MAX_PROFILES 512
+#define EVENT_QUEUE_MAX 20000
+#define HISTORY_LINES 200
+
+// ---- clients ---------------------------------------------------------------------------------------------------------------
+struct outmsg {
+ struct outmsg *next;
+ unsigned char *frame;
+ size_t len;
+};
+
+struct client {
+ int fd;
+ uid_t uid;
+ pthread_mutex_t mu;
+ pthread_cond_t cv;
+ struct outmsg *head, *tail;
+ size_t nevents; // queued events (responses are never dropped)
+ unsigned long dropped;
+ bool closing;
+ int batch_depth; // BeginBatch calls this client has not yet closed
+ atomic_int refs;
+ struct client *next;
+};
+
+static pthread_mutex_t clients_mu = PTHREAD_MUTEX_INITIALIZER;
+static struct client *clients;
+static int nclients;
+static int verbose;
+
+// engine state as the daemon last set it (the library has no getters)
+static pthread_mutex_t state_mu = PTHREAD_MUTEX_INITIALIZER;
+static bool engine_running;
+static bool engine_enabled = true;
+static bool logging_requested;
+
+static char history[HISTORY_LINES][512];
+static unsigned history_count; // total lines ever written
+static pthread_mutex_t history_mu = PTHREAD_MUTEX_INITIALIZER;
+
+static void enqueue(struct client *c, unsigned char *frame, size_t len, bool is_event)
+{
+ pthread_mutex_lock(&c->mu);
+ if (c->closing || (is_event && c->nevents >= EVENT_QUEUE_MAX)) {
+ if (is_event && !c->closing) c->dropped++;
+ pthread_mutex_unlock(&c->mu);
+ 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;
+ if (c->tail) c->tail->next = m; else c->head = m;
+ c->tail = m;
+ if (is_event) c->nevents++;
+ pthread_cond_signal(&c->cv);
+ pthread_mutex_unlock(&c->mu);
+}
+
+static void send_to(struct client *c, bool is_event, unsigned n, const char *const *f)
+{
+ size_t len;
+ unsigned char *frame = pb_ipc_encode(n, f, NULL, &len);
+ if (frame) enqueue(c, frame, len, is_event);
+}
+
+static void broadcast(unsigned n, const char *const *f)
+{
+ size_t len;
+ unsigned char *frame = pb_ipc_encode(n, f, NULL, &len);
+ if (!frame) return;
+ pthread_mutex_lock(&clients_mu);
+ for (struct client *c = clients; c; c = c->next) {
+ unsigned char *copy = malloc(len);
+ if (!copy) continue;
+ memcpy(copy, frame, len);
+ enqueue(c, copy, len, true);
+ }
+ pthread_mutex_unlock(&clients_mu);
+ free(frame);
+}
+
+static void *writer_main(void *arg)
+{
+ struct client *c = arg;
+ for (;;) {
+ pthread_mutex_lock(&c->mu);
+ while (!c->head && !c->closing) pthread_cond_wait(&c->cv, &c->mu);
+ if (c->closing) { pthread_mutex_unlock(&c->mu); break; }
+ struct outmsg *m = c->head;
+ c->head = m->next;
+ if (!c->head) c->tail = NULL;
+ pthread_mutex_unlock(&c->mu);
+ size_t off = 0;
+ bool ok = true;
+ while (off < m->len) {
+ ssize_t w = send(c->fd, m->frame + off, m->len - off, MSG_NOSIGNAL);
+ if (w > 0) { off += (size_t)w; continue; }
+ if (w < 0 && errno == EINTR) continue;
+ ok = false;
+ break;
+ }
+ free(m->frame);
+ free(m);
+ if (!ok) {
+ pthread_mutex_lock(&c->mu);
+ c->closing = true;
+ pthread_mutex_unlock(&c->mu);
+ shutdown(c->fd, SHUT_RDWR); // wakes the reader
+ break;
+ }
+ }
+ if (atomic_fetch_sub(&c->refs, 1) == 1) {
+ for (struct outmsg *m = c->head; m;) { struct outmsg *n = m->next; free(m->frame); free(m); m = n; }
+ close(c->fd);
+ pthread_mutex_destroy(&c->mu);
+ pthread_cond_destroy(&c->cv);
+ free(c);
+ }
+ return NULL;
+}
+
+// ---- logging ---------------------------------------------------------------------------------------------------------------
+static void on_log(const char *msg)
+{
+ pthread_mutex_lock(&history_mu);
+ snprintf(history[history_count % HISTORY_LINES], sizeof history[0], "%s", msg);
+ history_count++;
+ pthread_mutex_unlock(&history_mu);
+ if (verbose == 1 || verbose == 3) { printf("[LOG] %s\n", msg); fflush(stdout); }
+ const char *f[] = { "e", "log", msg };
+ broadcast(3, f);
+}
+
+static void dlog(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
+static void dlog(const char *fmt, ...)
+{
+ char buf[512];
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(buf, sizeof buf, fmt, ap);
+ va_end(ap);
+ for (char *p = buf; *p; p++) if ((unsigned char)*p < 0x20 || *p == 0x7f) *p = '?';
+ // the daemon's own lines go to the journal always: a service nobody watches still has to say why it did something
+ printf("[PB] %s\n", buf);
+ fflush(stdout);
+ pthread_mutex_lock(&history_mu);
+ snprintf(history[history_count % HISTORY_LINES], sizeof history[0], "%s", buf);
+ history_count++;
+ pthread_mutex_unlock(&history_mu);
+ const char *f[] = { "e", "log", buf };
+ broadcast(3, f);
+}
+
+static void on_conn(const char *proc, uint32_t pid, const char *ip, uint16_t port, const char *proto, const char *via)
+{
+ char pidb[16], portb[8];
+ snprintf(pidb, sizeof pidb, "%u", pid);
+ snprintf(portb, sizeof portb, "%u", port);
+ if (verbose == 2 || verbose == 3) {
+ printf("[CONN] %s (PID:%u) -> %s:%u via %s%s\n", proc, pid, ip, port, via, proto && !strcmp(proto, "UDP") ? " (UDP)" : "");
+ fflush(stdout);
+ }
+ const char *f[] = { "e", "conn", proc, pidb, ip, portb, proto ? proto : "TCP", via };
+ broadcast(8, f);
+}
+
+// ---- helpers ---------------------------------------------------------------------------------------------------------------
+// Numbers are parsed here, not with strto*, so the program does not depend on the C library's redirected symbols.
+static bool pu(const char *s, uint64_t max, uint64_t *out)
+{
+ if (!s || !*s || strlen(s) > 19) return false;
+ uint64_t v = 0;
+ for (const char *p = s; *p; p++) {
+ if (*p < '0' || *p > '9') return false;
+ v = v * 10 + (uint64_t)(*p - '0');
+ }
+ if (v > max) return false;
+ *out = v;
+ return true;
+}
+
+static void reply(struct client *c, const char *id, const char *status, unsigned nextra, const char *const *extra)
+{
+ const char *f[8 + 4];
+ unsigned n = 0;
+ f[n++] = "r"; f[n++] = id; f[n++] = status;
+ for (unsigned i = 0; i < nextra && n < 12; i++) f[n++] = extra[i];
+ send_to(c, false, n, f);
+}
+
+static void reply_ok(struct client *c, const char *id) { reply(c, id, "ok", 0, NULL); }
+static void reply_ok1(struct client *c, const char *id, const char *v) { const char *x[] = { v }; reply(c, id, "ok", 1, x); }
+static void reply_err(struct client *c, const char *id, const char *why) { const char *x[] = { why }; reply(c, id, "err", 1, x); }
+
+static void reply_u64(struct client *c, const char *id, uint64_t v)
+{
+ char b[24];
+ snprintf(b, sizeof b, "%llu", (unsigned long long)v);
+ reply_ok1(c, id, b);
+}
+
+// ---- profile store ---------------------------------------------------------------------------------------------------------
+static bool ensure_dir(const char *dir)
+{
+ struct stat st;
+ if (stat(dir, &st) == -1) {
+ if (mkdir(dir, 0700) != 0 && errno != EEXIST) return false;
+ } else if (chmod(dir, 0700) != 0) {
+ return false;
+ }
+ return true;
+}
+
+static bool ensure_store(void)
+{
+ char sub[4096];
+ snprintf(sub, sizeof sub, "%s/profiles", pbp_config_dir());
+ return ensure_dir(pbp_config_dir()) && ensure_dir(sub);
+}
+
+static char *profile_file(const char *name)
+{
+ char *file = pbp_filename_for(name);
+ if (!file) return NULL;
+ char *path = NULL;
+ if (asprintf(&path, "%s/profiles/%s", pbp_config_dir(), file) < 0) path = NULL;
+ free(file);
+ return path;
+}
+
+static int cmp_str(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
+
+static void store_list(struct client *c, const char *id)
+{
+ char dir[4096];
+ snprintf(dir, sizeof dir, "%s/profiles", pbp_config_dir());
+ DIR *d = opendir(dir);
+ char **names = calloc(MAX_PROFILES + 1, sizeof *names);
+ unsigned n = 0;
+ struct dirent *de;
+ while (names && d && (de = readdir(d)) != NULL && n < MAX_PROFILES) {
+ char *name = pbp_name_from_filename(de->d_name);
+ if (name) names[n++] = name;
+ }
+ if (d) closedir(d);
+ if (!names) { reply_err(c, id, "out of memory"); return; }
+ qsort(names, n, sizeof *names, cmp_str);
+ const char **f = calloc(n + 3, sizeof *f);
+ if (f) {
+ f[0] = "r"; f[1] = id; f[2] = "ok";
+ for (unsigned i = 0; i < n; i++) f[3 + i] = names[i];
+ send_to(c, false, n + 3, f);
+ free(f);
+ }
+ for (unsigned i = 0; i < n; i++) free(names[i]);
+ free(names);
+}
+
+static void store_get(struct client *c, const char *id, const char *name)
+{
+ char *path = profile_file(name);
+ if (!path) { reply_err(c, id, "unusable profile name"); return; }
+ FILE *f = fopen(path, "rb");
+ free(path);
+ if (!f) { reply_err(c, id, "no such profile"); return; }
+ char *buf = malloc(PBP_MAX_FILE + 1);
+ size_t n = buf ? fread(buf, 1, PBP_MAX_FILE + 1, f) : 0;
+ fclose(f);
+ if (!buf || n > PBP_MAX_FILE) { free(buf); reply_err(c, id, "profile file too large"); return; }
+ buf[n] = '\0';
+ const char *fl[] = { "r", id, "ok", buf };
+ size_t ll[] = { 1, strlen(id), 2, n };
+ size_t len;
+ unsigned char *frame = pb_ipc_encode(4, fl, ll, &len);
+ if (frame) enqueue(c, frame, len, false); else reply_err(c, id, "profile file too large");
+ free(buf);
+}
+
+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; }
+ char *path = profile_file(name);
+ if (!path) { reply_err(c, id, "unusable profile name"); return; }
+ struct pbp_profile p;
+ char err[256];
+ if (pbp_parse(data, dlen, &p, err, sizeof err) != 0) { free(path); reply_err(c, id, err); return; }
+ pbp_free(&p);
+ if (access(path, F_OK) != 0) { // a new profile: keep the number bounded
+ char dir[4096];
+ snprintf(dir, sizeof dir, "%s/profiles", pbp_config_dir());
+ unsigned count = 0;
+ DIR *d = opendir(dir);
+ struct dirent *de;
+ while (d && (de = readdir(d)) != NULL) { char *nm = pbp_name_from_filename(de->d_name); if (nm) count++; free(nm); }
+ if (d) closedir(d);
+ if (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 (pbp_write_file(path, data, err, sizeof err) != 0) { free(path); reply_err(c, id, err); return; }
+ free(path);
+ reply_ok(c, id);
+}
+
+static void store_delete(struct client *c, const char *id, const char *name)
+{
+ char *path = profile_file(name);
+ if (!path) { reply_err(c, id, "unusable profile name"); return; }
+ int rc = unlink(path);
+ free(path);
+ if (rc != 0 && errno != ENOENT) reply_err(c, id, strerror(errno)); else reply_ok(c, id);
+}
+
+// ---- engine control --------------------------------------------------------------------------------------------------------
+static bool engine_start(void)
+{
+ bool ok = ProxyBridge_Start();
+ pthread_mutex_lock(&state_mu);
+ engine_running = ok;
+ pthread_mutex_unlock(&state_mu);
+ return ok;
+}
+
+static void engine_stop(void)
+{
+ ProxyBridge_Stop();
+ pthread_mutex_lock(&state_mu);
+ engine_running = false;
+ pthread_mutex_unlock(&state_mu);
+}
+
+static void update_logging(void)
+{
+ pthread_mutex_lock(&clients_mu);
+ int n = nclients;
+ pthread_mutex_unlock(&clients_mu);
+ pthread_mutex_lock(&state_mu);
+ bool on = logging_requested && n > 0;
+ pthread_mutex_unlock(&state_mu);
+ ProxyBridge_SetTrafficLoggingEnabled(on || verbose == 2 || verbose == 3);
+}
+
+// Loads the profile that was active when the service last ran, so the machine is routed from the moment it boots, before any
+// window is opened.
+static void apply_active_profile(void)
+{
+ char *active = NULL;
+ char path[4096];
+ snprintf(path, sizeof path, "%s/settings.json", pbp_config_dir());
+ if (pbp_settings_load(path, &active, NULL, NULL) != 0 || !active || !*active) {
+ free(active);
+ dlog("no active profile yet: waiting for a window to set one up");
+ return;
+ }
+ char *file = profile_file(active);
+ struct pbp_profile prof;
+ char err[256];
+ if (!file || pbp_load_file(file, &prof, err, sizeof err) != 0) {
+ dlog("profile '%s' cannot be loaded: %s", active, file ? err : "unusable name");
+ free(file);
+ free(active);
+ return;
+ }
+ free(file);
+
+ ProxyBridge_BeginBatch();
+ ProxyBridge_ClearRules();
+ ProxyBridge_ClearProxies();
+ ProxyBridge_SetDnsViaProxy(prof.dns_via_proxy);
+ ProxyBridge_SetLogEveryConnection(prof.log_every);
+ uint32_t ids[PBP_MAX_PROXIES + 1] = { 0 };
+ bool ok = true;
+ for (size_t i = 0; i < prof.nproxies && ok; i++) {
+ const struct pbp_proxy *p = &prof.proxies[i];
+ ids[i] = ProxyBridge_AddProxy(p->name, p->type ? PROXY_TYPE_SOCKS5 : PROXY_TYPE_HTTP, p->host, p->port, p->user, p->pass, err, sizeof err);
+ if (!ids[i]) { dlog("profile '%s': proxy '%s': %s", active, p->name, err); ok = false; break; }
+ if (!p->send_domain) ProxyBridge_SetProxySendDomain(ids[i], false);
+ }
+ if (ok && prof.default_proxy_id)
+ for (size_t i = 0; i < prof.nproxies; i++)
+ if (prof.proxies[i].id == prof.default_proxy_id) ProxyBridge_SetDefaultProxy(ids[i]);
+ size_t enabled = 0;
+ for (size_t i = 0; i < prof.nrules && ok; i++) {
+ const struct pbp_rule *r = &prof.rules[i];
+ if (!r->enabled) continue;
+ uint32_t proxy_id = 0;
+ if (r->action == RULE_ACTION_PROXY && r->proxy_id)
+ for (size_t k = 0; k < prof.nproxies; k++)
+ if (prof.proxies[k].id == r->proxy_id) proxy_id = ids[k];
+ uint32_t rid = ProxyBridge_AddRule(r->process, r->hosts, r->ports, (RuleProtocol)r->protocol, (RuleAction)r->action, proxy_id, err, sizeof err);
+ if (!rid) { dlog("profile '%s': rule %zu: %s", active, i + 1, err); ok = false; break; }
+ if (r->localhost && r->action == RULE_ACTION_PROXY) ProxyBridge_SetRuleLocalhost(rid, true);
+ enabled++;
+ }
+ ProxyBridge_EndBatch();
+ if (!ok) {
+ ProxyBridge_ClearRules();
+ ProxyBridge_ClearProxies();
+ } else {
+ dlog("profile '%s' loaded: %zu proxies, %zu rules", active, prof.nproxies, enabled);
+ }
+ pbp_free(&prof);
+ free(active);
+}
+
+// ---- requests --------------------------------------------------------------------------------------------------------------
+struct test_ctx { struct client *c; const char *id; };
+
+static void test_line(const char *line, void *user)
+{
+ struct test_ctx *t = user;
+ const char *f[] = { "r", t->id, "line", line };
+ send_to(t->c, false, 4, f);
+}
+
+#define NEED(cnt) do { if (m->n != (unsigned)(cnt) + 3) { reply_err(c, id, "wrong number of arguments"); return; } } while (0)
+#define ARG(i) (m->f[3 + (i)])
+
+static bool bool_arg(const char *s, bool *out)
+{
+ if (!strcmp(s, "0")) { *out = false; return true; }
+ if (!strcmp(s, "1")) { *out = true; return true; }
+ return false;
+}
+
+static int read_settings(char **active, bool *updates, bool *boot)
+{
+ char path[4096];
+ snprintf(path, sizeof path, "%s/settings.json", pbp_config_dir());
+ return pbp_settings_load(path, active, updates, boot);
+}
+
+static int write_settings(const char *active, bool updates, bool boot, char *err, size_t errn)
+{
+ char path[4096];
+ if (!ensure_store()) { snprintf(err, errn, "cannot create the configuration folder"); return -1; }
+ snprintf(path, sizeof path, "%s/settings.json", pbp_config_dir());
+ return pbp_settings_save(path, active, updates, boot, err, errn);
+}
+
+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];
+ char err[256] = "";
+ uint64_t a, b;
+ bool on;
+
+ if (!strcmp(cmd, "hello")) {
+ NEED(1);
+ if (!pu(ARG(0), 1000, &a) || a != PB_IPC_PROTOCOL) {
+ snprintf(err, sizeof err, "protocol mismatch: the service speaks %d; update or restart ProxyBridge so both are the same version", PB_IPC_PROTOCOL);
+ reply_err(c, id, err);
+ return;
+ }
+ pthread_mutex_lock(&state_mu);
+ const char *x[] = { PROXYBRIDGE_VERSION, engine_running ? "1" : "0", engine_enabled ? "1" : "0" };
+ pthread_mutex_unlock(&state_mu);
+ reply(c, id, "ok", 3, x);
+ } else if (!strcmp(cmd, "log.history")) {
+ NEED(0);
+ pthread_mutex_lock(&history_mu);
+ unsigned total = history_count < HISTORY_LINES ? history_count : HISTORY_LINES;
+ const char **f = calloc(total + 3, sizeof *f);
+ char (*copy)[512] = malloc(total ? total * sizeof *copy : 1);
+ if (f && copy) {
+ for (unsigned i = 0; i < total; i++) {
+ unsigned idx = (history_count - total + i) % HISTORY_LINES;
+ memcpy(copy[i], history[idx], sizeof copy[i]);
+ f[3 + i] = copy[i];
+ }
+ }
+ pthread_mutex_unlock(&history_mu);
+ if (f && copy) { f[0] = "r"; f[1] = id; f[2] = "ok"; send_to(c, false, total + 3, f); }
+ else reply_err(c, id, "out of memory");
+ free(f); free(copy);
+ }
+ // ---- proxies
+ else if (!strcmp(cmd, "proxy.add") || !strcmp(cmd, "proxy.edit")) {
+ bool edit = cmd[6] == 'e';
+ unsigned base = edit ? 1 : 0;
+ NEED(6 + base);
+ uint64_t pid = 0, type, port;
+ if (edit && !pu(ARG(0), 0xffffffffu, &pid)) { reply_err(c, id, "bad proxy id"); return; }
+ if (!pu(ARG(base + 1), 1, &type) || !pu(ARG(base + 3), 65535, &port)) { reply_err(c, id, "bad proxy type or port"); return; }
+ if (edit) {
+ if (!ProxyBridge_EditProxy((uint32_t)pid, ARG(base), (ProxyType)type, ARG(base + 2), (uint16_t)port, ARG(base + 4), ARG(base + 5), err, sizeof err))
+ reply_err(c, id, err[0] ? err : "unknown proxy");
+ else reply_u64(c, id, pid);
+ } else {
+ uint32_t nid = ProxyBridge_AddProxy(ARG(base), (ProxyType)type, ARG(base + 2), (uint16_t)port, ARG(base + 4), ARG(base + 5), err, sizeof err);
+ if (!nid) reply_err(c, id, err[0] ? err : "proxy rejected"); else reply_u64(c, id, nid);
+ }
+ } else if (!strcmp(cmd, "proxy.sendDomain")) {
+ NEED(2);
+ if (!pu(ARG(0), 0xffffffffu, &a) || !bool_arg(ARG(1), &on)) { reply_err(c, id, "bad arguments"); return; }
+ if (ProxyBridge_SetProxySendDomain((uint32_t)a, on)) reply_ok(c, id); else reply_err(c, id, "unknown proxy");
+ } else if (!strcmp(cmd, "proxy.delete")) {
+ NEED(1);
+ if (!pu(ARG(0), 0xffffffffu, &a)) { reply_err(c, id, "bad proxy id"); return; }
+ if (ProxyBridge_DeleteProxy((uint32_t)a)) reply_ok(c, id); else reply_err(c, id, "unknown proxy");
+ } else if (!strcmp(cmd, "proxy.clear")) {
+ NEED(0);
+ ProxyBridge_ClearProxies();
+ reply_ok(c, id);
+ } else if (!strcmp(cmd, "proxy.default")) {
+ NEED(1);
+ if (!pu(ARG(0), 0xffffffffu, &a)) { reply_err(c, id, "bad proxy id"); return; }
+ ProxyBridge_SetDefaultProxy((uint32_t)a);
+ reply_ok(c, id);
+ } 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; }
+ struct test_ctx t = { c, id };
+ int rc = ProxyBridge_TestProxyEx((uint32_t)a, ARG(1), (uint16_t)b, test_line, &t);
+ char r[16];
+ snprintf(r, sizeof r, "%d", rc);
+ reply_ok1(c, id, r);
+ }
+ // ---- rules
+ else if (!strcmp(cmd, "rule.add") || !strcmp(cmd, "rule.edit")) {
+ bool edit = cmd[5] == 'e';
+ unsigned base = edit ? 1 : 0;
+ NEED(6 + base);
+ uint64_t rid = 0, proto, action, pid;
+ if (edit && !pu(ARG(0), 0xffffffffu, &rid)) { reply_err(c, id, "bad rule id"); return; }
+ if (!pu(ARG(base + 3), 2, &proto) || !pu(ARG(base + 4), 2, &action) || !pu(ARG(base + 5), 0xffffffffu, &pid)) { reply_err(c, id, "bad protocol, action or proxy"); return; }
+ if (edit) {
+ if (!ProxyBridge_EditRule((uint32_t)rid, ARG(base), ARG(base + 1), ARG(base + 2), (RuleProtocol)proto, (RuleAction)action, (uint32_t)pid, err, sizeof err))
+ reply_err(c, id, err[0] ? err : "unknown rule");
+ else reply_u64(c, id, rid);
+ } else {
+ uint32_t nid = ProxyBridge_AddRule(ARG(base), ARG(base + 1), ARG(base + 2), (RuleProtocol)proto, (RuleAction)action, (uint32_t)pid, err, sizeof err);
+ if (!nid) reply_err(c, id, err[0] ? err : "rule rejected"); else reply_u64(c, id, nid);
+ }
+ } else if (!strcmp(cmd, "rule.validate")) {
+ NEED(3);
+ if (ProxyBridge_ValidateRule(ARG(0), ARG(1), ARG(2), err, sizeof err)) reply_ok(c, id);
+ else reply_err(c, id, err[0] ? err : "invalid rule");
+ } else if (!strcmp(cmd, "rule.localhost")) {
+ NEED(2);
+ if (!pu(ARG(0), 0xffffffffu, &a) || !bool_arg(ARG(1), &on)) { reply_err(c, id, "bad arguments"); return; }
+ if (ProxyBridge_SetRuleLocalhost((uint32_t)a, on)) reply_ok(c, id); else reply_err(c, id, "unknown rule");
+ } else if (!strcmp(cmd, "rule.enable") || !strcmp(cmd, "rule.disable")) {
+ NEED(1);
+ if (!pu(ARG(0), 0xffffffffu, &a)) { reply_err(c, id, "bad rule id"); return; }
+ bool ok = cmd[5] == 'e' ? ProxyBridge_EnableRule((uint32_t)a) : ProxyBridge_DisableRule((uint32_t)a);
+ if (ok) reply_ok(c, id); else reply_err(c, id, "unknown rule");
+ } else if (!strcmp(cmd, "rule.delete")) {
+ NEED(1);
+ if (!pu(ARG(0), 0xffffffffu, &a)) { reply_err(c, id, "bad rule id"); return; }
+ if (ProxyBridge_DeleteRule((uint32_t)a)) reply_ok(c, id); else reply_err(c, id, "unknown rule");
+ } else if (!strcmp(cmd, "rule.move")) {
+ NEED(2);
+ if (!pu(ARG(0), 0xffffffffu, &a) || !pu(ARG(1), 100000, &b)) { reply_err(c, id, "bad arguments"); return; }
+ if (ProxyBridge_MoveRule((uint32_t)a, (int)b)) reply_ok(c, id); else reply_err(c, id, "unknown rule");
+ } else if (!strcmp(cmd, "rule.clear")) {
+ NEED(0);
+ ProxyBridge_ClearRules();
+ reply_ok(c, id);
+ }
+ // ---- runtime switches
+ else if (!strcmp(cmd, "batch.begin")) {
+ NEED(0);
+ ProxyBridge_BeginBatch();
+ c->batch_depth++;
+ reply_ok(c, id);
+ } else if (!strcmp(cmd, "batch.end")) {
+ NEED(0);
+ if (c->batch_depth > 0) { c->batch_depth--; ProxyBridge_EndBatch(); }
+ reply_ok(c, id);
+ } else if (!strcmp(cmd, "cfg.dns") || !strcmp(cmd, "cfg.logEvery") || !strcmp(cmd, "cfg.logging") || !strcmp(cmd, "cfg.enabled")) {
+ NEED(1);
+ if (!bool_arg(ARG(0), &on)) { reply_err(c, id, "bad value"); return; }
+ if (!strcmp(cmd, "cfg.dns")) ProxyBridge_SetDnsViaProxy(on);
+ else if (!strcmp(cmd, "cfg.logEvery")) ProxyBridge_SetLogEveryConnection(on);
+ else if (!strcmp(cmd, "cfg.logging")) { pthread_mutex_lock(&state_mu); logging_requested = on; pthread_mutex_unlock(&state_mu); update_logging(); }
+ else { pthread_mutex_lock(&state_mu); engine_enabled = on; pthread_mutex_unlock(&state_mu); ProxyBridge_SetEnabled(on); }
+ reply_ok(c, id);
+ } else if (!strcmp(cmd, "cfg.clearLogs")) {
+ NEED(0);
+ ProxyBridge_ClearConnectionLogs();
+ reply_ok(c, id);
+ } else if (!strcmp(cmd, "engine.start")) {
+ NEED(0);
+ if (engine_start()) reply_ok(c, id); else reply_err(c, id, "the engine could not start; see the Activity Logs");
+ } else if (!strcmp(cmd, "engine.stop")) {
+ NEED(0);
+ engine_stop();
+ reply_ok(c, id);
+ } else if (!strcmp(cmd, "flows.get")) {
+ NEED(0);
+ ProxyBridgeFlow *fl = calloc(PB_FLOWS_MAX, sizeof *fl);
+ if (!fl) { reply_err(c, id, "out of memory"); return; }
+ uint32_t n = ProxyBridge_GetFlows(fl, PB_FLOWS_MAX);
+ const char **f = calloc(n + 3, sizeof *f);
+ char **lines = calloc(n + 1, sizeof *lines);
+ if (f && lines) {
+ f[0] = "r"; f[1] = id; f[2] = "ok";
+ for (uint32_t i = 0; i < n; i++) {
+ char name[48], host[80];
+ snprintf(name, sizeof name, "%s", fl[i].name);
+ snprintf(host, sizeof host, "%s", fl[i].host);
+ for (char *p = name; *p; p++) if ((unsigned char)*p < 0x20 || *p == 0x7f) *p = '?';
+ for (char *p = host; *p; p++) if ((unsigned char)*p < 0x20 || *p == 0x7f) *p = '?';
+ // id, pid, proxy, age_ms, sent, received, port, udp, ipv6, dest(16 bytes, hex), name, host - tab separated
+ char hex[40];
+ for (int k = 0; k < 16; k++) snprintf(hex + 2 * k, 3, "%02x", fl[i].dest[k]);
+ if (asprintf(&lines[i], "%llu\t%u\t%u\t%u\t%llu\t%llu\t%u\t%u\t%u\t%s\t%s\t%s", (unsigned long long)fl[i].id, fl[i].pid, fl[i].proxy_id, fl[i].age_ms,
+ (unsigned long long)fl[i].sent, (unsigned long long)fl[i].received, fl[i].port, fl[i].is_udp, fl[i].is_ipv6, hex, name, host) < 0)
+ lines[i] = strdup("");
+ f[3 + i] = lines[i];
+ }
+ send_to(c, false, n + 3, f);
+ } else reply_err(c, id, "out of memory");
+ if (lines) for (uint32_t i = 0; i < n; i++) free(lines[i]);
+ free(lines); free(f); free(fl);
+ }
+ // ---- store
+ else if (!strcmp(cmd, "store.list")) {
+ NEED(0);
+ store_list(c, id);
+ } else if (!strcmp(cmd, "store.get")) {
+ NEED(1);
+ store_get(c, id, ARG(0));
+ } else if (!strcmp(cmd, "store.put")) {
+ NEED(2);
+ store_put(c, id, ARG(0), ARG(1), m->len[3 + 1]);
+ } else if (!strcmp(cmd, "store.delete")) {
+ NEED(1);
+ store_delete(c, id, ARG(0));
+ } else if (!strcmp(cmd, "store.settings.get")) {
+ NEED(0);
+ char *active = NULL;
+ bool updates = true, boot = false;
+ if (read_settings(&active, &updates, &boot) != 0) { free(active); active = NULL; updates = true; boot = false; }
+ const char *x[] = { active ? active : "", updates ? "1" : "0", boot ? "1" : "0" };
+ reply(c, id, "ok", 3, x);
+ free(active);
+ } else if (!strcmp(cmd, "store.settings.set")) {
+ NEED(3);
+ bool updates, boot;
+ if (!bool_arg(ARG(1), &updates) || !bool_arg(ARG(2), &boot)) { reply_err(c, id, "bad value"); 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
+ else if (!strcmp(cmd, "boot.get")) {
+ NEED(0);
+ bool updates = true, boot = false;
+ char *active = NULL;
+ if (read_settings(&active, &updates, &boot) != 0) boot = false;
+ free(active);
+ reply_ok1(c, id, boot ? "1" : "0");
+ } else if (!strcmp(cmd, "boot.set")) {
+ NEED(1);
+ if (!bool_arg(ARG(0), &on)) { reply_err(c, id, "bad value"); return; }
+ bool updates = true, boot = false;
+ char *active = NULL;
+ read_settings(&active, &updates, &boot);
+ int rc = write_settings(active ? active : "", updates, on, err, sizeof err);
+ free(active);
+ if (rc != 0) reply_err(c, id, err); else reply_ok(c, id);
+ } else {
+ reply_err(c, id, "unknown command");
+ }
+}
+
+static void *reader_main(void *arg)
+{
+ struct client *c = arg;
+ for (;;) {
+ pb_msg m;
+ int rc = pb_ipc_recv(c->fd, &m);
+ if (rc != 0) break;
+ handle(c, &m);
+ pb_msg_free(&m);
+ }
+ // a client that vanished in the middle of a batch must not leave the kernel update held back
+ while (c->batch_depth > 0) { c->batch_depth--; ProxyBridge_EndBatch(); }
+ pthread_mutex_lock(&clients_mu);
+ for (struct client **pp = &clients; *pp; pp = &(*pp)->next)
+ if (*pp == c) { *pp = c->next; break; }
+ nclients--;
+ pthread_mutex_unlock(&clients_mu);
+ pthread_mutex_lock(&c->mu);
+ c->closing = true;
+ pthread_cond_signal(&c->cv);
+ pthread_mutex_unlock(&c->mu);
+ shutdown(c->fd, SHUT_RDWR);
+ update_logging();
+ if (atomic_fetch_sub(&c->refs, 1) == 1) {
+ for (struct outmsg *m = c->head; m;) { struct outmsg *n = m->next; free(m->frame); free(m); m = n; }
+ close(c->fd);
+ pthread_mutex_destroy(&c->mu);
+ pthread_cond_destroy(&c->cv);
+ free(c);
+ }
+ return NULL;
+}
+
+// ---- 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.
+static bool uid_allowed(uid_t uid)
+{
+ if (uid == 0) return true;
+ struct group *g = getgrnam(GROUP_NAME);
+ if (!g) return false;
+ struct passwd *pw = getpwuid(uid);
+ if (!pw) return false;
+ if (pw->pw_gid == g->gr_gid) return true;
+ for (char **mem = g->gr_mem; mem && *mem; mem++)
+ if (strcmp(*mem, pw->pw_name) == 0) return true;
+ return false;
+}
+
+static int open_listener(const char *path)
+{
+ struct sockaddr_un a = { .sun_family = AF_UNIX };
+ if (strlen(path) >= sizeof a.sun_path) { errno = ENAMETOOLONG; return -1; }
+ strcpy(a.sun_path, path);
+
+ char dir[sizeof a.sun_path];
+ snprintf(dir, sizeof dir, "%s", path);
+ char *slash = strrchr(dir, '/');
+ if (slash && slash != dir) {
+ *slash = '\0';
+ if (mkdir(dir, 0755) == 0) chmod(dir, 0755); // only a folder created here is ours to set up
+ else if (errno != EEXIST) return -1;
+ }
+ int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
+ if (fd < 0) return -1;
+ unlink(path); // a stale socket of a previous run
+ mode_t old = umask(0); // everyone may connect; who may talk is decided by uid_allowed()
+ int rc = bind(fd, (struct sockaddr *)&a, sizeof a);
+ umask(old);
+ if (rc == 0) chmod(path, 0666);
+ if (rc != 0 || listen(fd, 128) != 0) { close(fd); return -1; }
+ return fd;
+}
+
+int pb_daemon_run(const char *socket_path, int verbose_level)
+{
+ verbose = verbose_level;
+ if (getuid() != 0) {
+ fprintf(stderr, "ERROR: the ProxyBridge service must run as root.\n");
+ return 1;
+ }
+ // Signals are read from a descriptor by this thread only: blocked here, so every thread started later inherits that, and
+ // the service does not wake up on a timer just to look at a flag.
+ sigset_t sigs;
+ sigemptyset(&sigs);
+ sigaddset(&sigs, SIGTERM);
+ sigaddset(&sigs, SIGINT);
+ sigaddset(&sigs, SIGPIPE);
+ pthread_sigmask(SIG_BLOCK, &sigs, NULL);
+ int sfd = signalfd(-1, &sigs, SFD_CLOEXEC);
+ if (sfd < 0) { fprintf(stderr, "ERROR: cannot watch for signals: %s\n", strerror(errno)); return 1; }
+
+ setvbuf(stdout, NULL, _IOLBF, 0);
+ ProxyBridge_SetLogCallback(on_log);
+ ProxyBridge_SetConnectionCallbackEx(on_conn);
+ ProxyBridge_SetTrafficLoggingEnabled(verbose == 2 || verbose == 3);
+
+ 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; }
+ 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
+ // until a window connects and asks for the engine; closing that window switches routing off again.
+ bool at_boot = false, updates = true;
+ char *active = NULL;
+ if (read_settings(&active, &updates, &at_boot) != 0) at_boot = false;
+ free(active);
+ if (at_boot) {
+ apply_active_profile();
+ if (!engine_start()) dlog("the engine could not start; see the lines above (needs a kernel >= 5.11 with BTF and cgroup v2)");
+ } else {
+ dlog("Start at Boot is off: waiting for a window");
+ }
+
+ bool stop = false;
+ while (!stop) {
+ struct pollfd p[2] = { { .fd = lfd, .events = POLLIN }, { .fd = sfd, .events = POLLIN } };
+ int r = poll(p, 2, -1);
+ if (r < 0 && errno == EINTR) continue;
+ if (r <= 0) continue;
+ if (p[1].revents & POLLIN) {
+ struct signalfd_siginfo si;
+ if (read(sfd, &si, sizeof si) == (ssize_t)sizeof si && (si.ssi_signo == SIGTERM || si.ssi_signo == SIGINT)) { stop = true; break; }
+ }
+ if (!(p[0].revents & POLLIN)) continue;
+ int fd;
+ while ((fd = accept4(lfd, NULL, NULL, SOCK_CLOEXEC)) >= 0) { // everything that is waiting, not one per wake-up
+ struct ucred cred;
+ 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);
+ 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;
+ }
+ pthread_mutex_lock(&clients_mu);
+ bool full = nclients >= MAX_CLIENTS;
+ pthread_mutex_unlock(&clients_mu);
+ struct client *c = full ? NULL : calloc(1, sizeof *c);
+ if (!c) {
+ pb_ipc_sendv(fd, "r", "0", "err", "too many windows are connected", (char *)NULL);
+ close(fd);
+ continue;
+ }
+ c->fd = fd;
+ c->uid = cred.uid;
+ pthread_mutex_init(&c->mu, NULL);
+ pthread_cond_init(&c->cv, NULL);
+ atomic_init(&c->refs, 2);
+ pthread_mutex_lock(&clients_mu);
+ c->next = clients;
+ clients = c;
+ nclients++;
+ pthread_mutex_unlock(&clients_mu);
+ pthread_t rt, wt;
+ pthread_attr_t at;
+ pthread_attr_init(&at);
+ pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED);
+ if (pthread_create(&wt, &at, writer_main, c) != 0) {
+ pthread_mutex_lock(&clients_mu);
+ for (struct client **pp = &clients; *pp; pp = &(*pp)->next) if (*pp == c) { *pp = c->next; break; }
+ nclients--;
+ pthread_mutex_unlock(&clients_mu);
+ close(fd); free(c); pthread_attr_destroy(&at);
+ continue;
+ }
+ if (pthread_create(&rt, &at, reader_main, c) != 0) {
+ pthread_mutex_lock(&c->mu);
+ c->closing = true;
+ pthread_cond_signal(&c->cv);
+ pthread_mutex_unlock(&c->mu);
+ shutdown(fd, SHUT_RDWR);
+ pthread_mutex_lock(&clients_mu);
+ for (struct client **pp = &clients; *pp; pp = &(*pp)->next) if (*pp == c) { *pp = c->next; break; }
+ nclients--;
+ pthread_mutex_unlock(&clients_mu);
+ atomic_fetch_sub(&c->refs, 1); // the reader thread that never started
+ }
+ pthread_attr_destroy(&at);
+ }
+ }
+
+ dlog("stopping");
+ close(lfd);
+ unlink(socket_path);
+ engine_stop();
+ return 0;
+}
diff --git a/Linux/cli/daemon.h b/Linux/cli/daemon.h
new file mode 100644
index 0000000..89a9500
--- /dev/null
+++ b/Linux/cli/daemon.h
@@ -0,0 +1,10 @@
+// "ProxyBridge --daemon": the root part of ProxyBridge. It owns the engine and the profile files and serves the GUI (and anything
+// else that speaks pb_ipc) over a Unix socket, so the window itself does not need root.
+#ifndef PB_DAEMON_H
+#define PB_DAEMON_H
+
+// Runs until SIGTERM/SIGINT. socket_path: where to listen (PB_IPC_SOCKET_PATH by default). verbose: as --verbose of the CLI.
+// Returns the process exit status.
+int pb_daemon_run(const char *socket_path, int verbose);
+
+#endif
diff --git a/Linux/cli/main.c b/Linux/cli/main.c
index 2b64ec5..f88dc25 100644
--- a/Linux/cli/main.c
+++ b/Linux/cli/main.c
@@ -9,6 +9,9 @@
#include <sys/auxv.h>
#include "../src/ProxyBridge.h"
#include "../profile/pb_profile.h"
+#include "../src/pb_ipc.h"
+#include "daemon.h"
+#include "../src/pb_unit.h"
#define UPDATE_FEED "https://download.interceptsuite.com/proxybridge.json"
@@ -61,6 +64,10 @@ static void show_help(void)
printf(" 1 - Log messages only\n");
printf(" 2 - Connection events only\n");
printf(" 3 - Both logs and connections\n\n");
+ printf(" --daemon Run as the ProxyBridge service: owns the engine and the profiles, and lets the\n");
+ printf(" window (which then needs no root) control it. Used by proxybridge.service\n");
+ printf(" --print-unit <path> Print the systemd unit that runs <path> --daemon (used by the installer)\n");
+ printf(" --socket <path> With --daemon: the control socket (default %s)\n\n", PB_IPC_SOCKET_PATH);
printf(" --version Show version information\n");
printf(" -?, -h, --help Show help\n\n");
printf("Commands:\n");
@@ -152,6 +159,8 @@ static bool is_root(void)
int main(int argc, char *argv[])
{
const char* profile_arg = NULL;
+ bool daemon_mode = false;
+ const char* socket_arg = PB_IPC_SOCKET_PATH;
for (int i = 1; i < argc; i++)
{
@@ -169,6 +178,27 @@ int main(int argc, char *argv[])
{
return check_update();
}
+ else if (strcmp(argv[i], "--daemon") == 0)
+ {
+ daemon_mode = true;
+ }
+ else if (strcmp(argv[i], "--print-unit") == 0 && i + 1 < argc)
+ {
+ const char* why = NULL;
+ char* text = pb_unit_text(argv[++i], &why);
+ if (!text)
+ {
+ fprintf(stderr, "ERROR: %s\n", why ? why : "cannot build the unit");
+ return 1;
+ }
+ fputs(text, stdout);
+ free(text);
+ return 0;
+ }
+ else if (strcmp(argv[i], "--socket") == 0 && i + 1 < argc)
+ {
+ socket_arg = argv[++i];
+ }
else if (strcmp(argv[i], "--profile") == 0 && i + 1 < argc)
{
profile_arg = argv[++i];
@@ -191,6 +221,16 @@ int main(int argc, char *argv[])
}
}
+ if (daemon_mode)
+ {
+ if (profile_arg)
+ {
+ fprintf(stderr, "ERROR: --daemon runs the profile the window made active; it does not take --profile.\n");
+ return 1;
+ }
+ return pb_daemon_run(socket_arg, verbose_level);
+ }
+
if (!profile_arg)
{
fprintf(stderr, "ERROR: No profile specified.\n");
diff --git a/Linux/gui/Makefile b/Linux/gui/Makefile
index 0d49055..68f43d2 100644
--- a/Linux/gui/Makefile
+++ b/Linux/gui/Makefile
@@ -13,7 +13,7 @@ LDFLAGS = -pie $(HARDEN_LDFLAGS) -L$(LIBDIR) -Wl,-rpath,'$$ORIGIN' -export-dynam
LIBS = -lproxybridge -lpthread $(GTK_LIBS)
SOURCES = $(filter-out tests/%,$(wildcard *.c))
-OBJECTS = $(addprefix $(BUILD_DIR)/,$(SOURCES:.c=.o)) $(BUILD_DIR)/pb_profile.o
+OBJECTS = $(addprefix $(BUILD_DIR)/,$(SOURCES:.c=.o)) $(BUILD_DIR)/pb_profile.o $(BUILD_DIR)/pb_ipc.o $(BUILD_DIR)/pb_unit.o
TARGET = $(BUILD_DIR)/ProxyBridgeGUI
all: $(TARGET)
@@ -30,6 +30,12 @@ $(BUILD_DIR)/%.o: %.c gui.h | $(BUILD_DIR)
$(BUILD_DIR)/pb_profile.o: ../profile/pb_profile.c ../profile/pb_profile.h | $(BUILD_DIR)
$(CC) $(CFLAGS) -c $< -o $@
+$(BUILD_DIR)/pb_ipc.o: ../src/pb_ipc.c ../src/pb_ipc.h | $(BUILD_DIR)
+ $(CC) $(CFLAGS) -c $< -o $@
+
+$(BUILD_DIR)/pb_unit.o: ../src/pb_unit.c ../src/pb_unit.h | $(BUILD_DIR)
+ $(CC) $(CFLAGS) -c $< -o $@
+
clean:
rm -f $(OBJECTS) $(TARGET)
diff --git a/Linux/gui/gui.h b/Linux/gui/gui.h
index f4adedb..145a121 100644
--- a/Linux/gui/gui.h
+++ b/Linux/gui/gui.h
@@ -51,6 +51,20 @@ typedef struct {
char *saved; // what is on disk, to skip rewriting unchanged profiles
} Profile;
+// Where profiles and settings.json are kept: files (a window with its own engine, running as root) or the ProxyBridge service.
+struct gui_store {
+ bool (*list)(GPtrArray *names); // appends g_strdup'd profile names
+ char *(*get)(const char *name); // g_malloc'd file content, or NULL
+ bool (*put)(const char *name, const char *data, char *err, size_t errn);
+ bool (*del)(const char *name);
+ bool (*exists)(const char *name);
+ bool (*settings_get)(char **active, bool *check_updates, bool *start_at_boot); // *active g_malloc'd or NULL
+ bool (*settings_set)(const char *active, bool check_updates, bool start_at_boot, char *err, size_t errn);
+};
+extern const struct gui_store gui_store_files;
+extern const struct gui_store pbc_store; // pb_client.c
+void gui_store_use(const struct gui_store *s);
+
typedef void (*RuleImportCb)(const RuleData *rule, int index, void *ud);
extern GtkWidget *window;
@@ -74,6 +88,7 @@ extern bool g_chk_dns;
extern bool g_chk_log_every;
extern bool g_chk_auto_clear;
extern int g_zoom;
+extern bool g_chk_boot; // Start at Boot (settings.json): the service keeps routing after the window closes, and applies the profile at boot
extern bool g_chk_updates; // check for a new version when the program starts (settings.json, not per profile)
void show_message(GtkWindow *parent, GtkMessageType type, const char *format, ...);
@@ -149,4 +164,6 @@ void on_clear_log_clicked(GtkButton *button, gpointer user_data);
// Path of the stored profile file for a profile name (g_malloc'd), or NULL for an unusable name.
char *profile_path(const char *name);
+#include "pb_client.h"
+
#endif
diff --git a/Linux/gui/gui_boot.c b/Linux/gui/gui_boot.c
index 77fa917..1284c02 100644
--- a/Linux/gui/gui_boot.c
+++ b/Linux/gui/gui_boot.c
@@ -1,4 +1,5 @@
#include "gui_boot.h"
+#include "pb_unit.h"
#include <fcntl.h>
#include <glib/gstdio.h>
#include <string.h>
@@ -77,43 +78,16 @@ static char *cli_path(char **error) {
return cli;
}
-// systemd's own quoting for one ExecStart word: backslash, double quote, % (specifier) and $ (variable) are escaped
-static void quote_word(GString *out, const char *s) {
- g_string_append_c(out, '"');
- for (; *s; s++) {
- if (*s == '\\' || *s == '"') g_string_append_c(out, '\\');
- else if (*s == '%') g_string_append_c(out, '%');
- else if (*s == '$') g_string_append_c(out, '$');
- g_string_append_c(out, *s);
- }
- g_string_append_c(out, '"');
-}
-
-char *boot_unit_text(const char *cli, const char *profile, char **error) {
- if (profile[0] != '/') { // the stored file, never a name: a name is resolved relative to the service's cwd
- if (error) *error = g_strdup("the profile must be given as an absolute path");
+char *boot_unit_text(const char *cli, char **error) {
+ const char *why = NULL;
+ char *text = pb_unit_text(cli, &why);
+ if (!text) {
+ if (error) *error = g_strdup(why ? why : "cannot build the unit");
return NULL;
}
- for (const char *p = profile; *p; p++)
- if ((unsigned char)*p < 0x20 || *p == 0x7f) {
- if (error) *error = g_strdup("the profile name contains control characters and cannot be used in a service file");
- return NULL;
- }
- for (const char *p = cli; *p; p++)
- if ((unsigned char)*p < 0x20 || *p == 0x7f) {
- if (error) *error = g_strdup("the program path contains control characters");
- return NULL;
- }
- GString *s = g_string_new("[Unit]\nDescription=ProxyBridge\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nExecStart=");
- quote_word(s, cli);
- g_string_append(s, " --profile ");
- quote_word(s, profile);
- g_string_append(s, "\nRestart=on-failure\nRestartSec=5\n"
- // the engine needs root for eBPF and /proc, nothing else: no new privileges, no writable system or home directories
- "LimitNOFILE=1048576\nNoNewPrivileges=yes\nProtectSystem=strict\nProtectHome=read-only\nPrivateTmp=yes\nProtectKernelModules=yes\n"
- "ProtectKernelLogs=yes\nProtectClock=yes\nRestrictSUIDSGID=yes\nLockPersonality=yes\nRestrictRealtime=yes\n"
- "\n[Install]\nWantedBy=multi-user.target\n");
- return g_string_free(s, FALSE);
+ char *out = g_strdup(text);
+ free(text);
+ return out;
}
bool boot_is_enabled(void) {
@@ -142,10 +116,10 @@ static bool run_systemctl(const char *a, const char *b, char **error) {
return ok;
}
-static bool write_unit(const char *profile, char **error) {
+static bool write_unit(char **error) {
char *cli = cli_path(error);
if (!cli) return false;
- char *text = boot_unit_text(cli, profile, error);
+ char *text = boot_unit_text(cli, error);
g_free(cli);
if (!text) return false;
char *path = unit_path(), *tmp = g_strdup_printf("%s.tmp", path);
@@ -166,10 +140,10 @@ static bool write_unit(const char *profile, char **error) {
return ok;
}
-bool boot_set(bool enable, const char *profile, char **error) {
+bool boot_set(bool enable, char **error) {
if (error) *error = NULL;
if (enable) {
- if (!write_unit(profile, error)) return false;
+ if (!write_unit(error)) return false;
if (!run_systemctl("daemon-reload", NULL, error) || !run_systemctl("enable", UNIT_NAME, error)) {
char *path = unit_path();
g_unlink(path); // do not leave a unit behind that is not enabled
@@ -189,9 +163,3 @@ bool boot_set(bool enable, const char *profile, char **error) {
g_free(path);
return ok;
}
-
-bool boot_refresh(const char *profile, char **error) {
- if (error) *error = NULL;
- if (!boot_is_enabled()) return true;
- return write_unit(profile, error) && run_systemctl("daemon-reload", NULL, error);
-}
diff --git a/Linux/gui/gui_boot.h b/Linux/gui/gui_boot.h
index 973fade..eb4d57a 100644
--- a/Linux/gui/gui_boot.h
+++ b/Linux/gui/gui_boot.h
@@ -1,22 +1,20 @@
-// "Start at boot": a systemd service that runs the command line program with the active profile.
+// "Start at boot" when the window itself runs as root: installs proxybridge.service, which runs "ProxyBridge --daemon". The service
+// starts the profile that was active when the window last saved its settings.
#ifndef PROXYBRIDGE_GUI_BOOT_H
#define PROXYBRIDGE_GUI_BOOT_H
#include <glib.h>
#include <stdbool.h>
-// Text of the unit file. profile_path is the stored profile file (absolute). NULL (with *error set) if a value cannot be
-// written safely (control characters, relative path).
-char *boot_unit_text(const char *cli_path, const char *profile_path, char **error);
+// Text of the unit file (see src/pb_unit.h). NULL (with *error set) if the program path cannot be written safely.
+char *boot_unit_text(const char *cli_path, char **error);
// True when path (a file) and every directory above it belong to root and are writable by root only.
bool boot_path_trusted(const char *path, char **why);
// True when the unit file exists.
bool boot_is_enabled(void);
// Writes the unit and enables it, or disables it and removes the file. On failure returns false with a message in *error
// (g_malloc'd). The program the unit starts is the ProxyBridge next to this program, or /usr/local/bin/ProxyBridge; it must
-// pass boot_path_trusted(). profile is the absolute path of the profile file.
-bool boot_set(bool enable, const char *profile, char **error);
-// Rewrites the unit for another active profile if it is enabled.
-bool boot_refresh(const char *profile, char **error);
+// pass boot_path_trusted().
+bool boot_set(bool enable, char **error);
#endif
diff --git a/Linux/gui/gui_config.c b/Linux/gui/gui_config.c
index 82114cf..467d95f 100644
--- a/Linux/gui/gui_config.c
+++ b/Linux/gui/gui_config.c
@@ -5,8 +5,13 @@
#include "pb_profile.h"
GList *g_profiles = NULL;
+bool g_chk_boot = false;
char *g_active_profile = NULL;
+static const char *config_dir_path() {
+ return pbp_config_dir();
+}
+
static char *config_dir() {
return g_strdup(pbp_config_dir());
}
@@ -21,11 +26,84 @@ char *profile_path(const char *name) {
return path;
}
-// the file of a deleted or renamed profile must go, or it would come back at the next start
-static void remove_profile_file(const char *name) {
+// ---- where profiles live ---------------------------------------------------------------------------------------------------
+// The window reads and writes profiles through a small interface: files under /etc/proxybridge when it runs as root with its own
+// engine, or the ProxyBridge service (pb_client.c) when it does not have root. The model and the .pbprofile code are the same.
+static bool ensure_private_dir(const char *dir);
+
+static bool file_list(GPtrArray *names) {
+ char *pdir = g_strdup_printf("%s/profiles", config_dir_path());
+ DIR *d = opendir(pdir);
+ struct dirent *de;
+ while (d && (de = readdir(d)) != NULL) {
+ if (strlen(de->d_name) <= strlen(PBP_EXT)) continue;
+ char *name = pbp_name_from_filename(de->d_name);
+ if (name) { g_ptr_array_add(names, g_strdup(name)); free(name); }
+ }
+ if (d) closedir(d);
+ g_free(pdir);
+ return true;
+}
+
+static char *file_get(const char *name) {
+ char *path = profile_path(name);
+ if (!path) return NULL;
+ chmod(path, 0600);
+ char *data = NULL;
+ gsize len = 0;
+ if (!g_file_get_contents(path, &data, &len, NULL) || len > PBP_MAX_FILE) { g_free(data); data = NULL; }
+ g_free(path);
+ return data;
+}
+
+static bool file_put(const char *name, const char *data, char *err, size_t en) {
+ char *dir = g_strdup(config_dir_path());
+ char *pdir = g_strdup_printf("%s/profiles", dir);
+ char *path = profile_path(name);
+ bool ok = false;
+ if (!path) snprintf(err, en, "the name is too long to be stored");
+ else if (!ensure_private_dir(dir) || !ensure_private_dir(pdir)) snprintf(err, en, "cannot create %s", pdir);
+ else ok = pbp_write_file(path, data, err, en) == 0;
+ g_free(path); g_free(pdir); g_free(dir);
+ return ok;
+}
+
+static bool file_del(const char *name) {
char *path = profile_path(name);
if (path) unlink(path);
g_free(path);
+ return true;
+}
+
+static bool file_exists(const char *name) {
+ char *path = profile_path(name);
+ bool yes = path && access(path, F_OK) == 0;
+ g_free(path);
+ return yes;
+}
+
+static bool file_settings_get(char **active, bool *updates, bool *boot) {
+ char *p = g_strdup_printf("%s/settings.json", config_dir_path());
+ bool ok = pbp_settings_load(p, active, updates, boot) == 0;
+ g_free(p);
+ return ok;
+}
+
+static bool file_settings_set(const char *active, bool updates, bool boot, char *err, size_t en) {
+ char *dir = g_strdup(config_dir_path());
+ char *p = g_strdup_printf("%s/settings.json", dir);
+ bool ok = ensure_private_dir(dir) && pbp_settings_save(p, active, updates, boot, err, en) == 0;
+ g_free(p); g_free(dir);
+ return ok;
+}
+
+const struct gui_store gui_store_files = { file_list, file_get, file_put, file_del, file_exists, file_settings_get, file_settings_set };
+static const struct gui_store *g_store = &gui_store_files;
+void gui_store_use(const struct gui_store *s) { g_store = s ? s : &gui_store_files; }
+
+// the file of a deleted or renamed profile must go, or it would come back at the next start
+static void remove_profile_file(const char *name) {
+ g_store->del(name);
}
static char *unesc(const char *s) {
@@ -382,24 +460,15 @@ static bool ensure_private_dir(const char *dir) {
void save_config() {
profile_sync_active();
- char *dir = config_dir();
- char *pdir = g_strdup_printf("%s/profiles", dir);
- if (!ensure_private_dir(dir) || !ensure_private_dir(pdir)) goto out;
-
char err[256];
for (GList *l = g_profiles; l != NULL; l = l->next) {
Profile *prof = (Profile *)l->data;
- char *path = profile_path(prof->name);
- if (!path) {
- fprintf(stderr, "profile '%s': the name is too long to be stored\n", prof->name);
- continue;
- }
struct pbp_profile view;
profile_to_pbp(prof, &view);
char *json = pbp_serialize(&view);
free_pbp_view(&view);
- if (json && !(prof->saved && strcmp(prof->saved, json) == 0 && access(path, F_OK) == 0)) {
- if (pbp_write_file(path, json, err, sizeof err) == 0) {
+ if (json && !(prof->saved && strcmp(prof->saved, json) == 0 && g_store->exists(prof->name))) {
+ if (g_store->put(prof->name, json, err, sizeof err)) {
free(prof->saved);
prof->saved = json;
json = NULL;
@@ -408,15 +477,9 @@ void save_config() {
}
}
free(json);
- g_free(path);
}
- char *settings = g_strdup_printf("%s/settings.json", dir);
- if (pbp_settings_save(settings, g_active_profile, g_chk_updates, err, sizeof err) != 0)
+ if (!g_store->settings_set(g_active_profile, g_chk_updates, g_chk_boot, err, sizeof err))
fprintf(stderr, "failed to save settings: %s\n", err);
- g_free(settings);
-out:
- g_free(pdir);
- g_free(dir);
}
static ProxyType proxy_type_from_int(int v) {
@@ -585,38 +648,29 @@ static gint compare_names(gconstpointer a, gconstpointer b) {
return strcmp(*(char *const *)a, *(char *const *)b);
}
-// sorted by file name, so the order is the same on every start
-static void load_profile_files(const char *dir) {
- char *pdir = g_strdup_printf("%s/profiles", dir);
- GPtrArray *files = g_ptr_array_new_with_free_func(g_free);
- DIR *d = opendir(pdir);
- struct dirent *de;
- while (d && (de = readdir(d)) != NULL)
- if (strlen(de->d_name) > strlen(PBP_EXT)) g_ptr_array_add(files, g_strdup(de->d_name));
- if (d) closedir(d);
- g_ptr_array_sort(files, compare_names);
+// sorted by name, so the order is the same on every start
+static void load_profile_files() {
+ GPtrArray *names = g_ptr_array_new_with_free_func(g_free);
+ g_store->list(names);
+ g_ptr_array_sort(names, compare_names);
- for (guint i = 0; i < files->len; i++) {
- const char *file = g_ptr_array_index(files, i);
- char *name = pbp_name_from_filename(file);
- if (!name) continue;
- char *path = g_strdup_printf("%s/%s", pdir, file);
+ for (guint i = 0; i < names->len; i++) {
+ const char *name = g_ptr_array_index(names, i);
+ if (profile_find(name)) continue; // duplicate name after decoding: keep the first
+ char *data = g_store->get(name);
struct pbp_profile src;
char err[256];
- chmod(path, 0600);
- if (profile_find(name)) {
- /* duplicate name after decoding: keep the first */
- } else if (pbp_load_file(path, &src, err, sizeof err) == 0) {
+ if (!data) {
+ fprintf(stderr, "ignoring profile '%s': cannot be read\n", name);
+ } else if (pbp_parse(data, strlen(data), &src, err, sizeof err) == 0) {
fill_profile_from_pbp(profile_new_empty(name), &src);
pbp_free(&src);
} else {
fprintf(stderr, "ignoring profile '%s': %s\n", name, err);
}
- g_free(path);
- free(name);
+ g_free(data);
}
- g_ptr_array_free(files, TRUE);
- g_free(pdir);
+ g_ptr_array_free(names, TRUE);
}
// profiles/<name>.pbprofile + settings.json; a config.ini from an older version is converted on first start
@@ -625,11 +679,9 @@ void load_config() {
char *settings_active = NULL, *legacy_active = NULL;
bool migrate = false;
- load_profile_files(dir);
- char *settings = g_strdup_printf("%s/settings.json", dir);
- pbp_settings_load(settings, &settings_active, &g_chk_updates);
- g_free(settings);
- if (!g_profiles) {
+ load_profile_files();
+ g_store->settings_get(&settings_active, &g_chk_updates, &g_chk_boot);
+ if (!g_profiles && g_store == &gui_store_files) { // a config.ini of an older version only exists next to the files
migrate = load_legacy_ini(dir, &legacy_active);
for (GList *l = g_profiles; l != NULL; l = l->next) { // the old file had one pair of switches for all profiles
((Profile *)l->data)->logging = g_chk_logging;
diff --git a/Linux/gui/gui_settings.c b/Linux/gui/gui_settings.c
index dcea41f..738ec89 100644
--- a/Linux/gui/gui_settings.c
+++ b/Linux/gui/gui_settings.c
@@ -480,14 +480,6 @@ void on_proxy_configure(GtkWidget *widget, gpointer data) {
}
static void update_profile_ui() {
- char *boot_err = NULL;
- char *ppath = profile_path(g_active_profile);
- bool refreshed = ppath && boot_refresh(ppath, &boot_err); // the boot service runs the active profile
- g_free(ppath);
- if (!refreshed) {
- gui_log("could not update the boot service: %s", boot_err ? boot_err : "unknown error");
- g_free(boot_err);
- }
char *title = g_strdup_printf("ProxyBridge - %s", g_active_profile);
gtk_window_set_title(GTK_WINDOW(window), title);
g_free(title);
@@ -499,9 +491,11 @@ static void update_profile_ui() {
// engine keeps running, only its proxies and rules are replaced
static void reapply_active_profile() {
+ ProxyBridge_BeginBatch(); // the datapath sees the new profile all at once, never a half-built one
ProxyBridge_ClearRules();
apply_proxies_to_lib();
apply_rules_to_lib();
+ ProxyBridge_EndBatch();
gui_sync_switches();
save_config();
refresh_rules_window();
diff --git a/Linux/gui/main.c b/Linux/gui/main.c
index abc464f..bddb701 100644
--- a/Linux/gui/main.c
+++ b/Linux/gui/main.c
@@ -119,18 +119,21 @@ static void on_boot_toggled(GtkCheckMenuItem *item, gpointer data) {
if (boot_syncing) return;
bool want = gtk_check_menu_item_get_active(item);
char *err = NULL;
- char *ppath = profile_path(g_active_profile);
- bool set_ok = ppath && boot_set(want, ppath, &err);
- g_free(ppath);
- if (!set_ok) {
+ if (!pbc_boot_set(want, &err)) {
show_message(GTK_WINDOW(window), GTK_MESSAGE_ERROR, "Could not %s starting at boot: %s", want ? "enable" : "disable", err ? err : "unknown error");
g_free(err);
boot_syncing = true;
- gtk_check_menu_item_set_active(item, boot_is_enabled());
+ gtk_check_menu_item_set_active(item, pbc_boot_is_enabled());
boot_syncing = false;
return;
}
- gui_log("ProxyBridge %s at boot (service proxybridge.service, profile '%s')", want ? "will start" : "will no longer start", g_active_profile);
+ g_chk_boot = want;
+ save_config();
+ if (pbc_is_service())
+ gui_log(want ? "Start at Boot is on: the service applies profile '%s' when the machine starts and keeps routing after this window is closed" :
+ "Start at Boot is off: routing stops when this window is closed", g_active_profile);
+ else
+ gui_log("ProxyBridge %s at boot (service proxybridge.service, profile '%s')", want ? "will start" : "will no longer start", g_active_profile);
}
static void on_update_startup_toggled(GtkCheckMenuItem *item, gpointer data) {
@@ -352,7 +355,7 @@ static void on_about(GtkWidget *widget, gpointer data) {
"<span size='xx-large' weight='bold'>ProxyBridge</span>\n"
"<span color='gray'>Version %s</span>\n\n"
"Universal proxy client for Linux applications\n"
- "eBPF backend (needs root, kernel 5.11+ with BTF and cgroup v2)\n\n"
+ "eBPF backend, run by the ProxyBridge service (root);\nkernel 5.11+ with BTF and cgroup v2\n\n"
"Author: Sourav Kalal / InterceptSuite\n\n"
"Website: <a href=\"https://interceptsuite.com\">interceptsuite.com</a>\n"
"GitHub: <a href=\"https://github.com/InterceptSuite/ProxyBridge\">InterceptSuite/ProxyBridge</a>\n\n"
@@ -465,8 +468,11 @@ static void shutdown_engine() {
engine_thread = NULL;
engine_state = engine_job.start && engine_job.ok ? ENGINE_RUNNING : ENGINE_STOPPED;
}
- if (engine_state == ENGINE_RUNNING) ProxyBridge_Stop();
+ // With the service the engine belongs to the service: closing the window must not switch routing off
+ // Start at Boot keeps the service routing after the window closes; without it routing ends with the window, as it always did
+ if (engine_state == ENGINE_RUNNING && (!pbc_is_service() || !g_chk_boot)) ProxyBridge_Stop();
engine_state = ENGINE_STOPPED;
+ pbc_disconnect();
}
static GtkWidget *add_menu_item(GtkWidget *menu, const char *label, GCallback cb) {
@@ -589,13 +595,53 @@ static GtkWidget *add_flows_tab(GtkWidget *notebook) {
return flows_page;
}
+// The service went away (restarted, updated, stopped). Try again every two seconds and send the window's configuration once it is back.
+static guint reconnect_source;
+
+static gboolean reconnect_tick(gpointer data) {
+ if (!pbc_reconnect()) return G_SOURCE_CONTINUE;
+ reconnect_source = 0;
+ pbc_BeginBatch();
+ ProxyBridge_ClearRules();
+ apply_proxies_to_lib();
+ apply_rules_to_lib();
+ pbc_EndBatch();
+ gui_sync_switches();
+ ProxyBridge_SetEnabled(gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(enable_item)));
+ set_engine_state(pbc_service_engine_running() ? ENGINE_RUNNING : ENGINE_STOPPED);
+ gtk_statusbar_push(GTK_STATUSBAR(status_bar), status_context_id, "Connected to the ProxyBridge service again.");
+ gui_log("connected to the ProxyBridge service again");
+ return G_SOURCE_REMOVE;
+}
+
+static gboolean service_lost_idle(gpointer data) {
+ if (reconnect_source) return G_SOURCE_REMOVE;
+ gtk_statusbar_push(GTK_STATUSBAR(status_bar), status_context_id, "Lost the connection to the ProxyBridge service. Trying to reconnect...");
+ gui_log("lost the connection to the ProxyBridge service; trying to reconnect");
+ set_engine_state(ENGINE_STOPPED);
+ reconnect_source = g_timeout_add_seconds(2, reconnect_tick, NULL);
+ return G_SOURCE_REMOVE;
+}
+
+static void on_service_lost(void) { // reader thread
+ g_idle_add(service_lost_idle, NULL);
+}
+
int main(int argc, char *argv[]) {
- if (getuid() != 0) {
+ setenv("GSETTINGS_BACKEND", "memory", 1);
+ // Prefer the ProxyBridge service: the window then needs no root. Without a service, a window started as root runs the engine itself.
+ char link_err[256] = "";
+ int link = pbc_connect(NULL, link_err, sizeof link_err);
+ if (link == PBC_CONNECTED) {
+ gui_store_use(&pbc_store);
+ } else if (link == PBC_REFUSED || getuid() != 0) {
gtk_init(&argc, &argv);
- show_message(NULL, GTK_MESSAGE_ERROR, "ProxyBridge must be run as root (sudo).");
+ if (link == PBC_REFUSED)
+ show_message(NULL, GTK_MESSAGE_ERROR, "%s\n\nIf this is a permissions problem, add your user to the group that may control ProxyBridge:\n sudo usermod -aG proxybridge $USER", link_err);
+ else
+ show_message(NULL, GTK_MESSAGE_ERROR, "The ProxyBridge service is not running.\n\nStart it with:\n sudo systemctl enable --now proxybridge\n\n(or run this window with sudo to use ProxyBridge without the service).");
return 1;
}
- setenv("GSETTINGS_BACKEND", "memory", 1);
load_config();
gtk_init(&argc, &argv);
@@ -646,7 +692,7 @@ int main(int argc, char *argv[]) {
rebuild_switch_menu(NULL);
GtkWidget *settings_menu = add_submenu(menubar, "Settings");
log_item = add_check_item(settings_menu, "Enable Traffic Logging", g_chk_logging, G_CALLBACK(on_log_traffic_toggled));
- boot_item = add_check_item(settings_menu, "Start at Boot (systemd service)", boot_is_enabled(), G_CALLBACK(on_boot_toggled));
+ boot_item = add_check_item(settings_menu, "Start at Boot (systemd service)", pbc_boot_is_enabled(), G_CALLBACK(on_boot_toggled));
clear_item = add_check_item(settings_menu, "Auto-clear Logs", g_chk_auto_clear, G_CALLBACK(on_auto_clear_toggled));
every_item = add_check_item(settings_menu, "Log Every Connection", g_chk_log_every, G_CALLBACK(on_log_every_toggled));
update_item = add_check_item(settings_menu, "Check for Updates on Startup", g_chk_updates, G_CALLBACK(on_update_startup_toggled));
@@ -689,8 +735,16 @@ int main(int argc, char *argv[]) {
ProxyBridge_SetTrafficLoggingEnabled(g_chk_logging);
ProxyBridge_SetDnsViaProxy(g_chk_dns);
ProxyBridge_SetLogEveryConnection(g_chk_log_every);
+ pbc_BeginBatch(); // the service loads the whole configuration at once, never half of it
apply_proxies_to_lib();
apply_rules_to_lib();
+ pbc_EndBatch();
+ if (pbc_is_service()) {
+ pbc_set_lost_callback(on_service_lost);
+ pbc_replay_history(lib_log_callback); // what the service did before this window opened
+ ProxyBridge_SetEnabled(true); // "Enable ProxyBridge" always starts on; the service may have been left paused by an earlier window
+ gui_log("connected to the ProxyBridge service%s", g_chk_boot ? " (Start at Boot is on: it keeps routing when this window is closed)" : "");
+ }
g_unix_signal_add(SIGINT, on_unix_signal, NULL);
g_unix_signal_add(SIGTERM, on_unix_signal, NULL);
@@ -698,7 +752,8 @@ int main(int argc, char *argv[]) {
gtk_widget_show_all(window);
update_status_info();
status_source = g_timeout_add_seconds(1, status_tick, NULL);
- engine_request(true);
+ if (pbc_is_service()) set_engine_state(pbc_service_engine_running() ? ENGINE_RUNNING : ENGINE_STOPPED); // it may already be routing (Start at Boot)
+ engine_request(true); // does nothing when it is
apply_zoom_css();
if (g_chk_updates && !pb_gui_ready_hook) gui_check_updates_on_startup();
if (pb_gui_ready_hook) pb_gui_ready_hook();
diff --git a/Linux/gui/pb_client.c b/Linux/gui/pb_client.c
new file mode 100644
index 0000000..0f0747d
--- /dev/null
+++ b/Linux/gui/pb_client.c
@@ -0,0 +1,616 @@
+#define PBC_IMPL
+#include "gui.h"
+#include "gui_boot.h"
+#include "pb_client.h"
+#include "pb_ipc.h"
+
+#include <errno.h>
+#include <pthread.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+
+// ---- connection ------------------------------------------------------------------------------------------------------------
+#define MAX_PENDING 16
+
+struct pending {
+ bool used, done, ok;
+ char id[24];
+ char **fields; // result fields (after ok/err)
+ unsigned nfields;
+ GQueue *lines; // streamed lines (proxy test), consumed by the thread that waits
+};
+
+static struct {
+ int fd;
+ bool service; // service mode (was connected at least once)
+ bool alive;
+ bool engine_running;
+ pthread_t reader;
+ bool reader_started;
+ pthread_mutex_t mu; // everything below and the pending table
+ pthread_cond_t cv;
+ pthread_mutex_t send_mu;
+ unsigned long next_id;
+ struct pending pend[MAX_PENDING];
+ LogCallback log_cb;
+ ConnectionCallbackEx conn_cb;
+ void (*lost_cb)(void);
+ char path[sizeof(((struct sockaddr_un *)0)->sun_path)];
+} C = { .fd = -1, .mu = PTHREAD_MUTEX_INITIALIZER, .cv = PTHREAD_COND_INITIALIZER, .send_mu = PTHREAD_MUTEX_INITIALIZER };
+
+bool pbc_is_service(void) { return C.service; }
+bool pbc_alive(void) { return C.service && C.alive; }
+bool pbc_service_engine_running(void) { return C.engine_running; }
+void pbc_set_lost_callback(void (*cb)(void)) { C.lost_cb = cb; }
+
+static void free_pending_fields(struct pending *p)
+{
+ for (unsigned i = 0; i < p->nfields; i++) g_free(p->fields[i]);
+ g_free(p->fields);
+ p->fields = NULL;
+ p->nfields = 0;
+}
+
+static void *reader_main(void *arg)
+{
+ (void)arg;
+ for (;;) {
+ pb_msg m;
+ int rc = pb_ipc_recv(C.fd, &m);
+ if (rc != 0) break;
+ if (m.n >= 2 && !strcmp(m.f[0], "e")) {
+ pthread_mutex_lock(&C.mu);
+ LogCallback lcb = C.log_cb;
+ ConnectionCallbackEx ccb = C.conn_cb;
+ pthread_mutex_unlock(&C.mu);
+ if (!strcmp(m.f[1], "log") && m.n >= 3 && lcb) lcb(m.f[2]);
+ else if (!strcmp(m.f[1], "conn") && m.n >= 8 && ccb) {
+ uint64_t pid = 0, port = 0;
+ for (const char *p = m.f[3]; *p >= '0' && *p <= '9'; p++) pid = pid * 10 + (uint64_t)(*p - '0');
+ for (const char *p = m.f[5]; *p >= '0' && *p <= '9'; p++) port = port * 10 + (uint64_t)(*p - '0');
+ ccb(m.f[2], (uint32_t)pid, m.f[4], (uint16_t)port, m.f[6], m.f[7]);
+ }
+ } else if (m.n >= 3 && !strcmp(m.f[0], "r")) {
+ pthread_mutex_lock(&C.mu);
+ bool refusal = !strcmp(m.f[1], "0");
+ for (int i = 0; i < MAX_PENDING; i++) {
+ struct pending *p = &C.pend[i];
+ if (!p->used || p->done) continue;
+ if (!refusal && strcmp(p->id, m.f[1]) != 0) continue;
+ if (!strcmp(m.f[2], "line") && m.n >= 4) {
+ g_queue_push_tail(p->lines, g_strdup(m.f[3]));
+ } else {
+ p->ok = !strcmp(m.f[2], "ok");
+ p->nfields = m.n - 3;
+ p->fields = g_new0(char *, p->nfields ? p->nfields : 1);
+ for (unsigned k = 0; k < p->nfields; k++) p->fields[k] = g_strndup(m.f[3 + k], m.len[3 + k]);
+ p->done = true;
+ }
+ }
+ pthread_cond_broadcast(&C.cv);
+ pthread_mutex_unlock(&C.mu);
+ }
+ pb_msg_free(&m);
+ }
+ pthread_mutex_lock(&C.mu);
+ C.alive = false;
+ pthread_cond_broadcast(&C.cv);
+ pthread_mutex_unlock(&C.mu);
+ if (C.lost_cb) C.lost_cb();
+ return NULL;
+}
+
+// One synchronous exchange on a fresh socket, before the reader thread exists
+static int handshake(int fd, char *err, size_t errn, bool *running)
+{
+ struct timeval tv = { 5, 0 };
+ setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
+ if (pb_ipc_sendv(fd, "q", "1", "hello", "1", (char *)NULL) != 0) { snprintf(err, errn, "the ProxyBridge service closed the connection"); return PBC_REFUSED; }
+ pb_msg m;
+ if (pb_ipc_recv(fd, &m) != 0) { snprintf(err, errn, "the ProxyBridge service did not answer"); return PBC_REFUSED; }
+ int rc = PBC_REFUSED;
+ if (m.n >= 3 && !strcmp(m.f[0], "r") && !strcmp(m.f[2], "ok") && m.n >= 6) {
+ *running = !strcmp(m.f[4], "1");
+ rc = PBC_CONNECTED;
+ } else {
+ snprintf(err, errn, "%s", m.n >= 4 ? m.f[3] : "the ProxyBridge service refused the connection");
+ }
+ pb_msg_free(&m);
+ tv.tv_sec = 0;
+ setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
+ return rc;
+}
+
+static int open_connection(const char *path, int *fd_out, bool *running, char *err, size_t errn)
+{
+ struct sockaddr_un a = { .sun_family = AF_UNIX };
+ if (strlen(path) >= sizeof a.sun_path) { snprintf(err, errn, "the socket path is too long"); return PBC_REFUSED; }
+ strcpy(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) {
+ int e = errno;
+ close(fd);
+ if (e == ENOENT || e == ECONNREFUSED) { snprintf(err, errn, "the ProxyBridge service is not running"); return PBC_NO_SERVICE; }
+ if (e == EACCES || e == EPERM) { snprintf(err, errn, "no permission to use the ProxyBridge service socket %s", path); return PBC_REFUSED; }
+ snprintf(err, errn, "cannot connect to %s: %s", path, strerror(e));
+ return PBC_REFUSED;
+ }
+ // A service that is not run by root is not the real one: never hand it proxy passwords.
+ struct ucred cred;
+ socklen_t cl = sizeof cred;
+ if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &cl) != 0 || cred.uid != 0) {
+ close(fd);
+ snprintf(err, errn, "the program listening on %s does not belong to root; refusing to talk to it", path);
+ return PBC_REFUSED;
+ }
+ int rc = handshake(fd, err, errn, running);
+ if (rc != PBC_CONNECTED) { close(fd); return rc; }
+ *fd_out = fd;
+ return PBC_CONNECTED;
+}
+
+static const char *socket_path(const char *given)
+{
+ if (given && *given) return given;
+#ifdef PB_TEST_HOOKS
+ const char *e = getenv("PROXYBRIDGE_SOCKET"); // the UI test build talks to a service of its own
+ if (e && *e) return e;
+#endif
+ return PB_IPC_SOCKET_PATH;
+}
+
+static void start_reader(int fd, bool running)
+{
+ pthread_mutex_lock(&C.mu);
+ C.fd = fd;
+ C.alive = true;
+ C.service = true;
+ C.engine_running = running;
+ pthread_mutex_unlock(&C.mu);
+ C.reader_started = pthread_create(&C.reader, NULL, reader_main, NULL) == 0;
+}
+
+int pbc_connect(const char *path, char *err, size_t errn)
+{
+ snprintf(C.path, sizeof C.path, "%s", socket_path(path));
+ int fd = -1;
+ bool running = false;
+ int rc = open_connection(C.path, &fd, &running, err, errn);
+ if (rc == PBC_CONNECTED) start_reader(fd, running);
+ return rc;
+}
+
+bool pbc_reconnect(void)
+{
+ if (!C.service) return false;
+ if (C.alive) return true;
+ if (C.reader_started) { pthread_join(C.reader, NULL); C.reader_started = false; }
+ if (C.fd >= 0) { close(C.fd); C.fd = -1; }
+ char err[256];
+ int fd = -1;
+ bool running = false;
+ if (open_connection(C.path, &fd, &running, err, sizeof err) != PBC_CONNECTED) return false;
+ start_reader(fd, running);
+ return true;
+}
+
+void pbc_disconnect(void)
+{
+ if (!C.service) return;
+ if (C.fd >= 0) shutdown(C.fd, SHUT_RDWR);
+ if (C.reader_started) { pthread_join(C.reader, NULL); C.reader_started = false; }
+ if (C.fd >= 0) { close(C.fd); C.fd = -1; }
+ C.alive = false;
+}
+
+// ---- one request -----------------------------------------------------------------------------------------------------------
+typedef struct {
+ bool ok;
+ char **f;
+ unsigned n;
+ char err[256];
+} reply_t;
+
+static void reply_free(reply_t *r)
+{
+ for (unsigned i = 0; i < r->n; i++) g_free(r->f[i]);
+ g_free(r->f);
+ memset(r, 0, sizeof *r);
+}
+
+// line: streamed lines are handed to it on the calling thread, as the library does for the proxy test
+static bool rpc(reply_t *r, const char *cmd, unsigned nargs, const char *const *args, void (*line)(const char *, void *), void *user)
+{
+ memset(r, 0, sizeof *r);
+ pthread_mutex_lock(&C.mu);
+ if (!C.alive) {
+ pthread_mutex_unlock(&C.mu);
+ snprintf(r->err, sizeof r->err, "the connection to the ProxyBridge service was lost");
+ return false;
+ }
+ struct pending *p = NULL;
+ for (int i = 0; i < MAX_PENDING && !p; i++) if (!C.pend[i].used) p = &C.pend[i];
+ if (!p) {
+ pthread_mutex_unlock(&C.mu);
+ snprintf(r->err, sizeof r->err, "too many requests at once");
+ return false;
+ }
+ memset(p, 0, sizeof *p);
+ p->used = true;
+ p->lines = g_queue_new();
+ snprintf(p->id, sizeof p->id, "%lu", ++C.next_id);
+ char idcopy[24];
+ snprintf(idcopy, sizeof idcopy, "%s", p->id);
+ pthread_mutex_unlock(&C.mu);
+
+ const char *f[3 + 16];
+ unsigned n = 0;
+ 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);
+ pthread_mutex_unlock(&C.send_mu);
+
+ pthread_mutex_lock(&C.mu);
+ if (sent != 0) {
+ snprintf(r->err, sizeof r->err, "the connection to the ProxyBridge service was lost");
+ } else {
+ for (;;) {
+ while (!g_queue_is_empty(p->lines)) {
+ char *l = g_queue_pop_head(p->lines);
+ pthread_mutex_unlock(&C.mu);
+ if (line) line(l, user);
+ g_free(l);
+ pthread_mutex_lock(&C.mu);
+ }
+ if (p->done) break;
+ if (!C.alive) {
+ snprintf(r->err, sizeof r->err, "the connection to the ProxyBridge service was lost");
+ break;
+ }
+ pthread_cond_wait(&C.cv, &C.mu);
+ }
+ }
+ if (p->done) {
+ r->ok = p->ok;
+ r->f = p->fields;
+ r->n = p->nfields;
+ p->fields = NULL;
+ p->nfields = 0;
+ if (!r->ok) {
+ snprintf(r->err, sizeof r->err, "%s", r->n ? r->f[0] : "the ProxyBridge service reported an error");
+ }
+ }
+ free_pending_fields(p);
+ g_queue_free_full(p->lines, g_free);
+ p->used = false;
+ pthread_mutex_unlock(&C.mu);
+ return r->ok;
+}
+
+static void copy_err(char *dst, size_t n, const reply_t *r)
+{
+ if (dst && n) snprintf(dst, n, "%s", r->err);
+}
+
+static bool simple(const char *cmd, unsigned nargs, const char *const *args)
+{
+ reply_t r;
+ bool ok = rpc(&r, cmd, nargs, args, NULL, NULL);
+ reply_free(&r);
+ return ok;
+}
+
+static bool simple_b(const char *cmd, bool v)
+{
+ const char *a[] = { v ? "1" : "0" };
+ return simple(cmd, 1, a);
+}
+
+static uint32_t parse_u32(const char *s)
+{
+ uint64_t v = 0;
+ for (; s && *s >= '0' && *s <= '9' && v < 0xffffffffull; s++) v = v * 10 + (uint64_t)(*s - '0');
+ return (uint32_t)v;
+}
+
+static bool is_embedded(void) { return !C.service; }
+
+// ---- the engine API --------------------------------------------------------------------------------------------------------
+uint32_t pbc_AddProxy(const char *name, ProxyType type, const char *host, uint16_t port, const char *user, const char *pass, char *err, size_t en)
+{
+ if (is_embedded()) return ProxyBridge_AddProxy(name, type, host, port, user, pass, err, en);
+ char t[4], p[8];
+ snprintf(t, sizeof t, "%d", (int)type);
+ snprintf(p, sizeof p, "%u", port);
+ const char *a[] = { name, t, host, p, user ? user : "", pass ? pass : "" };
+ reply_t r;
+ uint32_t id = 0;
+ if (rpc(&r, "proxy.add", 6, a, NULL, NULL) && r.n) id = parse_u32(r.f[0]);
+ else copy_err(err, en, &r);
+ reply_free(&r);
+ return id;
+}
+
+bool pbc_EditProxy(uint32_t id, const char *name, ProxyType type, const char *host, uint16_t port, const char *user, const char *pass, char *err, size_t en)
+{
+ if (is_embedded()) return ProxyBridge_EditProxy(id, name, type, host, port, user, pass, err, en);
+ char i[12], t[4], p[8];
+ snprintf(i, sizeof i, "%u", id);
+ snprintf(t, sizeof t, "%d", (int)type);
+ snprintf(p, sizeof p, "%u", port);
+ const char *a[] = { i, name, t, host, p, user ? user : "", pass ? pass : "" };
+ reply_t r;
+ bool ok = rpc(&r, "proxy.edit", 7, a, NULL, NULL);
+ if (!ok) copy_err(err, en, &r);
+ reply_free(&r);
+ return ok;
+}
+
+static bool id_cmd(const char *cmd, uint32_t id)
+{
+ char i[12];
+ snprintf(i, sizeof i, "%u", id);
+ const char *a[] = { i };
+ return simple(cmd, 1, a);
+}
+
+bool pbc_SetProxySendDomain(uint32_t id, bool v)
+{
+ if (is_embedded()) return ProxyBridge_SetProxySendDomain(id, v);
+ char i[12];
+ snprintf(i, sizeof i, "%u", id);
+ const char *a[] = { i, v ? "1" : "0" };
+ return simple("proxy.sendDomain", 2, a);
+}
+
+bool pbc_DeleteProxy(uint32_t id) { return is_embedded() ? ProxyBridge_DeleteProxy(id) : id_cmd("proxy.delete", id); }
+void pbc_ClearProxies(void) { if (is_embedded()) ProxyBridge_ClearProxies(); else simple("proxy.clear", 0, NULL); }
+void pbc_SetDefaultProxy(uint32_t id) { if (is_embedded()) ProxyBridge_SetDefaultProxy(id); else id_cmd("proxy.default", id); }
+
+uint32_t pbc_AddRule(const char *proc, const char *hosts, const char *ports, RuleProtocol proto, RuleAction act, uint32_t proxy_id, char *err, size_t en)
+{
+ if (is_embedded()) return ProxyBridge_AddRule(proc, hosts, ports, proto, act, proxy_id, err, en);
+ char pr[4], ac[4], px[12];
+ snprintf(pr, sizeof pr, "%d", (int)proto);
+ snprintf(ac, sizeof ac, "%d", (int)act);
+ snprintf(px, sizeof px, "%u", proxy_id);
+ const char *a[] = { proc ? proc : "", hosts ? hosts : "", ports ? ports : "", pr, ac, px };
+ reply_t r;
+ uint32_t id = 0;
+ if (rpc(&r, "rule.add", 6, a, NULL, NULL) && r.n) id = parse_u32(r.f[0]);
+ else copy_err(err, en, &r);
+ reply_free(&r);
+ return id;
+}
+
+bool pbc_EditRule(uint32_t id, const char *proc, const char *hosts, const char *ports, RuleProtocol proto, RuleAction act, uint32_t proxy_id, char *err, size_t en)
+{
+ if (is_embedded()) return ProxyBridge_EditRule(id, proc, hosts, ports, proto, act, proxy_id, err, en);
+ char i[12], pr[4], ac[4], px[12];
+ snprintf(i, sizeof i, "%u", id);
+ snprintf(pr, sizeof pr, "%d", (int)proto);
+ snprintf(ac, sizeof ac, "%d", (int)act);
+ snprintf(px, sizeof px, "%u", proxy_id);
+ const char *a[] = { i, proc ? proc : "", hosts ? hosts : "", ports ? ports : "", pr, ac, px };
+ reply_t r;
+ bool ok = rpc(&r, "rule.edit", 7, a, NULL, NULL);
+ if (!ok) copy_err(err, en, &r);
+ reply_free(&r);
+ return ok;
+}
+
+bool pbc_SetRuleLocalhost(uint32_t id, bool on)
+{
+ if (is_embedded()) return ProxyBridge_SetRuleLocalhost(id, on);
+ char i[12];
+ snprintf(i, sizeof i, "%u", id);
+ const char *a[] = { i, on ? "1" : "0" };
+ return simple("rule.localhost", 2, a);
+}
+
+bool pbc_EnableRule(uint32_t id) { return is_embedded() ? ProxyBridge_EnableRule(id) : id_cmd("rule.enable", id); }
+bool pbc_DisableRule(uint32_t id) { return is_embedded() ? ProxyBridge_DisableRule(id) : id_cmd("rule.disable", id); }
+bool pbc_DeleteRule(uint32_t id) { return is_embedded() ? ProxyBridge_DeleteRule(id) : id_cmd("rule.delete", id); }
+
+bool pbc_MoveRule(uint32_t id, int index)
+{
+ if (is_embedded()) return ProxyBridge_MoveRule(id, index);
+ char i[12], x[12];
+ snprintf(i, sizeof i, "%u", id);
+ snprintf(x, sizeof x, "%d", index < 0 ? 0 : index);
+ const char *a[] = { i, x };
+ return simple("rule.move", 2, a);
+}
+
+void pbc_ClearRules(void) { if (is_embedded()) ProxyBridge_ClearRules(); else simple("rule.clear", 0, NULL); }
+
+bool pbc_ValidateRule(const char *proc, const char *hosts, const char *ports, char *err, size_t en)
+{
+ if (is_embedded()) return ProxyBridge_ValidateRule(proc, hosts, ports, err, en);
+ const char *a[] = { proc ? proc : "", hosts ? hosts : "", ports ? ports : "" };
+ reply_t r;
+ bool ok = rpc(&r, "rule.validate", 3, a, NULL, NULL);
+ if (!ok) copy_err(err, en, &r);
+ reply_free(&r);
+ return ok;
+}
+
+void pbc_SetDnsViaProxy(bool v) { if (is_embedded()) ProxyBridge_SetDnsViaProxy(v); else simple_b("cfg.dns", v); }
+void pbc_SetEnabled(bool v) { if (is_embedded()) ProxyBridge_SetEnabled(v); else simple_b("cfg.enabled", v); }
+void pbc_SetLogEveryConnection(bool v) { if (is_embedded()) ProxyBridge_SetLogEveryConnection(v); else simple_b("cfg.logEvery", v); }
+void pbc_SetTrafficLoggingEnabled(bool v) { if (is_embedded()) ProxyBridge_SetTrafficLoggingEnabled(v); else simple_b("cfg.logging", v); }
+void pbc_BeginBatch(void) { if (is_embedded()) ProxyBridge_BeginBatch(); else simple("batch.begin", 0, NULL); }
+void pbc_EndBatch(void) { if (is_embedded()) ProxyBridge_EndBatch(); else simple("batch.end", 0, NULL); }
+
+void pbc_SetLogCallback(LogCallback cb)
+{
+ pthread_mutex_lock(&C.mu);
+ C.log_cb = cb;
+ pthread_mutex_unlock(&C.mu);
+ if (is_embedded()) ProxyBridge_SetLogCallback(cb);
+}
+
+void pbc_SetConnectionCallbackEx(ConnectionCallbackEx cb)
+{
+ pthread_mutex_lock(&C.mu);
+ C.conn_cb = cb;
+ pthread_mutex_unlock(&C.mu);
+ if (is_embedded()) ProxyBridge_SetConnectionCallbackEx(cb);
+}
+
+bool pbc_Start(void)
+{
+ if (is_embedded()) return ProxyBridge_Start();
+ return simple("engine.start", 0, NULL);
+}
+
+bool pbc_Stop(void)
+{
+ if (is_embedded()) return ProxyBridge_Stop();
+ return simple("engine.stop", 0, NULL);
+}
+
+static int hexv(char c) { return c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : 0; }
+
+uint32_t pbc_GetFlows(ProxyBridgeFlow *out, uint32_t max)
+{
+ if (is_embedded()) return ProxyBridge_GetFlows(out, max);
+ reply_t r;
+ uint32_t n = 0;
+ if (rpc(&r, "flows.get", 0, NULL, NULL, NULL)) {
+ for (unsigned i = 0; i < r.n && n < max && n < PB_FLOWS_MAX; i++) {
+ gchar **t = g_strsplit(r.f[i], "\t", 12);
+ if (g_strv_length(t) == 12) {
+ ProxyBridgeFlow *o = &out[n];
+ memset(o, 0, sizeof *o);
+ o->id = g_ascii_strtoull(t[0], NULL, 10);
+ o->pid = parse_u32(t[1]);
+ o->proxy_id = parse_u32(t[2]);
+ o->age_ms = parse_u32(t[3]);
+ o->sent = g_ascii_strtoull(t[4], NULL, 10);
+ o->received = g_ascii_strtoull(t[5], NULL, 10);
+ o->port = (uint16_t)parse_u32(t[6]);
+ o->is_udp = (uint8_t)parse_u32(t[7]);
+ o->is_ipv6 = (uint8_t)parse_u32(t[8]);
+ if (strlen(t[9]) == 32) for (int k = 0; k < 16; k++) o->dest[k] = (uint8_t)(hexv(t[9][2 * k]) * 16 + hexv(t[9][2 * k + 1]));
+ snprintf(o->name, sizeof o->name, "%s", t[10]);
+ snprintf(o->host, sizeof o->host, "%s", t[11]);
+ n++;
+ }
+ g_strfreev(t);
+ }
+ }
+ reply_free(&r);
+ return n;
+}
+
+int pbc_TestProxyEx(uint32_t proxy_id, const char *host, uint16_t port, ProxyTestLogCallback cb, void *user)
+{
+ if (is_embedded()) return ProxyBridge_TestProxyEx(proxy_id, host, port, cb, user);
+ char i[12], p[8];
+ snprintf(i, sizeof i, "%u", proxy_id);
+ snprintf(p, sizeof p, "%u", port);
+ const char *a[] = { i, host, p };
+ reply_t r;
+ int rc = -1;
+ if (rpc(&r, "proxy.test", 3, a, (void (*)(const char *, void *))cb, user) && r.n) {
+ rc = (int)parse_long(r.f[0]);
+ } else if (cb) {
+ cb(r.err, user);
+ }
+ reply_free(&r);
+ return rc;
+}
+
+void pbc_replay_history(LogCallback cb)
+{
+ if (is_embedded() || !cb) return;
+ reply_t r;
+ if (rpc(&r, "log.history", 0, NULL, NULL, NULL))
+ for (unsigned i = 0; i < r.n; i++) cb(r.f[i]);
+ reply_free(&r);
+}
+
+// ---- boot ------------------------------------------------------------------------------------------------------------------
+bool pbc_boot_is_enabled(void)
+{
+ if (is_embedded()) return boot_is_enabled();
+ return g_chk_boot; // read from the service's settings when the window started
+}
+
+bool pbc_boot_set(bool enable, char **error)
+{
+ if (error) *error = NULL;
+ if (is_embedded()) return boot_set(enable, error);
+ const char *a[] = { enable ? "1" : "0" };
+ reply_t r;
+ bool ok = rpc(&r, "boot.set", 1, a, NULL, NULL);
+ if (!ok && error) *error = g_strdup(r.err);
+ reply_free(&r);
+ return ok;
+}
+
+// ---- profile store ---------------------------------------------------------------------------------------------------------
+static bool st_list(GPtrArray *names)
+{
+ reply_t r;
+ bool ok = rpc(&r, "store.list", 0, NULL, NULL, NULL);
+ if (ok) for (unsigned i = 0; i < r.n; i++) g_ptr_array_add(names, g_strdup(r.f[i]));
+ reply_free(&r);
+ return ok;
+}
+
+static char *st_get(const char *name)
+{
+ const char *a[] = { name };
+ reply_t r;
+ char *out = NULL;
+ if (rpc(&r, "store.get", 1, a, NULL, NULL) && r.n) out = g_strdup(r.f[0]);
+ reply_free(&r);
+ return out;
+}
+
+static bool st_put(const char *name, const char *data, char *err, size_t en)
+{
+ const char *a[] = { name, data };
+ reply_t r;
+ bool ok = rpc(&r, "store.put", 2, a, NULL, NULL);
+ if (!ok) copy_err(err, en, &r);
+ reply_free(&r);
+ return ok;
+}
+
+static bool st_del(const char *name)
+{
+ const char *a[] = { name };
+ return simple("store.delete", 1, a);
+}
+
+static bool st_settings_get(char **active, bool *updates, bool *boot)
+{
+ reply_t r;
+ bool ok = rpc(&r, "store.settings.get", 0, NULL, NULL, NULL) && r.n >= 3;
+ if (ok) {
+ *active = r.f[0][0] ? g_strdup(r.f[0]) : NULL;
+ *updates = r.f[1][0] == '1';
+ *boot = r.f[2][0] == '1';
+ }
+ reply_free(&r);
+ return ok;
+}
+
+static bool st_settings_set(const char *active, bool updates, bool boot, char *err, size_t en)
+{
+ const char *a[] = { active ? active : "", updates ? "1" : "0", boot ? "1" : "0" };
+ reply_t r;
+ bool ok = rpc(&r, "store.settings.set", 3, a, NULL, NULL);
+ if (!ok) copy_err(err, en, &r);
+ reply_free(&r);
+ return ok;
+}
+
+static bool st_exists(const char *name) { (void)name; return true; } // the service owns the files; nothing can delete them behind our back
+
+const struct gui_store pbc_store = { st_list, st_get, st_put, st_del, st_exists, st_settings_get, st_settings_set };
diff --git a/Linux/gui/pb_client.h b/Linux/gui/pb_client.h
new file mode 100644
index 0000000..16b502e
--- /dev/null
+++ b/Linux/gui/pb_client.h
@@ -0,0 +1,93 @@
+// The window's link to the engine. With the ProxyBridge service running, every engine call goes over its socket (the window
+// then needs no root). Without a service, a window started as root runs the engine inside itself, as before.
+//
+// The functions have the signatures of the ProxyBridge_* functions they stand for; gui.h maps the names, so the rest of the
+// window is written against the library API in both modes.
+#ifndef PB_CLIENT_H
+#define PB_CLIENT_H
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include "ProxyBridge.h"
+
+enum { PBC_CONNECTED = 0, PBC_NO_SERVICE = 1, PBC_REFUSED = -1 };
+
+// Tries the service. PBC_NO_SERVICE: nothing is listening (a root window may then run its own engine). PBC_REFUSED: the service
+// is there but will not talk to us (not allowed, version mismatch...); err says why.
+int pbc_connect(const char *socket_path, char *err, size_t errn);
+bool pbc_is_service(void); // service mode
+bool pbc_alive(void); // service mode and the connection is healthy
+bool pbc_service_engine_running(void); // what the service said when we connected
+void pbc_disconnect(void);
+// Called (from the reader thread) when the connection is lost.
+void pbc_set_lost_callback(void (*cb)(void));
+// After a lost connection: try again. True when connected again (the window must then send its configuration again).
+bool pbc_reconnect(void);
+
+// Feeds the service's recent log lines (what it did before this window connected) to cb.
+void pbc_replay_history(LogCallback cb);
+
+// Whether "Start at Boot" is on, and switching it. Service mode asks the service; embedded mode writes the unit itself.
+bool pbc_boot_is_enabled(void);
+bool pbc_boot_set(bool enable, char **error); // *error g_malloc'd
+
+#ifndef PBC_IMPL
+#define ProxyBridge_AddProxy pbc_AddProxy
+#define ProxyBridge_EditProxy pbc_EditProxy
+#define ProxyBridge_SetProxySendDomain pbc_SetProxySendDomain
+#define ProxyBridge_DeleteProxy pbc_DeleteProxy
+#define ProxyBridge_ClearProxies pbc_ClearProxies
+#define ProxyBridge_SetDefaultProxy pbc_SetDefaultProxy
+#define ProxyBridge_AddRule pbc_AddRule
+#define ProxyBridge_EditRule pbc_EditRule
+#define ProxyBridge_SetRuleLocalhost pbc_SetRuleLocalhost
+#define ProxyBridge_EnableRule pbc_EnableRule
+#define ProxyBridge_DisableRule pbc_DisableRule
+#define ProxyBridge_DeleteRule pbc_DeleteRule
+#define ProxyBridge_MoveRule pbc_MoveRule
+#define ProxyBridge_ClearRules pbc_ClearRules
+#define ProxyBridge_ValidateRule pbc_ValidateRule
+#define ProxyBridge_SetDnsViaProxy pbc_SetDnsViaProxy
+#define ProxyBridge_SetEnabled pbc_SetEnabled
+#define ProxyBridge_SetLogEveryConnection pbc_SetLogEveryConnection
+#define ProxyBridge_SetLogCallback pbc_SetLogCallback
+#define ProxyBridge_SetConnectionCallbackEx pbc_SetConnectionCallbackEx
+#define ProxyBridge_SetTrafficLoggingEnabled pbc_SetTrafficLoggingEnabled
+#define ProxyBridge_BeginBatch pbc_BeginBatch
+#define ProxyBridge_EndBatch pbc_EndBatch
+#define ProxyBridge_Start pbc_Start
+#define ProxyBridge_Stop pbc_Stop
+#define ProxyBridge_GetFlows pbc_GetFlows
+#define ProxyBridge_TestProxyEx pbc_TestProxyEx
+#endif
+
+uint32_t pbc_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 pbc_EditProxy(uint32_t 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 pbc_SetProxySendDomain(uint32_t id, bool send_domain);
+bool pbc_DeleteProxy(uint32_t id);
+void pbc_ClearProxies(void);
+void pbc_SetDefaultProxy(uint32_t id);
+uint32_t pbc_AddRule(const char *process, const char *hosts, const char *ports, RuleProtocol protocol, RuleAction action, uint32_t proxy_id, char *err, size_t err_size);
+bool pbc_EditRule(uint32_t id, const char *process, const char *hosts, const char *ports, RuleProtocol protocol, RuleAction action, uint32_t proxy_id, char *err, size_t err_size);
+bool pbc_SetRuleLocalhost(uint32_t id, bool on);
+bool pbc_EnableRule(uint32_t id);
+bool pbc_DisableRule(uint32_t id);
+bool pbc_DeleteRule(uint32_t id);
+bool pbc_MoveRule(uint32_t id, int new_index);
+void pbc_ClearRules(void);
+bool pbc_ValidateRule(const char *process, const char *hosts, const char *ports, char *err, size_t err_size);
+void pbc_SetDnsViaProxy(bool enable);
+void pbc_SetEnabled(bool enable);
+void pbc_SetLogEveryConnection(bool enable);
+void pbc_SetLogCallback(LogCallback cb);
+void pbc_SetConnectionCallbackEx(ConnectionCallbackEx cb);
+void pbc_SetTrafficLoggingEnabled(bool enable);
+void pbc_BeginBatch(void);
+void pbc_EndBatch(void);
+bool pbc_Start(void);
+bool pbc_Stop(void);
+uint32_t pbc_GetFlows(ProxyBridgeFlow *out, uint32_t max);
+int pbc_TestProxyEx(uint32_t proxy_id, const char *host, uint16_t port, ProxyTestLogCallback cb, void *user);
+
+#endif
diff --git a/Linux/gui/proxybridge.desktop b/Linux/gui/proxybridge.desktop
index b1a4ce9..46583c0 100644
--- a/Linux/gui/proxybridge.desktop
+++ b/Linux/gui/proxybridge.desktop
@@ -8,6 +8,3 @@ Terminal=false
Categories=Network;Security;
StartupWMClass=ProxyBridgeGUI
StartupNotify=false
-# The GUI needs root (start it with sudo), so it is not offered in the application grid; this file gives the running window its
-# name and icon in the dock.
-NoDisplay=true
diff --git a/Linux/gui/tests/boot_test.c b/Linux/gui/tests/boot_test.c
index 5c27af6..5c6b7e7 100644
--- a/Linux/gui/tests/boot_test.c
+++ b/Linux/gui/tests/boot_test.c
@@ -33,11 +33,12 @@ int main(void)
char *t;
// unit text
- t = boot_unit_text("/x/ProxyBridge", "Work", &err); // a name would resolve against the service's cwd
+ t = boot_unit_text("x/ProxyBridge", &err); // a relative path would resolve against the service's cwd
CHECK(t == NULL && err && strstr(err, "absolute"));
g_free(err); err = NULL;
- t = boot_unit_text("/usr/local/bin/ProxyBridge", "/etc/proxybridge/profiles/Work.pbprofile", &err);
- CHECK(t && strstr(t, "LimitNOFILE=1048576") && strstr(t, "NoNewPrivileges=yes") && strstr(t, "ProtectSystem=strict") && strstr(t, "ProtectHome=read-only"));
+ 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"));
g_free(t);
// only root-owned, root-writable-only paths may be started at boot
@@ -50,83 +51,72 @@ int main(void)
char *lnk = g_build_filename(dir, "lnk", NULL);
CHECK(symlink("/usr/bin/true", lnk) == 0 && !boot_path_trusted(lnk, &why)); g_free(why); why = NULL; g_free(lnk);
- t = boot_unit_text("/usr/local/bin/ProxyBridge", "/etc/proxybridge/profiles/Work.pbprofile", &err);
- CHECK(t && strstr(t, "ExecStart=\"/usr/local/bin/ProxyBridge\" --profile \"/etc/proxybridge/profiles/Work.pbprofile\"\n") && strstr(t, "WantedBy=multi-user.target") &&
- strstr(t, "After=network-online.target") && strstr(t, "Restart=on-failure"));
+ t = boot_unit_text("/usr/local/bin/ProxyBridge", &err);
+ CHECK(t && strstr(t, "ExecStart=\"/usr/local/bin/ProxyBridge\" --daemon\n") && strstr(t, "WantedBy=multi-user.target") &&
+ strstr(t, "After=network-online.target") && strstr(t, "Restart=on-failure") && !strstr(t, "--profile"));
g_free(t);
- t = boot_unit_text("/x/ProxyBridge", "/p/a \"b\" \\c %h $HOME", &err);
- CHECK(t && strstr(t, "--profile \"/p/a \\\"b\\\" \\\\c %%h $$HOME\"\n")); // quoting that systemd understands
+ t = boot_unit_text("/x/a \"b\" \\c %h $HOME/ProxyBridge", &err);
+ CHECK(t && strstr(t, "ExecStart=\"/x/a \\\"b\\\" \\\\c %%h $$HOME/ProxyBridge\" --daemon\n")); // quoting that systemd understands
g_free(t);
- t = boot_unit_text("/x/ProxyBridge", "/p/line\nbreak", &err);
+ t = boot_unit_text("/x/Proxy\nBridge", &err);
CHECK(t == NULL && err && strstr(err, "control characters"));
g_free(err); err = NULL;
- t = boot_unit_text("/x/ProxyBridge", "/p/tab\there", &err);
+ t = boot_unit_text("/x/Proxy\tBridge", &err);
CHECK(t == NULL);
g_free(err); err = NULL;
- t = boot_unit_text("/x/Proxy\nBridge", "/p/ok", &err);
- CHECK(t == NULL && err);
- g_free(err); err = NULL;
// enable
CHECK(!boot_is_enabled());
- CHECK(boot_set(true, "/etc/proxybridge/profiles/Work.pbprofile", &err) && err == NULL);
+ CHECK(boot_set(true, &err) && err == NULL);
CHECK(boot_is_enabled());
char *content = slurp(unit);
- CHECK(strstr(content, "ExecStart=\"/opt/pb dir/ProxyBridge\" --profile \"/etc/proxybridge/profiles/Work.pbprofile\"\n")); // a path with a space is quoted
+ CHECK(strstr(content, "ExecStart=\"/opt/pb dir/ProxyBridge\" --daemon\n")); // a path with a space is quoted
struct stat st;
CHECK(stat(unit, &st) == 0 && (st.st_mode & 0777) == 0644);
char *log = slurp(calls);
CHECK(strstr(log, "daemon-reload") && strstr(log, "enable proxybridge.service"));
g_free(content); g_free(log);
- // another active profile rewrites the unit
- CHECK(boot_refresh("/etc/proxybridge/profiles/Home.pbprofile", &err));
- content = slurp(unit);
- CHECK(strstr(content, "--profile \"/etc/proxybridge/profiles/Home.pbprofile\"") && !strstr(content, "/etc/proxybridge/profiles/Work.pbprofile"));
- g_free(content);
-
// disable
g_unlink(calls);
- CHECK(boot_set(false, "/etc/proxybridge/profiles/Home.pbprofile", &err));
+ CHECK(boot_set(false, &err));
CHECK(!boot_is_enabled());
log = slurp(calls);
CHECK(strstr(log, "disable proxybridge.service") && strstr(log, "daemon-reload"));
g_free(log);
g_unlink(calls);
- CHECK(boot_refresh("/etc/proxybridge/profiles/Work.pbprofile", &err) && !boot_is_enabled()); // refresh does not enable anything
- CHECK(boot_set(false, "/etc/proxybridge/profiles/Work.pbprofile", &err)); // disabling twice is fine and runs nothing
+ CHECK(boot_set(false, &err)); // disabling twice is fine and runs nothing
log = slurp(calls);
CHECK(strlen(log) == 0);
g_free(log);
// a failing systemctl: report it and leave no unit behind
setenv("FAKE_FAIL", "enable", 1);
- CHECK(!boot_set(true, "/etc/proxybridge/profiles/Work.pbprofile", &err) && err && strstr(err, "systemctl enable") && strstr(err, "boom"));
+ CHECK(!boot_set(true, &err) && err && strstr(err, "systemctl enable") && strstr(err, "boom"));
CHECK(!boot_is_enabled());
g_free(err); err = NULL;
setenv("FAKE_FAIL", "daemon-reload", 1);
- CHECK(!boot_set(true, "/etc/proxybridge/profiles/Work.pbprofile", &err) && err && strstr(err, "daemon-reload"));
+ CHECK(!boot_set(true, &err) && err && strstr(err, "daemon-reload"));
CHECK(!boot_is_enabled());
g_free(err); err = NULL;
unsetenv("FAKE_FAIL");
- CHECK(boot_set(true, "/etc/proxybridge/profiles/Work.pbprofile", &err));
+ CHECK(boot_set(true, &err));
setenv("FAKE_FAIL", "disable", 1);
- CHECK(!boot_set(false, "/etc/proxybridge/profiles/Work.pbprofile", &err) && err && strstr(err, "disable"));
+ CHECK(!boot_set(false, &err) && err && strstr(err, "disable"));
CHECK(boot_is_enabled()); // still enabled: the disable failed
g_free(err); err = NULL;
unsetenv("FAKE_FAIL");
- CHECK(boot_set(false, "/etc/proxybridge/profiles/Work.pbprofile", &err));
+ CHECK(boot_set(false, &err));
// systemctl missing, and a directory that cannot be written
setenv("PROXYBRIDGE_SYSTEMCTL", "/nonexistent/systemctl", 1);
- CHECK(!boot_set(true, "/etc/proxybridge/profiles/Work.pbprofile", &err) && err && strstr(err, "could not run"));
+ CHECK(!boot_set(true, &err) && err && strstr(err, "could not run"));
CHECK(!boot_is_enabled());
g_free(err); err = NULL;
setenv("PROXYBRIDGE_SYSTEMCTL", fake, 1);
setenv("PROXYBRIDGE_SYSTEMD_DIR", "/nonexistent/dir", 1);
- CHECK(!boot_set(true, "/etc/proxybridge/profiles/Work.pbprofile", &err) && err && strstr(err, "cannot write"));
+ CHECK(!boot_set(true, &err) && err && strstr(err, "cannot write"));
g_free(err); err = NULL;
- CHECK(!boot_set(true, "/p/bad\nname", &err) && err && strstr(err, "control characters"));
g_free(err);
char *cmd = g_strdup_printf("rm -rf %s", dir);
diff --git a/Linux/gui/tests/run_tests.sh b/Linux/gui/tests/run_tests.sh
index 48c7fe2..49150e4 100755
--- a/Linux/gui/tests/run_tests.sh
+++ b/Linux/gui/tests/run_tests.sh
@@ -7,7 +7,7 @@ CF="-Wall -Wextra -Wno-unused-parameter -g -fsanitize=address,undefined -I../src
LF="$(pkg-config --libs gtk+-3.0)"
gcc $CF tests/config_test.c gui_config.c ../profile/pb_profile.c -o "$OUT/config_test" $LF
gcc $CF tests/json_test.c gui_json.c -o "$OUT/json_test" $LF
-gcc -g -Wall -Wextra -fsanitize=address,undefined -DPB_TEST_HOOKS -D_GNU_SOURCE -I. $(pkg-config --cflags glib-2.0) tests/boot_test.c gui_boot.c -o "$OUT/boot_test" $(pkg-config --libs glib-2.0)
+gcc -g -Wall -Wextra -fsanitize=address,undefined -DPB_TEST_HOOKS -D_GNU_SOURCE -I. -I../src $(pkg-config --cflags glib-2.0) tests/boot_test.c gui_boot.c ../src/pb_unit.c -o "$OUT/boot_test" $(pkg-config --libs glib-2.0)
gcc $CF tests/list_test.c gui_list.c -o "$OUT/list_test" $LF
gcc -O1 -I../src -I../profile -I. -D_GNU_SOURCE $(pkg-config --cflags gtk+-3.0) tests/config_test.c gui_config.c ../profile/pb_profile.c -o "$OUT/config_plain" $LF
"$OUT/config_plain"
diff --git a/Linux/gui/tests/ui_test.c b/Linux/gui/tests/ui_test.c
index 3d6d7da..1e28629 100644
--- a/Linux/gui/tests/ui_test.c
+++ b/Linux/gui/tests/ui_test.c
@@ -1230,8 +1230,34 @@ static void make_fake_systemctl(const char *path, const char *log)
g_free(script);
}
+// With the service, Start at Boot is a setting the service keeps in settings.json: it applies the active profile when it starts and
+// keeps routing after the window closes. The unit itself is installed (and enabled) by the installer.
+static bool settings_boot_flag(void)
+{
+ char *p = g_build_filename(getenv("PROXYBRIDGE_CONFIG_DIR"), "settings.json", NULL), *text = NULL;
+ bool on = g_file_get_contents(p, &text, NULL, NULL) && strstr(text, "\"StartAtBoot\": true");
+ g_free(text); g_free(p);
+ return on;
+}
+
+static void boot_service_scenario(void)
+{
+ STEP("start at boot (through the service)");
+ GtkWidget *item = menu_item("Start at Boot (systemd service)");
+ CHECK(item != NULL && !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(item)) && !settings_boot_flag());
+ gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), TRUE);
+ CHECK(g_chk_boot && settings_boot_flag());
+ CHECK_STR(g_active_profile, g_active_profile); // the active profile is kept in the same file
+ gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), FALSE);
+ CHECK(!g_chk_boot && !settings_boot_flag());
+ switch_to_profile("Zoomed");
+ switch_to_profile("Default");
+ CHECK(!settings_boot_flag()); // switching profiles does not touch it
+}
+
static void boot_scenario(void)
{
+ if (pbc_is_service()) { boot_service_scenario(); return; }
STEP("start at boot");
char *units = tmp_path("units"), *fake = tmp_path("systemctl"), *calls = tmp_path("systemctl.log");
g_mkdir_with_parents(units, 0755);
@@ -1246,34 +1272,23 @@ static void boot_scenario(void)
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), TRUE);
char *text = NULL;
CHECK(g_file_get_contents(unit, &text, NULL, NULL));
- // the unit names the stored profile FILE by its absolute path (a bare name would be resolved against the service's cwd)
- char *def_path = profile_path("Default"), *zoom_path = profile_path("Zoomed");
- char *want_default = g_strdup_printf("ExecStart=\"/usr/local/bin/ProxyBridge\" --profile \"%s\"", def_path);
- CHECK_HAS(text, want_default);
- CHECK(def_path[0] == '/' && strstr(text, "LimitNOFILE=1048576") && strstr(text, "NoNewPrivileges=yes"));
- g_free(want_default);
+ // the unit runs the service; which profile it starts is the one the window saved as active (settings.json), so the unit itself
+ // never changes when profiles are switched
+ CHECK_HAS(text, "ExecStart=\"/usr/local/bin/ProxyBridge\" --daemon\n");
+ CHECK(!strstr(text, "--profile") && strstr(text, "LimitNOFILE=1048576") && strstr(text, "NoNewPrivileges=yes") && strstr(text, "RuntimeDirectory=proxybridge"));
g_free(text);
char *log = NULL;
g_file_get_contents(calls, &log, NULL, NULL);
CHECK_HAS(log, "enable proxybridge.service");
g_free(log);
- // another active profile is what the service runs after the next boot
+ char *before = NULL, *after = NULL;
+ CHECK(g_file_get_contents(unit, &before, NULL, NULL));
switch_to_profile("Zoomed");
CHECK_STR(g_active_profile, "Zoomed");
- CHECK(g_file_get_contents(unit, &text, NULL, NULL));
- char *want_zoom = g_strdup_printf("--profile \"%s\"", zoom_path);
- CHECK_HAS(text, want_zoom);
- g_free(want_zoom);
- g_free(text);
switch_to_profile("Default");
- CHECK(g_file_get_contents(unit, &text, NULL, NULL));
- char *want_def2 = g_strdup_printf("--profile \"%s\"", def_path);
- CHECK_HAS(text, want_def2);
- g_free(want_def2);
- g_free(text);
- g_free(def_path);
- g_free(zoom_path);
+ CHECK(g_file_get_contents(unit, &after, NULL, NULL) && strcmp(before, after) == 0);
+ g_free(before); g_free(after);
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), FALSE);
CHECK(!g_file_test(unit, G_FILE_TEST_EXISTS));
diff --git a/Linux/profile/pb_profile.c b/Linux/profile/pb_profile.c
index 8c82b2b..d3bcc7f 100644
--- a/Linux/profile/pb_profile.c
+++ b/Linux/profile/pb_profile.c
@@ -752,7 +752,7 @@ int pbp_save_file(const char *path, const struct pbp_profile *p, char *err, size
return rc;
}
-int pbp_settings_load(const char *path, char **active, bool *check_updates)
+int pbp_settings_load(const char *path, char **active, bool *check_updates, bool *start_at_boot)
{
char err[200];
FILE *f = fopen(path, "r");
@@ -769,18 +769,20 @@ int pbp_settings_load(const char *path, char **active, bool *check_updates)
char *a = jtext(&root, "ActiveProfileName");
if (a && *a) { free(*active); *active = a; } else free(a);
if (check_updates) *check_updates = jbool(&root, "CheckForUpdatesOnStartup", true);
+ if (start_at_boot) *start_at_boot = jbool(&root, "StartAtBoot", false);
} else rc = -1;
jfree(&root);
free(buf);
return rc;
}
-int pbp_settings_save(const char *path, const char *active, bool check_updates, char *err, size_t errlen)
+int pbp_settings_save(const char *path, const char *active, bool check_updates, bool start_at_boot, char *err, size_t errlen)
{
struct sb b = {0};
sb_puts(&b, "{\n");
sb_kv(&b, " ", "ActiveProfileName", active ? active : "", ",\n");
- sb_puts(&b, check_updates ? " \"CheckForUpdatesOnStartup\": true\n}\n" : " \"CheckForUpdatesOnStartup\": false\n}\n");
+ sb_puts(&b, check_updates ? " \"CheckForUpdatesOnStartup\": true,\n" : " \"CheckForUpdatesOnStartup\": false,\n");
+ sb_puts(&b, start_at_boot ? " \"StartAtBoot\": true\n}\n" : " \"StartAtBoot\": false\n}\n");
if (b.oom) { free(b.p); snprintf(err, errlen, "out of memory"); return -1; }
int rc = pbp_write_file(path, b.p, err, errlen);
free(b.p);
diff --git a/Linux/profile/pb_profile.h b/Linux/profile/pb_profile.h
index 3ee6ee9..affe6c1 100644
--- a/Linux/profile/pb_profile.h
+++ b/Linux/profile/pb_profile.h
@@ -79,8 +79,10 @@ int pbp_save_file(const char *path, const struct pbp_profile *p, char *err, si
// settings.json next to the profiles holds the name of the active profile and the update check switch (both are not per profile);
// everything else lives in the profile files.
-int pbp_settings_load(const char *path, char **active, bool *check_updates); // -1 if missing or unreadable
-int pbp_settings_save(const char *path, const char *active, bool check_updates, char *err, size_t errlen);
+// start_at_boot: the ProxyBridge service applies the active profile when it starts, and keeps routing after the window is closed
+// (default false: the service stays idle until a window asks, and routing stops when that window closes).
+int pbp_settings_load(const char *path, char **active, bool *check_updates, bool *start_at_boot); // -1 if missing or unreadable; either bool may be NULL
+int pbp_settings_save(const char *path, const char *active, bool check_updates, bool start_at_boot, char *err, size_t errlen);
// Does a connection pass the filters? Excludes run first (any match hides); then, if there are Include filters, one must match.
// protocol: "TCP"/"UDP"; action: "Direct"/"Proxy"/"Blocked".
diff --git a/Linux/profile/tests/profile_test.c b/Linux/profile/tests/profile_test.c
index ebeca08..5ef734f 100644
--- a/Linux/profile/tests/profile_test.c
+++ b/Linux/profile/tests/profile_test.c
@@ -195,22 +195,23 @@ static void test_settings(void)
CHECK(mkdtemp(dir) != NULL);
snprintf(path, sizeof path, "%s/settings.json", dir);
char *active = NULL;
- bool upd = false;
- CHECK(pbp_settings_load(path, &active, &upd) == -1); // no file yet
- CHECK(pbp_settings_save(path, "Work", true, err, sizeof err) == 0);
- CHECK(pbp_settings_load(path, &active, &upd) == 0 && active && !strcmp(active, "Work") && upd);
- CHECK(pbp_settings_save(path, "Home \"x\"", false, err, sizeof err) == 0);
- upd = true;
- CHECK(pbp_settings_load(path, &active, &upd) == 0 && !strcmp(active, "Home \"x\"") && !upd);
+ bool upd = false, boot = false;
+ CHECK(pbp_settings_load(path, &active, &upd, &boot) == -1); // no file yet
+ CHECK(pbp_settings_save(path, "Work", true, true, err, sizeof err) == 0);
+ CHECK(pbp_settings_load(path, &active, &upd, &boot) == 0 && active && !strcmp(active, "Work") && upd && boot);
+ CHECK(pbp_settings_save(path, "Home \"x\"", false, false, err, sizeof err) == 0);
+ upd = true; boot = true;
+ CHECK(pbp_settings_load(path, &active, &upd, &boot) == 0 && !strcmp(active, "Home \"x\"") && !upd && !boot);
FILE *f = fopen(path, "w");
fputs("{ \"ActiveProfileName\": \"Only\" }", f); // an older file without the switch
fclose(f);
- upd = false;
- CHECK(pbp_settings_load(path, &active, &upd) == 0 && !strcmp(active, "Only") && upd); // defaults to on
+ upd = false; boot = true;
+ CHECK(pbp_settings_load(path, &active, &upd, &boot) == 0 && !strcmp(active, "Only") && upd && !boot); // update check defaults to on, start at boot to off
+ CHECK(pbp_settings_load(path, &active, NULL, NULL) == 0); // either switch may be left out
f = fopen(path, "w");
fputs("not json", f);
fclose(f);
- CHECK(pbp_settings_load(path, &active, &upd) == -1);
+ CHECK(pbp_settings_load(path, &active, &upd, &boot) == -1);
free(active);
char cmd[400];
snprintf(cmd, sizeof cmd, "rm -rf %s", dir);
diff --git a/Linux/src/Makefile b/Linux/src/Makefile
index 77dd4b3..9e11219 100644
--- a/Linux/src/Makefile
+++ b/Linux/src/Makefile
@@ -56,10 +56,11 @@ $(TARGET): $(OBJECTS) exports.map
$(BUILD_DIR)/%.o: %.c pb_internal.h ProxyBridge.h | $(BUILD_DIR)
$(CC) $(CFLAGS) -c $< -o $@
-test-rules: tests/rules_test.c tests/dns_test.c tests/proc_test.c pb_rules.c pb_rules.h pb_dns.c pb_dns.h pb_proc.c pb_proc.h | $(BUILD_DIR)
+test-rules: tests/rules_test.c tests/dns_test.c tests/proc_test.c tests/ipc_test.c pb_rules.c pb_rules.h pb_dns.c pb_dns.h pb_proc.c pb_proc.h pb_ipc.c pb_ipc.h | $(BUILD_DIR)
$(CC) -Wall -Wextra -g -fsanitize=address,undefined -D_GNU_SOURCE tests/rules_test.c pb_rules.c -o $(BUILD_DIR)/rules_test && $(BUILD_DIR)/rules_test
$(CC) -Wall -Wextra -g -fsanitize=address,undefined -D_GNU_SOURCE tests/dns_test.c pb_dns.c -o $(BUILD_DIR)/dns_test && $(BUILD_DIR)/dns_test
$(CC) -Wall -Wextra -g -fsanitize=address,undefined -D_GNU_SOURCE tests/proc_test.c pb_proc.c -o $(BUILD_DIR)/proc_test && $(BUILD_DIR)/proc_test
+ $(CC) -Wall -Wextra -g -fsanitize=address,undefined -D_GNU_SOURCE tests/ipc_test.c pb_ipc.c -o $(BUILD_DIR)/ipc_test && $(BUILD_DIR)/ipc_test
# Downloads, verifies and builds zlib, libelf (from elfutils) and libbpf (cached); prints nothing. `make -s libbpf-path` prints
# the directory to use as LIBBPF_DIR. Every download is checked against a pinned SHA-256.
diff --git a/Linux/src/ProxyBridge.c b/Linux/src/ProxyBridge.c
index a18b794..4187a5e 100644
--- a/Linux/src/ProxyBridge.c
+++ b/Linux/src/ProxyBridge.c
@@ -35,6 +35,7 @@ static struct {
pthread_mutex_t maint_mu;
pthread_cond_t maint_cv;
uint64_t warned[16]; size_t nwarned;
+ int batch; bool batch_dirty; // BeginBatch/EndBatch: changes reach the kernel datapath once, at the end
LogCallback log_cb;
ConnectionCallback conn_cb;
ConnectionCallbackEx conn_cb_ex;
@@ -328,6 +329,7 @@ static void sync_locked(void)
{
rebuild_views_locked();
if (!G.running) return;
+ if (G.batch > 0) { G.batch_dirty = true; 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();
@@ -854,6 +856,23 @@ void ProxyBridge_ClearConnectionLogs(void)
void ProxyBridge_SetLogEveryConnection(bool enable) { atomic_store(&G.log_every, enable); }
+void ProxyBridge_BeginBatch(void)
+{
+ pthread_rwlock_wrlock(&G.lock);
+ G.batch++;
+ pthread_rwlock_unlock(&G.lock);
+}
+
+void ProxyBridge_EndBatch(void)
+{
+ pthread_rwlock_wrlock(&G.lock);
+ if (G.batch > 0 && --G.batch == 0 && G.batch_dirty) {
+ G.batch_dirty = false;
+ sync_locked();
+ }
+ pthread_rwlock_unlock(&G.lock);
+}
+
void ProxyBridge_SetEnabled(bool enable)
{
atomic_store(&G.paused, !enable);
@@ -903,7 +922,11 @@ bool ProxyBridge_Start(void)
pb_bpf_set_paused(atomic_load(&G.paused));
pthread_rwlock_wrlock(&G.lock);
+ int held = G.batch; // starting always loads everything, even inside a batch
+ G.batch = 0;
sync_locked();
+ G.batch = held;
+ G.batch_dirty = false;
pthread_rwlock_unlock(&G.lock);
pb_core_log("ProxyBridge started (eBPF datapath, relay tcp:%u udp:%u)", pb_relay_tcp_port(), pb_relay_udp_port());
return true;
diff --git a/Linux/src/ProxyBridge.h b/Linux/src/ProxyBridge.h
index c8b65e6..d966dab 100644
--- a/Linux/src/ProxyBridge.h
+++ b/Linux/src/ProxyBridge.h
@@ -80,6 +80,11 @@ PB_API bool ProxyBridge_SetProxyConfig(ProxyType type, const char* proxy_ip, uin
/* ---- Runtime --------------------------------------------------------------------------------------------------------- */
PB_API void ProxyBridge_SetDnsViaProxy(bool enable);
+/* Batch: between BeginBatch and EndBatch, changes to proxies and rules are collected and loaded into the kernel datapath once, at
+ * the end, so replacing a whole configuration never exposes a half-built rule set to new connections. Calls nest; every
+ * BeginBatch needs an EndBatch. */
+PB_API void ProxyBridge_BeginBatch(void);
+PB_API void ProxyBridge_EndBatch(void);
/* Main switch (default true). False pauses every rule for new connections; existing connections are not touched. */
PB_API void ProxyBridge_SetEnabled(bool enable);
/* Connection log: by default a connection is reported once per (application, destination, port, protocol, action); true reports
diff --git a/Linux/src/pb_ipc.c b/Linux/src/pb_ipc.c
new file mode 100644
index 0000000..391311d
--- /dev/null
+++ b/Linux/src/pb_ipc.c
@@ -0,0 +1,147 @@
+#include "pb_ipc.h"
+
+#include <errno.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+static void put32(unsigned char *p, uint32_t v) { p[0] = v >> 24; p[1] = v >> 16; p[2] = v >> 8; p[3] = (unsigned char)v; }
+static uint32_t get32(const unsigned char *p) { return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3]; }
+
+void pb_msg_free(pb_msg *m)
+{
+ if (!m) return;
+ free(m->f);
+ free(m->len);
+ free(m->pool);
+ memset(m, 0, sizeof *m);
+}
+
+unsigned char *pb_ipc_encode(unsigned n, const char *const *f, const size_t *len, size_t *out_len)
+{
+ if (n > PB_IPC_MAX_FIELDS) return NULL;
+ size_t total = 2;
+ for (unsigned i = 0; i < n; i++) {
+ size_t l = len ? len[i] : strlen(f[i]);
+ if (l > PB_IPC_MAX_FRAME) return NULL;
+ total += 4 + l;
+ if (total > PB_IPC_MAX_FRAME) return NULL;
+ }
+ unsigned char *out = malloc(4 + total);
+ if (!out) return NULL;
+ put32(out, (uint32_t)total);
+ out[4] = (unsigned char)(n >> 8);
+ out[5] = (unsigned char)n;
+ size_t pos = 6;
+ for (unsigned i = 0; i < n; i++) {
+ size_t l = len ? len[i] : strlen(f[i]);
+ put32(out + pos, (uint32_t)l);
+ pos += 4;
+ if (l) memcpy(out + pos, f[i], l);
+ pos += l;
+ }
+ *out_len = 4 + total;
+ return out;
+}
+
+int pb_ipc_decode(const unsigned char *p, size_t plen, pb_msg *m)
+{
+ memset(m, 0, sizeof *m);
+ if (plen < 2 || plen > PB_IPC_MAX_FRAME) return -2;
+ unsigned n = ((unsigned)p[0] << 8) | p[1];
+ if (n > PB_IPC_MAX_FIELDS) return -2;
+ // First pass: the lengths must add up exactly, before anything is allocated
+ size_t pos = 2, data = 0;
+ for (unsigned i = 0; i < n; i++) {
+ if (plen - pos < 4) return -2;
+ uint32_t l = get32(p + pos);
+ pos += 4;
+ if (l > plen - pos) return -2;
+ pos += l;
+ data += l;
+ }
+ if (pos != plen) return -2;
+
+ m->f = calloc(n ? n : 1, sizeof *m->f);
+ m->len = calloc(n ? n : 1, sizeof *m->len);
+ m->pool = malloc(data + n + 1);
+ if (!m->f || !m->len || !m->pool) { pb_msg_free(m); return -1; }
+ m->n = n;
+ pos = 2;
+ size_t out = 0;
+ for (unsigned i = 0; i < n; i++) {
+ uint32_t l = get32(p + pos);
+ pos += 4;
+ m->f[i] = m->pool + out;
+ m->len[i] = l;
+ if (l) memcpy(m->pool + out, p + pos, l);
+ m->pool[out + l] = '\0';
+ out += (size_t)l + 1;
+ pos += l;
+ }
+ return 0;
+}
+
+static int read_full(int fd, void *buf, size_t n)
+{
+ unsigned char *p = buf;
+ while (n) {
+ ssize_t r = read(fd, p, n);
+ if (r > 0) { p += r; n -= (size_t)r; continue; }
+ if (r < 0 && errno == EINTR) continue;
+ return -1;
+ }
+ return 0;
+}
+
+static int write_full(int fd, const void *buf, size_t n)
+{
+ const unsigned char *p = buf;
+ while (n) {
+ ssize_t w = send(fd, p, n, MSG_NOSIGNAL);
+ if (w > 0) { p += w; n -= (size_t)w; continue; }
+ if (w < 0 && errno == EINTR) continue;
+ return -1;
+ }
+ return 0;
+}
+
+int pb_ipc_recv(int fd, pb_msg *m)
+{
+ memset(m, 0, sizeof *m);
+ unsigned char hdr[4];
+ if (read_full(fd, hdr, 4) != 0) return -1;
+ uint32_t l = get32(hdr);
+ 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; }
+ int rc = pb_ipc_decode(buf, l, m);
+ free(buf);
+ return rc;
+}
+
+int pb_ipc_send(int fd, unsigned n, const char *const *f, const size_t *len)
+{
+ size_t out_len;
+ unsigned char *frame = pb_ipc_encode(n, f, len, &out_len);
+ if (!frame) return -1;
+ int rc = write_full(fd, frame, out_len);
+ free(frame);
+ return rc;
+}
+
+int pb_ipc_sendv(int fd, ...)
+{
+ const char *f[64];
+ unsigned n = 0;
+ va_list ap;
+ va_start(ap, fd);
+ const char *s;
+ while (n < 64 && (s = va_arg(ap, const char *)) != NULL) f[n++] = s;
+ va_end(ap);
+ return pb_ipc_send(fd, n, f, NULL);
+}
diff --git a/Linux/src/pb_ipc.h b/Linux/src/pb_ipc.h
new file mode 100644
index 0000000..e3ecf38
--- /dev/null
+++ b/Linux/src/pb_ipc.h
@@ -0,0 +1,46 @@
+// Messages between the ProxyBridge service (root, "ProxyBridge --daemon") and its clients (the GUI), over a Unix socket.
+//
+// frame = u32 length (big endian, bytes after this field) | u16 field count | field...
+// field = u32 length | bytes
+//
+// Every message is a list of byte strings. Numbers are decimal text. The first field is the kind:
+// request "q" <id> <command> <argument>...
+// response "r" <id> "ok" <result>... or "r" <id> "err" <reason>
+// event "e" <name> <argument>...
+// Limits are enforced while reading, before anything is allocated, so a client cannot make the service allocate more than
+// PB_IPC_MAX_FRAME for one message.
+#ifndef PB_IPC_H
+#define PB_IPC_H
+
+#include <stddef.h>
+#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_FIELDS 4096
+#define PB_IPC_SOCKET_DIR "/run/proxybridge"
+#define PB_IPC_SOCKET_PATH "/run/proxybridge/ctl.sock"
+
+typedef struct {
+ unsigned n;
+ char **f; // f[i] is NUL terminated (it may also contain NULs: use len[i])
+ size_t *len;
+ char *pool; // all fields live here
+} pb_msg;
+
+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);
+// 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.
+int pb_ipc_sendv(int fd, ...);
+
+// Pure encoding and decoding (the I/O functions use these; they are also what the tests and the fuzzer drive).
+// pb_ipc_encode returns a malloc'd frame (*out_len bytes) or NULL when the message is too big.
+unsigned char *pb_ipc_encode(unsigned n, const char *const *f, const size_t *len, size_t *out_len);
+// Decodes the payload of a frame (without the 4 length bytes). 0 or -2.
+int pb_ipc_decode(const unsigned char *payload, size_t plen, pb_msg *m);
+
+#endif
diff --git a/Linux/src/pb_unit.c b/Linux/src/pb_unit.c
new file mode 100644
index 0000000..dbfcbc6
--- /dev/null
+++ b/Linux/src/pb_unit.c
@@ -0,0 +1,68 @@
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include "pb_unit.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+// systemd's own quoting for one ExecStart word: backslash, double quote, % (specifier) and $ (variable) are escaped
+static void quote_word(char *out, const char *s)
+{
+ *out++ = '"';
+ for (; *s; s++) {
+ if (*s == '\\' || *s == '"') *out++ = '\\';
+ else if (*s == '%') *out++ = '%';
+ else if (*s == '$') *out++ = '$';
+ *out++ = *s;
+ }
+ *out++ = '"';
+ *out = '\0';
+}
+
+char *pb_unit_text(const char *exe, const char **error)
+{
+ if (!exe || exe[0] != '/') { if (error) *error = "the program must be given as an absolute path"; return NULL; }
+ for (const char *p = exe; *p; p++)
+ if ((unsigned char)*p < 0x20 || *p == 0x7f) { if (error) *error = "the program path contains control characters"; return NULL; }
+ size_t n = strlen(exe) * 2 + 8;
+ char *quoted = malloc(n);
+ if (!quoted) { if (error) *error = "out of memory"; return NULL; }
+ quote_word(quoted, exe);
+ char *text = NULL;
+ // The service needs root for eBPF and /proc and nothing else: no new privileges, nothing writable but its own configuration
+ // folder, no home directories, no other users' temporary files.
+ int rc = asprintf(&text,
+ "[Unit]\n"
+ "Description=ProxyBridge\n"
+ "Documentation=https://proxybridge.interceptsuite.com/docs/linux-settings/\n"
+ "After=network-online.target\n"
+ "Wants=network-online.target\n"
+ "\n"
+ "[Service]\n"
+ "Type=simple\n"
+ "ExecStart=%s --daemon\n"
+ "Restart=on-failure\n"
+ "RestartSec=5\n"
+ "RuntimeDirectory=proxybridge\n"
+ "RuntimeDirectoryMode=0755\n"
+ "LimitNOFILE=1048576\n"
+ "NoNewPrivileges=yes\n"
+ "ProtectSystem=strict\n"
+ "ReadWritePaths=/etc/proxybridge\n"
+ "ProtectHome=yes\n"
+ "PrivateTmp=yes\n"
+ "ProtectKernelModules=yes\n"
+ "ProtectKernelLogs=yes\n"
+ "ProtectClock=yes\n"
+ "RestrictSUIDSGID=yes\n"
+ "LockPersonality=yes\n"
+ "RestrictRealtime=yes\n"
+ "\n"
+ "[Install]\n"
+ "WantedBy=multi-user.target\n", quoted);
+ free(quoted);
+ if (rc < 0) { if (error) *error = "out of memory"; return NULL; }
+ return text;
+}
diff --git a/Linux/src/pb_unit.h b/Linux/src/pb_unit.h
new file mode 100644
index 0000000..32ff8ae
--- /dev/null
+++ b/Linux/src/pb_unit.h
@@ -0,0 +1,12 @@
+// The systemd unit that runs "ProxyBridge --daemon". One text for everything that installs it: setup.sh (through
+// "ProxyBridge --print-unit"), the window's Start at Boot in embedded mode, and the tests.
+#ifndef PB_UNIT_H
+#define PB_UNIT_H
+
+#define PB_UNIT_NAME "proxybridge.service"
+
+// exe: absolute path of the ProxyBridge program. Returns the malloc'd unit text, or NULL with *error (static string) set when the
+// path cannot be written safely into a service file (relative, control characters).
+char *pb_unit_text(const char *exe, const char **error);
+
+#endif
diff --git a/Linux/src/tests/ipc_test.c b/Linux/src/tests/ipc_test.c
new file mode 100644
index 0000000..9794d6f
--- /dev/null
+++ b/Linux/src/tests/ipc_test.c
@@ -0,0 +1,155 @@
+// Unit test of the service protocol framing (pb_ipc.c): round trips, every kind of malformed input, a fuzz run. Needs no root.
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/socket.h>
+#include "../pb_ipc.h"
+
+static int checks, fails;
+#define CHECK(c) do { checks++; if (!(c)) { fails++; printf("FAIL line %d: %s\n", __LINE__, #c); } } while (0)
+
+static void roundtrip(void)
+{
+ const char *f[] = { "q", "7", "proxy.add", "", "with space", "ünïcode", "tab\there" };
+ size_t len;
+ unsigned char *frame = pb_ipc_encode(7, f, NULL, &len);
+ CHECK(frame && len > 4);
+ CHECK(((size_t)frame[0] << 24 | frame[1] << 16 | frame[2] << 8 | frame[3]) == len - 4);
+ pb_msg m;
+ CHECK(pb_ipc_decode(frame + 4, len - 4, &m) == 0 && m.n == 7);
+ for (unsigned i = 0; i < 7 && m.n == 7; i++) CHECK(strcmp(m.f[i], f[i]) == 0 && m.len[i] == strlen(f[i]));
+ pb_msg_free(&m);
+ free(frame);
+
+ // binary data with NULs and an empty message
+ const char blob[] = { 'a', 0, 'b', 0, 0, 'c' };
+ const char *g[] = { blob };
+ size_t gl[] = { sizeof blob };
+ frame = pb_ipc_encode(1, g, gl, &len);
+ CHECK(pb_ipc_decode(frame + 4, len - 4, &m) == 0 && m.n == 1 && m.len[0] == sizeof blob && memcmp(m.f[0], blob, sizeof blob) == 0 && m.f[0][sizeof blob] == '\0');
+ pb_msg_free(&m);
+ free(frame);
+ frame = pb_ipc_encode(0, NULL, NULL, &len);
+ CHECK(frame && pb_ipc_decode(frame + 4, len - 4, &m) == 0 && m.n == 0);
+ pb_msg_free(&m);
+ free(frame);
+}
+
+static void limits(void)
+{
+ size_t len;
+ const char *f[1] = { "x" };
+ CHECK(pb_ipc_encode(PB_IPC_MAX_FIELDS + 1, f, NULL, &len) == NULL);
+ const char **many = calloc(PB_IPC_MAX_FIELDS, sizeof *many);
+ for (int i = 0; i < PB_IPC_MAX_FIELDS; i++) many[i] = "";
+ unsigned char *frame = pb_ipc_encode(PB_IPC_MAX_FIELDS, many, NULL, &len);
+ pb_msg m;
+ CHECK(frame && pb_ipc_decode(frame + 4, len - 4, &m) == 0 && m.n == PB_IPC_MAX_FIELDS);
+ pb_msg_free(&m);
+ free(frame);
+ free(many);
+ size_t big = PB_IPC_MAX_FRAME;
+ char *huge = malloc(big);
+ memset(huge, 'a', big);
+ const char *h[] = { huge };
+ size_t hl[] = { big };
+ CHECK(pb_ipc_encode(1, h, hl, &len) == NULL); // frame limit includes the headers
+ free(huge);
+
+ // decode refuses: a field count above the limit, a length past the end, trailing bytes, too short
+ unsigned char bad1[] = { 0xff, 0xff };
+ CHECK(pb_ipc_decode(bad1, sizeof bad1, &m) == -2);
+ unsigned char bad2[] = { 0, 1, 0, 0, 0, 9, 'a' };
+ CHECK(pb_ipc_decode(bad2, sizeof bad2, &m) == -2);
+ unsigned char bad3[] = { 0, 1, 0, 0, 0, 1, 'a', 'x' };
+ CHECK(pb_ipc_decode(bad3, sizeof bad3, &m) == -2);
+ unsigned char bad4[] = { 0 };
+ CHECK(pb_ipc_decode(bad4, sizeof bad4, &m) == -2);
+ unsigned char bad5[] = { 0, 2, 0, 0, 0, 1, 'a' }; // announces two fields, holds one
+ CHECK(pb_ipc_decode(bad5, sizeof bad5, &m) == -2);
+ unsigned char bad6[] = { 0, 1, 0xff, 0xff, 0xff, 0xff, 'a' }; // length that would overflow an addition
+ CHECK(pb_ipc_decode(bad6, sizeof bad6, &m) == -2);
+}
+
+static void every_truncation(void)
+{
+ const char *f[] = { "q", "1", "store.put", "name", "{\"a\":1}" };
+ size_t len;
+ unsigned char *frame = pb_ipc_encode(5, f, NULL, &len);
+ pb_msg m;
+ for (size_t cut = 0; cut < len - 4; cut++) CHECK(pb_ipc_decode(frame + 4, cut, &m) == -2);
+ CHECK(pb_ipc_decode(frame + 4, len - 4, &m) == 0);
+ pb_msg_free(&m);
+ free(frame);
+}
+
+static void fuzz(void)
+{
+ srand(12345);
+ unsigned char buf[400];
+ int accepted = 0;
+ for (int i = 0; i < 300000; i++) {
+ size_t n = (size_t)(rand() % (int)sizeof buf);
+ for (size_t k = 0; k < n; k++) buf[k] = (unsigned char)(rand() % 4 == 0 ? rand() : (rand() % 3)); // many small numbers: plausible counts and lengths
+ pb_msg m;
+ int rc = pb_ipc_decode(buf, n, &m);
+ if (rc == 0) { accepted++; pb_msg_free(&m); }
+ }
+ CHECK(accepted > 0);
+}
+
+static void sockets(void)
+{
+ int sv[2];
+ CHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
+ CHECK(pb_ipc_sendv(sv[0], "e", "log", "hello", (char *)NULL) == 0);
+ pb_msg m;
+ CHECK(pb_ipc_recv(sv[1], &m) == 0 && m.n == 3 && strcmp(m.f[2], "hello") == 0);
+ pb_msg_free(&m);
+ // two frames in one write, then a frame split across writes
+ size_t l1, l2;
+ const char *a[] = { "a" }, *b[] = { "bb", "cc" };
+ unsigned char *f1 = pb_ipc_encode(1, a, NULL, &l1), *f2 = pb_ipc_encode(2, b, NULL, &l2);
+ unsigned char *both = malloc(l1 + l2);
+ memcpy(both, f1, l1); memcpy(both + l1, f2, l2);
+ CHECK(write(sv[0], both, l1 + l2) == (ssize_t)(l1 + l2));
+ CHECK(pb_ipc_recv(sv[1], &m) == 0 && m.n == 1); pb_msg_free(&m);
+ CHECK(pb_ipc_recv(sv[1], &m) == 0 && m.n == 2 && strcmp(m.f[1], "cc") == 0); pb_msg_free(&m);
+ CHECK(write(sv[0], f2, 3) == 3);
+ CHECK(write(sv[0], f2 + 3, l2 - 3) == (ssize_t)(l2 - 3));
+ CHECK(pb_ipc_recv(sv[1], &m) == 0 && m.n == 2); pb_msg_free(&m);
+ // a header announcing more than the limit is refused before anything is read or allocated
+ unsigned char hdr[4] = { 0x7f, 0xff, 0xff, 0xff };
+ CHECK(write(sv[0], hdr, 4) == 4);
+ CHECK(pb_ipc_recv(sv[1], &m) == -2);
+ // an announced length shorter than the minimum
+ unsigned char tiny[4] = { 0, 0, 0, 1 };
+ CHECK(write(sv[0], tiny, 4) == 4);
+ CHECK(pb_ipc_recv(sv[1], &m) == -2);
+ // the peer vanishes in the middle of a frame
+ CHECK(write(sv[0], f2, 6) == 6);
+ close(sv[0]);
+ CHECK(pb_ipc_recv(sv[1], &m) == -1);
+ // writing to a closed peer fails (no SIGPIPE)
+ int sv2[2];
+ CHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, sv2) == 0);
+ close(sv2[1]);
+ CHECK(pb_ipc_sendv(sv2[0], "e", "x", (char *)NULL) == -1);
+ close(sv2[0]); close(sv[1]);
+ free(f1); free(f2); free(both);
+}
+
+int main(void)
+{
+ roundtrip();
+ limits();
+ every_truncation();
+ fuzz();
+ sockets();
+ 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.c
index c08c432..64c057d 100644
--- a/Linux/tests/api_live_test.c
+++ b/Linux/tests/api_live_test.c
@@ -174,6 +174,37 @@ int main(void)
buf[0] = 0; check("TestProxy against a dead proxy fails with a readable message", ProxyBridge_TestProxy(dead, "192.0.2.77", 80, buf, sizeof buf) != 0 && strlen(buf) > 5);
printf(" (%s)\n", buf);
+ printf("== batch: a whole configuration reaches the datapath at once\n");
+ {
+ ProxyBridge_ClearRules();
+ uint32_t bxa = ProxyBridge_AddProxy("batch-a", PROXY_TYPE_SOCKS5, "127.0.0.1", 19080, "", "", err, sizeof err);
+ uint32_t bxb = ProxyBridge_AddProxy("batch-b", PROXY_TYPE_SOCKS5, "127.0.0.1", 19081, "bob", "pw", err, sizeof err);
+ uint32_t keep = ProxyBridge_AddRule("curl", "192.0.2.64/26", "*", RULE_PROTOCOL_TCP, RULE_ACTION_PROXY, bxa, err, sizeof err);
+ expect("a rule before the batch routes", "192.0.2.70", "hello-from-A");
+ ProxyBridge_BeginBatch();
+ ProxyBridge_ClearRules();
+ uint32_t nr = ProxyBridge_AddRule("curl", "192.0.2.128/26", "*", RULE_PROTOCOL_TCP, RULE_ACTION_PROXY, bxb, err, sizeof err);
+ check("rules can be changed inside a batch", nr != 0);
+ expect("inside a batch the datapath still has the old rules", "192.0.2.70", "hello-from-A");
+ expect("inside a batch the new rule is not active yet", "192.0.2.130", NULL);
+ ProxyBridge_BeginBatch(); // batches nest
+ ProxyBridge_EndBatch();
+ expect("a nested batch ending does not release the outer one", "192.0.2.130", NULL);
+ ProxyBridge_EndBatch();
+ expect("when the outer batch ends the new configuration is live", "192.0.2.130", "hello-from-B");
+ expect("and the old rule is gone", "192.0.2.70", NULL);
+ ProxyBridge_EndBatch(); // an unbalanced End is harmless
+ ProxyBridge_BeginBatch();
+ ProxyBridge_Stop();
+ check("Start inside a batch still loads everything", ProxyBridge_Start());
+ expect("rules are live after Start inside a batch", "192.0.2.130", "hello-from-B");
+ ProxyBridge_EndBatch();
+ ProxyBridge_DeleteRule(nr);
+ ProxyBridge_DeleteProxy(bxa);
+ ProxyBridge_DeleteProxy(bxb);
+ (void)keep;
+ }
+
printf("== cleanup\n");
ProxyBridge_ClearRules();
expect("ClearRules: direct again", "192.0.2.5", NULL);
diff --git a/Linux/tests/e2e_daemon.py b/Linux/tests/e2e_daemon.py
new file mode 100755
index 0000000..fdab6f8
--- /dev/null
+++ b/Linux/tests/e2e_daemon.py
@@ -0,0 +1,399 @@
+#!/usr/bin/env python3
+"""End-to-end test of the ProxyBridge service. Needs root (it loads the eBPF programs)."""
+import os, sys, time, json, socket, struct, subprocess, tempfile, shutil, random, signal, threading, urllib.request
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+import pbd
+
+PB = os.path.join(os.environ["PB_DIR"], "ProxyBridge")
+WORK = tempfile.mkdtemp(prefix="pbdaemon.")
+os.chmod(WORK, 0o755) # the socket folder must be reachable by the unprivileged user of the access tests
+CFG = os.path.join(WORK, "cfg")
+SOCK = os.path.join(WORK, "run", "ctl.sock")
+PASS = FAIL = 0
+procs = []
+
+
+def ok(name):
+ global PASS
+ PASS += 1
+ print(" PASS " + name, flush=True)
+
+
+def bad(name, why=""):
+ global FAIL
+ FAIL += 1
+ print(" FAIL %s %s" % (name, why), flush=True)
+
+
+def check(name, cond, why=""):
+ ok(name) if cond else bad(name, why)
+
+
+def start_daemon(extra=()):
+ env = dict(os.environ, PROXYBRIDGE_CONFIG_DIR=CFG)
+ p = subprocess.Popen([PB, "--daemon", "--socket", SOCK, "--verbose", "1"] + list(extra), env=env,
+ stdout=open(os.path.join(WORK, "daemon.out"), "ab"), stderr=subprocess.STDOUT)
+ procs.append(p)
+ for _ in range(80):
+ if os.path.exists(SOCK):
+ try:
+ pbd.Daemon.connect(SOCK, 2).close()
+ return p
+ except OSError:
+ pass
+ if p.poll() is not None:
+ break
+ time.sleep(0.1)
+ raise RuntimeError("daemon did not start: " + open(os.path.join(WORK, "daemon.out")).read())
+
+
+def stop_daemon(p):
+ p.send_signal(signal.SIGTERM)
+ try:
+ p.wait(10)
+ except subprocess.TimeoutExpired:
+ p.kill()
+ p.wait()
+
+
+def conn():
+ d = pbd.Daemon.connect(SOCK)
+ d.ok("hello", "1")
+ return d
+
+
+def curl(url, t=5):
+ r = subprocess.run(["curl", "-s", "-m", str(t), url], capture_output=True, text=True)
+ return r.returncode, r.stdout
+
+
+def cleanup():
+ for p in procs:
+ try:
+ p.kill()
+ except OSError:
+ pass
+ shutil.rmtree(WORK, ignore_errors=True)
+
+
+profile = lambda name, extra="": json.dumps({"Version": "1.0", "Name": name, "ProxyConfigs": [], "ProxyRules": []})
+
+try:
+ fake_log = os.path.join(WORK, "fake.log")
+ procs.append(subprocess.Popen([sys.executable, os.path.join(HERE, "fake_proxies.py"), fake_log], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
+ time.sleep(1)
+ d0 = start_daemon()
+
+ print("== a fresh service is idle")
+ d = pbd.Daemon.connect(SOCK)
+ st, f = d.req("hello", "1")
+ check("with Start at Boot off the engine is not started until a window asks", st == "ok" and f[1] == "0", (st, f))
+ check("Start at Boot is off by default", d.ok("boot.get") == ["0"])
+ d.close()
+ d0.send_signal(signal.SIGTERM); d0.wait(10)
+ d0 = start_daemon()
+
+ print("== socket and protocol")
+ st = os.stat(SOCK)
+ check("socket is reachable by everyone (access is decided by the service)", st.st_mode & 0o777 == 0o666, oct(st.st_mode))
+ check("socket folder is 0755", os.stat(os.path.dirname(SOCK)).st_mode & 0o777 == 0o755)
+ d = pbd.Daemon.connect(SOCK)
+ st, f = d.req("hello", "1")
+ check("hello answers with the version", st == "ok" and f[0].startswith("4."), (st, f))
+ st, f = d.req("hello", "999")
+ check("a different protocol version is refused with a clear message", st == "err" and "protocol mismatch" in f[0], (st, f))
+ st, f = d.req("no.such.command")
+ check("an unknown command is an error, not a crash", st == "err" and "unknown" in f[0], (st, f))
+ st, f = d.req("proxy.add", "only-one-arg")
+ check("wrong argument count is an error", st == "err" and "number of arguments" in f[0], (st, f))
+ st, f = d.req("proxy.delete", "abc")
+ check("a non-numeric id is an error", st == "err", (st, f))
+ d.close()
+
+ s = socket.socket(socket.AF_UNIX); s.connect(SOCK)
+ s.sendall(struct.pack(">I", 0x7fffffff) + b"junk")
+ s.settimeout(3)
+ try:
+ r = s.recv(10)
+ except OSError:
+ r = b""
+ check("an oversized frame closes the connection", r == b"")
+ s.close()
+ rnd = random.Random(7)
+ for i in range(60):
+ s = socket.socket(socket.AF_UNIX); s.connect(SOCK)
+ blob = bytes(rnd.getrandbits(8) for _ in range(rnd.randint(1, 300)))
+ if i % 3 == 0: # a valid length header around garbage
+ blob = struct.pack(">I", len(blob)) + blob
+ try:
+ s.sendall(blob)
+ except OSError:
+ pass
+ s.close()
+ time.sleep(1) # the limit is on windows connected at once; let the storm drain
+ d = conn()
+ check("the service survives random garbage on 60 connections", d.req("log.history")[0] == "ok")
+ d.close()
+ d = pbd.Daemon.connect(SOCK)
+ d.sock.sendall(pbd.encode([b"q", b"1", b"hello", b"1"])[:7]) # truncated frame, then a vanished peer
+ d.close()
+ d = conn()
+ check("the service survives a truncated frame", True)
+ d.close()
+ time.sleep(0.3)
+
+ print("== too many windows")
+ many = []
+ for i in range(16):
+ try:
+ many.append(conn())
+ except Exception as e:
+ bad("window %d of 16 is accepted" % (i + 1), e)
+ break
+ try:
+ extra = pbd.Daemon.connect(SOCK)
+ st, f = extra.req("hello", "1")
+ check("the 17th connection is refused", st == "err" and "too many" in f[0], (st, f))
+ extra.close()
+ except Exception as e:
+ check("the 17th connection is refused", False, e)
+ for m in many: m.close()
+ time.sleep(0.5)
+ d = conn(); check("slots are free again after they disconnect", True); d.close()
+
+ print("== access control")
+ code = (
+ "import os,sys,socket\nsys.path.insert(0,%r)\nimport pbd\nos.setgid(65534);os.setgroups([]);os.setuid(65534)\n"
+ "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)
+ made_group = subprocess.run(["getent", "group", "proxybridge"], capture_output=True).returncode != 0
+ if made_group:
+ subprocess.run(["groupadd", "-r", "proxybridge"], check=True)
+ try:
+ subprocess.run(["usermod", "-aG", "proxybridge", "nobody"], check=True)
+ r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
+ check("a member of the group 'proxybridge' is accepted at once, without logging in again", r.stdout.startswith("ok"), r.stdout + r.stderr)
+ subprocess.run(["gpasswd", "-d", "nobody", "proxybridge"], capture_output=True)
+ r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
+ check("removed from the group, the user is refused again", r.stdout.startswith("err"), r.stdout + r.stderr)
+ finally:
+ subprocess.run(["gpasswd", "-d", "nobody", "proxybridge"], capture_output=True)
+ if made_group:
+ subprocess.run(["groupdel", "proxybridge"], capture_output=True)
+ d = conn(); check("root is always accepted", True); d.close()
+
+ print("== profile store")
+ d = conn()
+ check("an empty store lists no profiles", d.ok("store.list") == [])
+ st, f = d.req("store.put", "bad", "this is not json")
+ check("a file that is not a profile is rejected", st == "err", (st, f))
+ st, f = d.req("store.put", "bad", '{"ProxyConfigs":[{"Type":"SOCKS5","Host":"h","Port":"70000"}]}')
+ check("a profile with a bad port is rejected", st == "err", (st, f))
+ st, f = d.req("store.put", "big", "x" * (5 << 20))
+ check("a profile over 4 MiB is rejected", st == "err", (st, f)[:2])
+ d.ok("store.put", "Work", profile("Work"))
+ d.ok("store.put", "Test/lab", profile("Test/lab"))
+ check("profiles are listed, sorted, with their real names", d.ok("store.list") == sorted(["Work", "Test/lab"]), d.ok("store.list"))
+ got = d.ok("store.get", "Test/lab")[0]
+ check("a profile reads back unchanged", json.loads(got)["Name"] == "Test/lab")
+ mode = os.stat(os.path.join(CFG, "profiles", "Test%2Flab.pbprofile")).st_mode & 0o777
+ check("profile files are private (0600) and a slash in a name is encoded", mode == 0o600, oct(mode))
+ check("the config folder is private (0700)", os.stat(CFG).st_mode & 0o777 == 0o700)
+ st, f = d.req("store.get", "../../etc/passwd")
+ check("a path in a profile name cannot escape the folder", st == "err" and not os.path.exists(os.path.join(CFG, "..", "..", "etc")), (st, f))
+ st, f = d.req("store.get", "nosuch")
+ check("an unknown profile is an error", st == "err")
+ d.ok("store.delete", "Work")
+ check("a deleted profile is gone", d.ok("store.list") == ["Test/lab"])
+ d.ok("store.delete", "Work")
+ check("deleting twice is harmless", True)
+ d.ok("store.settings.set", "Test/lab", "0", "1")
+ check("settings round-trip", d.ok("store.settings.get") == ["Test/lab", "0", "1"], d.ok("store.settings.get"))
+ d.ok("store.settings.set", "", "1", "0")
+ d.ok("store.delete", "Test/lab")
+ for i in range(520):
+ st, f = d.req("store.put", "p%03d" % i, profile("p"))
+ if st == "err":
+ break
+ check("the number of profiles is bounded", st == "err" and "too many" in f[0] and i <= 512, (i, st, f))
+ for i in range(520):
+ d.req("store.delete", "p%03d" % i)
+ d.close()
+
+ print("== engine: proxies, rules, traffic")
+ d = conn()
+ pid_a = int(d.ok("proxy.add", "fakeA", "1", "127.0.0.1", "19080", "", "")[0])
+ pid_b = int(d.ok("proxy.add", "fakeB", "1", "127.0.0.1", "19081", "bob", "pw")[0])
+ check("proxy ids are returned", pid_a > 0 and pid_b > 0 and pid_a != pid_b)
+ st, f = d.req("proxy.add", "x", "1", "", "1080", "", "")
+ check("an empty proxy host is refused", st == "err", (st, f))
+ rid = int(d.ok("rule.add", "curl", "192.0.2.0/24", "*", "0", "0", str(pid_a))[0])
+ rid2 = int(d.ok("rule.add", "curl", "198.51.100.0/24", "80;8080", "0", "0", str(pid_b))[0])
+ st, f = d.req("rule.add", "curl", "999.1.1.1", "*", "0", "0", str(pid_a))
+ check("a bad address is refused with the reason", st == "err" and f[0], (st, f))
+ check("rule.validate accepts a good rule", d.req("rule.validate", "curl", "10.0.0.0/8", "80")[0] == "ok")
+ check("rule.validate refuses a bad port", d.req("rule.validate", "curl", "*", "99999")[0] == "err")
+ d.ok("cfg.logging", "1")
+ d.ok("engine.start")
+ rc, out = curl("http://192.0.2.7/")
+ check("a rule routes curl through proxy A", "hello-from-A dst=192.0.2.7:80" in out, (rc, out))
+ rc, out = curl("http://198.51.100.7:8080/")
+ check("another rule routes through proxy B (with login)", "hello-from-B dst=198.51.100.7:8080" in out, (rc, out))
+ ev = d.wait_event(lambda e: e[0] == "conn" and e[1] == "curl" and e[4] == "80", 5)
+ check("connection events reach the window", ev is not None, d.events[-5:])
+ check("the event carries process, pid, address, port, protocol and route", ev and ev[2].isdigit() and ev[3] == "192.0.2.7" and ev[5] == "TCP" and "SOCKS5" in ev[6], ev)
+ d.ok("rule.disable", str(rid))
+ rc, out = curl("http://192.0.2.7/", 3)
+ check("a disabled rule stops routing", "hello-from" not in out, (rc, out))
+ d.ok("rule.enable", str(rid))
+ rc, out = curl("http://192.0.2.7/")
+ check("re-enabling routes again", "hello-from-A" in out, (rc, out))
+ d.ok("rule.edit", str(rid), "curl", "192.0.2.0/24", "*", "0", "0", str(pid_b))
+ rc, out = curl("http://192.0.2.7/")
+ check("editing a rule changes its proxy", "hello-from-B" in out, (rc, out))
+ d.ok("rule.move", str(rid2), "0")
+ d.ok("rule.delete", str(rid))
+ rc, out = curl("http://192.0.2.7/", 3)
+ check("a deleted rule stops routing", "hello-from" not in out, (rc, out))
+ rid3 = int(d.ok("rule.add", "curl", "203.0.113.0/24", "*", "0", "2", "0")[0])
+ rc, out = curl("http://203.0.113.5/", 3)
+ check("a Block rule refuses the connection", rc == 7 or "hello-from" not in out, (rc, out))
+ d.ok("rule.delete", str(rid3))
+
+ print("== live connections")
+ d.ok("rule.add", "python3*", "192.0.2.0/24", "8888", "0", "0", str(pid_a))
+ hold = socket.create_connection(("192.0.2.9", 8888), timeout=5)
+ hold.sendall(b"x")
+ time.sleep(1.5)
+ flows = d.ok("flows.get")
+ mine = [f.split("\t") for f in flows if f.split("\t")[1] == str(os.getpid())]
+ check("an open proxied connection is listed with its process, port and proxy", len(mine) == 1 and mine[0][6] == "8888" and mine[0][2] == str(pid_a), flows)
+ hold.sendall(b"y" * 5000); time.sleep(1.2)
+ again = [f.split("\t") for f in d.ok("flows.get") if f.split("\t")[1] == str(os.getpid())]
+ check("bytes sent are counted", again and int(again[0][4]) >= 5000, again)
+ hold.close()
+ time.sleep(1.5)
+ after = [f for f in d.ok("flows.get") if f.split("\t")[1] == str(os.getpid())]
+ check("a closed connection leaves the list", not after, after)
+
+ print("== batch")
+ d2 = conn()
+ d2.ok("batch.begin")
+ nid = int(d2.ok("rule.add", "curl", "192.0.2.0/24", "*", "0", "0", str(pid_a))[0])
+ rc, out = curl("http://192.0.2.7/", 3)
+ check("inside a batch a change does not reach the kernel yet", "hello-from" not in out, (rc, out))
+ d2.ok("batch.end")
+ rc, out = curl("http://192.0.2.7/")
+ check("when the batch ends the whole change arrives at once", "hello-from-A" in out, (rc, out))
+ d2.ok("rule.delete", str(nid))
+ d2.ok("batch.begin")
+ nid = int(d2.ok("rule.add", "curl", "192.0.2.0/24", "*", "0", "0", str(pid_a))[0])
+ d2.close() # the window dies in the middle of a batch
+ time.sleep(1)
+ rc, out = curl("http://192.0.2.7/")
+ check("a window that vanishes mid-batch does not leave the update held back", "hello-from-A" in out, (rc, out))
+ d.ok("rule.delete", str(nid))
+
+ print("== proxy test over the service")
+ st, f = d.req("proxy.test", str(pid_a), "example.com", "80", raw=False)
+ lines = d.lines.get(str(d.ids and (next(iter([k for k in d.lines])) )), [])
+ allines = [l for ls in d.lines.values() for l in ls]
+ check("the proxy test streams its report and returns a result", st == "ok" and any("Connecting to the proxy" in l for l in allines) and f[0] in ("0",), (st, f, allines[:3]))
+
+ print("== switches")
+ check("DNS via proxy switch", d.req("cfg.dns", "0")[0] == "ok" and d.req("cfg.dns", "1")[0] == "ok")
+ check("log every connection switch", d.req("cfg.logEvery", "1")[0] == "ok")
+ check("enable switch pauses the rules", d.req("cfg.enabled", "0")[0] == "ok")
+ rc, out = curl("http://198.51.100.7:8080/", 3)
+ check("while paused nothing is routed", "hello-from" not in out, (rc, out))
+ d.ok("cfg.enabled", "1")
+ rc, out = curl("http://198.51.100.7:8080/")
+ check("after resuming the rules apply again", "hello-from-B" in out, (rc, out))
+ check("a bad boolean is refused", d.req("cfg.dns", "yes")[0] == "err")
+ d.ok("engine.stop")
+ rc, out = curl("http://198.51.100.7:8080/", 3)
+ check("with the engine stopped traffic is direct (fail-open)", "hello-from" not in out, (rc, out))
+ d.ok("engine.start")
+ rc, out = curl("http://198.51.100.7:8080/")
+ check("the engine starts again with the same rules", "hello-from-B" in out, (rc, out))
+ h = d.ok("log.history")
+ check("the service keeps its recent log lines for windows that connect later", any("started" in l for l in h), h[-3:])
+ d.close()
+
+ print("== the service applies the active profile by itself at start")
+ stop_daemon(d0)
+ check("the socket is removed on a clean stop", not os.path.exists(SOCK))
+ rc, out = curl("http://198.51.100.7:8080/", 3)
+ check("after the service stops, traffic is direct", "hello-from" not in out, (rc, out))
+ prof = {"Version": "1.0", "Name": "boot", "DnsViaProxy": True,
+ "ProxyConfigs": [{"Id": 1, "Name": "A", "Type": "SOCKS5", "Host": "127.0.0.1", "Port": "19080", "Username": "", "Password": "", "SendDomainToProxy": True}],
+ "ProxyRules": [{"Name": "r", "ProcessName": "curl", "TargetHosts": "192.0.2.0/24", "TargetPorts": "*", "Protocol": "TCP", "Action": "PROXY", "IsEnabled": True, "ProxyConfigId": 1},
+ {"Name": "off", "ProcessName": "curl", "TargetHosts": "203.0.113.0/24", "TargetPorts": "*", "Protocol": "TCP", "Action": "PROXY", "IsEnabled": False, "ProxyConfigId": 1}]}
+ os.makedirs(os.path.join(CFG, "profiles"), exist_ok=True)
+ with open(os.path.join(CFG, "profiles", "boot.pbprofile"), "w") as fh:
+ json.dump(prof, fh)
+ os.chmod(os.path.join(CFG, "profiles", "boot.pbprofile"), 0o600)
+ with open(os.path.join(CFG, "settings.json"), "w") as fh:
+ json.dump({"ActiveProfileName": "boot", "CheckForUpdatesOnStartup": True, "StartAtBoot": True}, fh)
+ d1 = start_daemon()
+ time.sleep(1)
+ rc, out = curl("http://192.0.2.7/")
+ check("with no window open, the active profile is already routing", "hello-from-A dst=192.0.2.7:80" in out, (rc, out, open(os.path.join(WORK, "daemon.out")).read()[-600:]))
+ rc, out = curl("http://203.0.113.5/", 3)
+ check("a disabled rule of that profile is not applied", "hello-from" not in out, (rc, out))
+ d = conn()
+ h = d.ok("log.history")
+ check("a window that connects later can read what the service did at boot", any("profile 'boot' loaded" in l for l in h), h)
+ d.close()
+ stop_daemon(d1)
+
+ print("== a broken active profile does not stop the service")
+ with open(os.path.join(CFG, "profiles", "boot.pbprofile"), "w") as fh:
+ fh.write("{ not json")
+ d1 = start_daemon()
+ d = conn()
+ check("the service stays up and answers", d.req("log.history")[0] == "ok")
+ check("it says why in its log", any("cannot be loaded" in l for l in d.ok("log.history")))
+ d.close()
+ stop_daemon(d1)
+
+ print("== Start at Boot is a setting of the service")
+ with open(os.path.join(CFG, "profiles", "boot.pbprofile"), "w") as fh:
+ json.dump(prof, fh)
+ d1 = start_daemon()
+ d = conn()
+ d.ok("boot.set", "0")
+ check("boot.set stores the choice and boot.get reads it", d.ok("boot.get") == ["0"] and json.load(open(os.path.join(CFG, "settings.json")))["StartAtBoot"] is False)
+ check("the active profile name is kept when only the boot switch changes", json.load(open(os.path.join(CFG, "settings.json")))["ActiveProfileName"] == "boot")
+ d.close()
+ stop_daemon(d1)
+ d1 = start_daemon()
+ time.sleep(1)
+ rc, out = curl("http://192.0.2.7/", 3)
+ check("with Start at Boot off the service does not route by itself", "hello-from" not in out, (rc, out))
+ d = conn()
+ st, f = d.req("hello", "1")
+ check("and its engine is not running", f[1] == "0", f)
+ d.ok("boot.set", "1")
+ check("turned on", d.ok("boot.get") == ["1"])
+ d.close()
+ stop_daemon(d1)
+ d1 = start_daemon()
+ time.sleep(1)
+ rc, out = curl("http://192.0.2.7/")
+ check("with Start at Boot on it routes at once after a restart", "hello-from-A" in out, (rc, out))
+ d = conn()
+ check("and reports its engine as running", d.req("hello", "1")[1][1] == "1")
+ d.close()
+ 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)
+finally:
+ cleanup()
+print("\nPASS=%d FAIL=%d" % (PASS, FAIL))
+sys.exit(1 if FAIL else 0)
diff --git a/Linux/tests/e2e_daemon.sh b/Linux/tests/e2e_daemon.sh
new file mode 100755
index 0000000..8501736
--- /dev/null
+++ b/Linux/tests/e2e_daemon.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+# The ProxyBridge service (ProxyBridge --daemon): protocol, access control, profile store, engine control and routing, as root.
+# sudo Linux/tests/e2e_daemon.sh
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(dirname "$HERE")"
+PB_DIR="${PB_DIR:-$ROOT/output}"
+[ -x "$PB_DIR/ProxyBridge" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+export PB_DIR LD_LIBRARY_PATH="$PB_DIR"
+exec python3 "$HERE/e2e_daemon.py" "$@"
diff --git a/Linux/tests/e2e_service.py b/Linux/tests/e2e_service.py
new file mode 100755
index 0000000..8d376ae
--- /dev/null
+++ b/Linux/tests/e2e_service.py
@@ -0,0 +1,125 @@
+#!/usr/bin/env python3
+import os, sys, time, json, shutil, subprocess, tempfile, signal
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+import pbd
+
+PB = os.path.join(os.environ["PB_DIR"], "ProxyBridge")
+UNIT = "proxybridge-e2e.service"
+UNIT_PATH = "/run/systemd/system/" + UNIT
+INSTALL = "/opt/pbtest-e2e"
+CFG = "/var/lib/pbtest-e2e-cfg"
+SOCK = "/run/proxybridge/ctl.sock"
+PASS = FAIL = 0
+procs = []
+
+
+def check(name, cond, why=""):
+ global PASS, FAIL
+ if cond:
+ PASS += 1; print(" PASS " + name, flush=True)
+ else:
+ FAIL += 1; print(" FAIL %s %s" % (name, why), flush=True)
+
+
+def sc(*a):
+ return subprocess.run(["systemctl"] + list(a), capture_output=True, text=True)
+
+
+def wait_sock(gone=False, t=15):
+ for _ in range(int(t * 10)):
+ if os.path.exists(SOCK) != gone:
+ return True
+ time.sleep(0.1)
+ return False
+
+
+def curl(url, t=5):
+ r = subprocess.run(["curl", "-s", "-m", str(t), url], capture_output=True, text=True)
+ return r.stdout
+
+
+def cleanup():
+ sc("stop", UNIT)
+ for p in procs:
+ p.kill()
+ for p in (UNIT_PATH,):
+ try: os.unlink(p)
+ except OSError: pass
+ sc("daemon-reload")
+ shutil.rmtree(INSTALL, ignore_errors=True)
+ shutil.rmtree(CFG, ignore_errors=True)
+
+
+try:
+ os.makedirs(INSTALL, mode=0o755, exist_ok=True)
+ shutil.copy(PB, INSTALL + "/ProxyBridge")
+ os.chmod(INSTALL + "/ProxyBridge", 0o755)
+ os.makedirs(CFG, mode=0o700, exist_ok=True)
+ unit = subprocess.run([INSTALL + "/ProxyBridge", "--print-unit", INSTALL + "/ProxyBridge"], capture_output=True, text=True, check=True).stdout
+ check("--print-unit gives a unit that starts the daemon", "ExecStart=\"%s/ProxyBridge\" --daemon" % INSTALL in unit and "[Install]" in unit)
+ # the test's own configuration folder instead of /etc/proxybridge; every other line is the installer's
+ unit = unit.replace("ReadWritePaths=/etc/proxybridge", "ReadWritePaths=" + CFG).replace("[Service]\n", "[Service]\nEnvironment=PROXYBRIDGE_CONFIG_DIR=%s\n" % CFG)
+ open(UNIT_PATH, "w").write(unit)
+ r = subprocess.run(["systemd-analyze", "verify", UNIT_PATH], capture_output=True, text=True)
+ check("systemd accepts the unit without complaints about its settings", "Unknown" not in r.stderr and "Failed" not in r.stderr, r.stderr[:300])
+ sc("daemon-reload")
+
+ fake_log = tempfile.mktemp()
+ procs.append(subprocess.Popen([sys.executable, os.path.join(HERE, "fake_proxies.py"), fake_log], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
+ time.sleep(1)
+
+ print("== start")
+ r = sc("start", UNIT)
+ check("systemctl start succeeds", r.returncode == 0, r.stderr)
+ check("the socket appears in /run/proxybridge (RuntimeDirectory)", wait_sock())
+ st = os.stat(os.path.dirname(SOCK)).st_mode & 0o777
+ check("the folder is 0755 and the socket reachable by every user", st == 0o755 and os.stat(SOCK).st_mode & 0o777 == 0o666, oct(st))
+ check("the unit is active", sc("is-active", UNIT).stdout.strip() == "active")
+
+ d = pbd.Daemon.connect(SOCK)
+ st, f = d.req("hello", "1")
+ check("a client can talk to it", st == "ok", (st, f))
+
+ print("== the sandbox does not get in the way")
+ d.ok("store.put", "svc", json.dumps({"Version": "1.0", "Name": "svc", "ProxyConfigs": [], "ProxyRules": []}))
+ check("it can write its configuration folder", os.path.exists(CFG + "/profiles/svc.pbprofile"))
+ d.ok("boot.set", "1")
+ check("it can write settings.json", os.path.exists(CFG + "/settings.json"))
+ pid = int(d.ok("proxy.add", "A", "1", "127.0.0.1", "19080", "", "")[0])
+ d.ok("rule.add", "curl", "192.0.2.0/24", "*", "0", "0", str(pid))
+ d.ok("engine.start")
+ out = curl("http://192.0.2.7/")
+ check("it loads the eBPF programs and routes traffic under ProtectSystem=strict and NoNewPrivileges", "hello-from-A dst=192.0.2.7:80" in out, out)
+ out = subprocess.run(["systemctl", "show", UNIT, "-p", "MainPID", "--value"], capture_output=True, text=True).stdout.strip()
+ mainpid = int(out)
+ check("it runs as root", os.stat("/proc/%d" % mainpid).st_uid == 0)
+ nofile = [l for l in open("/proc/%d/limits" % mainpid) if l.startswith("Max open files")][0].split()
+ check("the raised open-file limit applies (LimitNOFILE)", int(nofile[3]) >= 1048576, nofile)
+ status = dict(l.split(":\t") for l in open("/proc/%d/status" % mainpid).read().splitlines() if ":\t" in l)
+ check("it cannot gain privileges (NoNewPrivileges)", status.get("NoNewPrivs", "").strip() == "1", status.get("NoNewPrivs"))
+ d.close()
+
+ print("== crash and restart")
+ os.kill(mainpid, signal.SIGKILL)
+ time.sleep(0.5)
+ out = curl("http://192.0.2.7/", 3)
+ check("when the service dies traffic goes direct at once (fail-open)", "hello-from" not in out, out)
+ check("systemd restarts it (Restart=on-failure)", wait_sock(t=20) and sc("is-active", UNIT).stdout.strip() == "active")
+ time.sleep(1)
+ d = pbd.Daemon.connect(SOCK)
+ check("its profiles survived the crash", "svc" in d.ok("store.list"))
+ check("and so did the Start at Boot choice", d.ok("boot.get") == ["1"])
+ d.close()
+
+ print("== stop")
+ r = sc("stop", UNIT)
+ check("systemctl stop succeeds quickly", r.returncode == 0)
+ check("the socket is removed", wait_sock(gone=True))
+ check("the unit is inactive", sc("is-active", UNIT).stdout.strip() == "inactive")
+ out = curl("http://192.0.2.7/", 3)
+ check("traffic is direct after stop", "hello-from" not in out, out)
+finally:
+ cleanup()
+print("\nPASS=%d FAIL=%d" % (PASS, FAIL))
+sys.exit(1 if FAIL else 0)
diff --git a/Linux/tests/e2e_service.sh b/Linux/tests/e2e_service.sh
new file mode 100755
index 0000000..005b9d0
--- /dev/null
+++ b/Linux/tests/e2e_service.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+# The ProxyBridge service under real systemd, with the exact unit the installer writes (sandboxing included): it starts, creates its
+# socket, loads the eBPF programs, routes traffic, keeps its profiles, restarts after a crash and stops cleanly.
+# Uses a volatile unit (/run/systemd/system) and a copy of the program under /opt; nothing is left behind.
+# sudo Linux/tests/e2e_service.sh
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(dirname "$HERE")"
+PB_DIR="${PB_DIR:-$ROOT/output}"
+[ -x "$PB_DIR/ProxyBridge" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+[ -d /run/systemd/system ] || { echo "SKIP: systemd is not running here"; exit 0; }
+[ ! -e /run/proxybridge/ctl.sock ] || { echo "SKIP: a ProxyBridge service is already running here"; exit 0; }
+export PB_DIR
+exec python3 "$HERE/e2e_service.py"
diff --git a/Linux/tests/gui_headless.sh b/Linux/tests/gui_headless.sh
index 887f890..e7d1834 100755
--- a/Linux/tests/gui_headless.sh
+++ b/Linux/tests/gui_headless.sh
@@ -89,7 +89,7 @@ grep -q '"ActiveProfileName": "Alt"' "$WORK/cfg/settings.json" && ok "settings.j
grep -q '"ProxyConfigs"' "$P/Default.pbprofile" && grep -q '"TargetDomains": "\*.example.test"' "$P/Default.pbprofile" && grep -q '"Version": "1.0"' "$P/Default.pbprofile" \
&& ok "the saved profile uses the Windows/macOS format (domain rule in TargetDomains)" || bad "profile format: $(head -40 "$P/Default.pbprofile")"
grep -q '"IsTrafficLoggingEnabled": true' "$P/Default.pbprofile" && grep -q '"DnsViaProxy": true' "$P/Default.pbprofile" \
- && [ "$(grep -c . "$WORK/cfg/settings.json")" -le 4 ] && ! grep -q Dns "$WORK/cfg/settings.json" \
+ && [ "$(grep -c . "$WORK/cfg/settings.json")" -le 5 ] && ! grep -q Dns "$WORK/cfg/settings.json" \
&& ok "logging and DNS switches live in the profile; settings.json only names the active profile" || bad "switches placement"
[ "$(stat -c %a "$P/Default.pbprofile")" = 600 ] && [ "$(stat -c %a "$P")" = 700 ] && ok "profile files are 0600 in a 0700 directory" || bad "profile permissions"
diff --git a/Linux/tests/gui_service.sh b/Linux/tests/gui_service.sh
new file mode 100755
index 0000000..436f5b4
--- /dev/null
+++ b/Linux/tests/gui_service.sh
@@ -0,0 +1,116 @@
+#!/bin/bash
+# The real ProxyBridgeGUI binary run by an UNPRIVILEGED user (Broadway, no desktop window) in front of a real ProxyBridge service:
+# access control, loading the profile from the service, routing with no root in the window, and what closing the window does.
+# sudo Linux/tests/gui_service.sh [dir with ProxyBridge, ProxyBridgeGUI and libproxybridge.so]
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+PB_DIR="${1:-${PB_DIR:-$ROOT/output}}"
+GUI="$PB_DIR/ProxyBridgeGUI"; PB="$PB_DIR/ProxyBridge"
+[ -x "$GUI" ] && [ -x "$PB" ] || { echo "Build first (Linux/build.sh) or pass the directory"; exit 1; }
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+command -v broadwayd >/dev/null && command -v setpriv >/dev/null || { echo "SKIP: needs broadwayd and setpriv"; exit 0; }
+[ ! -e /run/proxybridge/ctl.sock ] || { echo "SKIP: a ProxyBridge service is already running here"; exit 0; }
+WORK="$(mktemp -d)"; chmod 755 "$WORK"
+PASS=0; FAIL=0
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+MADE_GROUP=0
+cleanup() {
+ kill $GUI_PID 2>/dev/null; wait $GUI_PID 2>/dev/null; kill $DPID $FAKE $BW 2>/dev/null; wait 2>/dev/null
+ gpasswd -d nobody proxybridge >/dev/null 2>&1; [ $MADE_GROUP = 1 ] && groupdel proxybridge 2>/dev/null
+ rm -rf "$WORK" /run/proxybridge
+}
+GUI_PID=; DPID=; FAKE=; BW=
+trap cleanup EXIT
+getent group proxybridge >/dev/null || { groupadd -r proxybridge && MADE_GROUP=1; }
+
+python3 "$HERE/fake_proxies.py" "$WORK/proxy.log" >/dev/null 2>&1 & FAKE=$!
+mkdir -p "$WORK/cfg" "$WORK/home" "$WORK/bin" "$WORK/xdg"; chown nobody "$WORK/home" "$WORK/xdg"; chmod 700 "$WORK/xdg"
+# the display server belongs to the same unprivileged user as the window
+( ulimit -c 0; exec env XDG_RUNTIME_DIR="$WORK/xdg" HOME="$WORK/home" setpriv --reuid=nobody --regid=nogroup --clear-groups broadwayd :9 ) >/dev/null 2>&1 & BW=$!
+# the window runs as another user: it, and the library next to it, must be reachable by that user wherever the build lives
+install -m 755 "$GUI" "$WORK/bin/ProxyBridgeGUI"; install -m 755 "$PB_DIR/libproxybridge.so" "$WORK/bin/libproxybridge.so"
+GUI="$WORK/bin/ProxyBridgeGUI"
+sleep 1.5
+bpf_up() { "${BPFTOOL:-bpftool}" prog show 2>/dev/null | grep -q pb_connect4; }
+start_service() { PROXYBRIDGE_CONFIG_DIR="$WORK/cfg" "$PB" --daemon --verbose 1 > "$WORK/daemon.log" 2>&1 & DPID=$!
+ for _ in $(seq 40); do [ -S /run/proxybridge/ctl.sock ] && break; sleep 0.25; done; }
+stop_service() { kill $DPID 2>/dev/null; wait $DPID 2>/dev/null; DPID=; }
+seed() { # start-at-boot (0/1)
+python3 - "$1" <<PY
+import sys, json
+sys.path.insert(0, "$HERE")
+import pbd
+d = pbd.Daemon.connect("/run/proxybridge/ctl.sock"); d.ok("hello", "1")
+prof = {"Version": "1.0", "Name": "Default", "IsTrafficLoggingEnabled": True, "ProxyConfigs": [
+ {"Id": 1, "Name": "a", "Type": "SOCKS5", "Host": "127.0.0.1", "Port": "19080", "Username": "", "Password": "", "SendDomainToProxy": True}],
+ "ProxyRules": [{"Name": "r", "ProcessName": "curl", "TargetHosts": "192.0.2.0/24", "TargetPorts": "*", "Protocol": "TCP", "Action": "PROXY", "IsEnabled": True, "ProxyConfigId": 1}]}
+d.ok("store.put", "Default", json.dumps(prof))
+d.ok("store.settings.set", "Default", "1", sys.argv[1])
+PY
+}
+run_gui() { # user group-args...
+ local who="$1"; shift
+ GDK_BACKEND=broadway BROADWAY_DISPLAY=:9 HOME="$WORK/home" XDG_RUNTIME_DIR="$WORK/xdg" \
+ setpriv --reuid="$who" --regid=nogroup "$@" "$GUI" > "$WORK/gui.out" 2>&1 & GUI_PID=$!
+}
+wait_routing() { for _ in $(seq 40); do bpf_up && return 0; kill -0 $GUI_PID 2>/dev/null || return 1; sleep 0.25; done; return 1; }
+stop_gui() { kill -TERM $GUI_PID 2>/dev/null; for _ in $(seq 40); do kill -0 $GUI_PID 2>/dev/null || break; sleep 0.25; done
+ if kill -0 $GUI_PID 2>/dev/null; then kill -KILL $GUI_PID; bad "the window did not exit on SIGTERM"; else wait $GUI_PID; fi; GUI_PID=; }
+
+echo "== the service is running, the window is not root"
+start_service
+ok "service started (socket present)"
+seed 0
+out=$(curl -s -m 3 http://192.0.2.7/ 2>&1); [[ "$out" != *hello-from* ]] && ok "nothing is routed before a window asks (Start at Boot off)" || bad "routed without a window"
+
+echo "== a user who is not in the group"
+gpasswd -d nobody proxybridge >/dev/null 2>&1
+run_gui nobody --clear-groups
+sleep 3
+kill -0 $GUI_PID 2>/dev/null && ok "the window stays up showing its error (no crash)" || bad "window died: $(head -3 "$WORK/gui.out")"
+grep -q "refused a connection from user" "$WORK/daemon.log" && ok "the service refused that user and said so" || bad "no refusal in the service log"
+out=$(curl -s -m 3 http://192.0.2.7/ 2>&1); [[ "$out" != *hello-from* ]] && ok "a refused window changes nothing" || bad "routed for a refused user"
+kill -KILL $GUI_PID 2>/dev/null; wait $GUI_PID 2>/dev/null; GUI_PID=
+
+echo "== a member of the group (added just now, no new login)"
+usermod -aG proxybridge nobody
+run_gui nobody --clear-groups
+if wait_routing; then ok "the window started the engine through the service"; else bad "no routing: $(head -5 "$WORK/gui.out")"; fi
+sleep 1
+uid=$(stat -c %u /proc/$GUI_PID 2>/dev/null)
+[ -n "$uid" ] && [ "$uid" != 0 ] && ok "the window runs as an ordinary user (uid $uid)" || bad "window uid: $uid"
+out=$(curl -s -m 5 http://192.0.2.7/); [[ "$out" == *"hello-from-A dst=192.0.2.7:80"* ]] && ok "the profile held by the service routes traffic" || bad "not routed: $out"
+stop_gui
+sleep 1
+out=$(curl -s -m 3 http://192.0.2.7/ 2>&1); [[ "$out" != *hello-from* ]] && ok "Start at Boot off: closing the window stops routing" || bad "still routed after the window closed"
+
+echo "== Start at Boot on: routing continues after the window closes"
+python3 - <<PY
+import sys; sys.path.insert(0, "$HERE")
+import pbd
+d = pbd.Daemon.connect("/run/proxybridge/ctl.sock"); d.ok("hello", "1"); d.ok("boot.set", "1")
+PY
+run_gui nobody --clear-groups
+wait_routing && ok "window started" || bad "window did not start routing"
+sleep 1
+stop_gui
+sleep 1
+out=$(curl -s -m 5 http://192.0.2.7/); [[ "$out" == *"hello-from-A"* ]] && ok "the service keeps routing after the window closed" || bad "routing stopped with the window: $out"
+
+echo "== the service restarts: a fresh service applies the profile by itself"
+stop_service
+out=$(curl -s -m 3 http://192.0.2.7/ 2>&1); [[ "$out" != *hello-from* ]] && ok "stopping the service ends routing (fail-open)" || bad "routed with no service"
+start_service
+sleep 1.5
+out=$(curl -s -m 5 http://192.0.2.7/); [[ "$out" == *"hello-from-A"* ]] && ok "at start the service applies the active profile (Start at Boot on)" || bad "not applied at start: $out"
+stop_service
+
+echo "== no service at all, window run as a normal user"
+run_gui nobody --clear-groups
+sleep 3
+kill -0 $GUI_PID 2>/dev/null && ok "the window explains that the service is not running (does not crash or hang the desktop)" || bad "window died: $(head -3 "$WORK/gui.out")"
+kill -KILL $GUI_PID 2>/dev/null; wait $GUI_PID 2>/dev/null; GUI_PID=
+
+echo; echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ] || { echo "---- gui"; cat "$WORK/gui.out"; echo "---- service"; tail -20 "$WORK/daemon.log"; exit 1; }
diff --git a/Linux/tests/gui_ui.sh b/Linux/tests/gui_ui.sh
index 71be0e5..c834861 100755
--- a/Linux/tests/gui_ui.sh
+++ b/Linux/tests/gui_ui.sh
@@ -10,7 +10,8 @@ LIBDIR="${1:-${PB_DIR:-$ROOT/output}}"
WORK="$(mktemp -d)"
BUILD="${UI_BUILD_DIR:-$WORK}" # coverage runs keep the objects (and their .gcno files) here
mkdir -p "$BUILD"
-cleanup() { kill $FAKE $BW 2>/dev/null; wait 2>/dev/null; rm -rf "$WORK"; }
+cleanup() { kill $FAKE $BW $DAEMON 2>/dev/null; wait 2>/dev/null; rm -rf "$WORK"; }
+DAEMON=
trap cleanup EXIT
G="$ROOT/gui"
@@ -18,13 +19,39 @@ SRC=$(ls "$G"/*.c | grep -v "/main.c$")
gcc -O1 -g -w -D_GNU_SOURCE ${EXTRA_CFLAGS:-} -I"$ROOT/src" -I"$ROOT/profile" -I"$G" $(pkg-config --cflags gtk+-3.0) \
-DPB_TEST_HOOKS -Dmain=pb_gui_main -c "$G/main.c" -o "$BUILD/gui_main.o" || exit 1
gcc -O1 -g -w -D_GNU_SOURCE -DPB_TEST_HOOKS ${EXTRA_CFLAGS:-} -I"$ROOT/src" -I"$ROOT/profile" -I"$G" $(pkg-config --cflags gtk+-3.0) \
- -o "$BUILD/ui_test" "$G/tests/ui_test.c" "$BUILD/gui_main.o" $SRC "$ROOT/profile/pb_profile.c" \
+ -o "$BUILD/ui_test" "$G/tests/ui_test.c" "$BUILD/gui_main.o" $SRC "$ROOT/profile/pb_profile.c" "$ROOT/src/pb_ipc.c" "$ROOT/src/pb_unit.c" \
-L"$LIBDIR" -Wl,-rpath,"$LIBDIR" -lproxybridge -lpthread $(pkg-config --libs gtk+-3.0) ${EXTRA_LDFLAGS:-} || exit 1
python3 "$HERE/fake_proxies.py" "$WORK/proxy.log" > /dev/null 2>&1 & FAKE=$!
-( ulimit -c 0; exec broadwayd :8 ) > /dev/null 2>&1 & BW=$! # no core dump: apport would pop up a crash report when the daemon aborts on a client that vanished
-sleep 1.5
-mkdir -p "$WORK/cfg"
-GDK_BACKEND=broadway BROADWAY_DISPLAY=:8 PROXYBRIDGE_CONFIG_DIR="$WORK/cfg" LD_LIBRARY_PATH="$LIBDIR" \
- timeout 300 "$BUILD/ui_test" 2>&1 | grep -v "^$\|Gtk-WARNING\|GLib-GIO\|dconf"
-exit "${PIPESTATUS[0]}"
+BW=
+run_ui() { # $1 = label; the environment says whether the window talks to a service
+ echo "== window: $1"
+ # A display server of its own for every run: broadwayd aborts when its client disappears, so one cannot serve two runs.
+ # (no core dump: apport would pop up a crash report for that abort)
+ ( ulimit -c 0; exec broadwayd :8 ) > /dev/null 2>&1 & BW=$!
+ sleep 1.5
+ GDK_BACKEND=broadway BROADWAY_DISPLAY=:8 LD_LIBRARY_PATH="$LIBDIR" \
+ timeout 300 "$BUILD/ui_test" 2>&1 | grep -v "^$\|Gtk-WARNING\|GLib-GIO\|dconf"
+ local rc="${PIPESTATUS[0]}"
+ kill $BW 2>/dev/null; wait $BW 2>/dev/null; BW=
+ sleep 0.5
+ return "$rc"
+}
+
+rc=0
+if [ "${UI_MODES:-both}" != service ]; then
+ mkdir -p "$WORK/cfg"
+ PROXYBRIDGE_CONFIG_DIR="$WORK/cfg" run_ui "its own engine (root, no service)" || rc=1
+fi
+if [ "${UI_MODES:-both}" != embedded ] && [ -x "$LIBDIR/ProxyBridge" ]; then
+ # the same suite, every engine and profile call going over the socket to a ProxyBridge --daemon
+ mkdir -p "$WORK/cfg2" "$WORK/run"
+ chmod 755 "$WORK" "$WORK/run"
+ PROXYBRIDGE_CONFIG_DIR="$WORK/cfg2" LD_LIBRARY_PATH="$LIBDIR" \
+ "$LIBDIR/ProxyBridge" --daemon --socket "$WORK/run/ctl.sock" --verbose 1 > "$WORK/daemon.log" 2>&1 & DAEMON=$!
+ for _ in $(seq 40); do [ -S "$WORK/run/ctl.sock" ] && break; sleep 0.25; done
+ PROXYBRIDGE_CONFIG_DIR="$WORK/cfg2" PROXYBRIDGE_SOCKET="$WORK/run/ctl.sock" \
+ run_ui "through the service" || rc=1
+ kill "$DAEMON" 2>/dev/null; wait "$DAEMON" 2>/dev/null
+fi
+exit $rc
diff --git a/Linux/tests/pbd.py b/Linux/tests/pbd.py
new file mode 100644
index 0000000..73d8912
--- /dev/null
+++ b/Linux/tests/pbd.py
@@ -0,0 +1,130 @@
+"""Client for the ProxyBridge service protocol (src/pb_ipc.h), used by the tests.
+
+ d = Daemon.connect(path)
+ status, fields = d.req("proxy.add", "name", "1", "127.0.0.1", "1080", "", "")
+ d.events # list of ("log", msg) / ("conn", process, pid, ip, port, proto, via)
+"""
+import socket, struct, threading, queue, itertools
+
+
+def encode(fields):
+ body = struct.pack(">H", len(fields))
+ for f in fields:
+ b = f if isinstance(f, bytes) else str(f).encode()
+ body += struct.pack(">I", len(b)) + b
+ return struct.pack(">I", len(body)) + body
+
+
+def read_frame(sock):
+ hdr = b""
+ while len(hdr) < 4:
+ c = sock.recv(4 - len(hdr))
+ if not c:
+ return None
+ hdr += c
+ (n,) = struct.unpack(">I", hdr)
+ buf = b""
+ while len(buf) < n:
+ c = sock.recv(n - len(buf))
+ if not c:
+ return None
+ buf += c
+ (cnt,) = struct.unpack(">H", buf[:2])
+ pos, out = 2, []
+ for _ in range(cnt):
+ (l,) = struct.unpack(">I", buf[pos:pos + 4])
+ pos += 4
+ out.append(buf[pos:pos + l])
+ pos += l
+ return out
+
+
+class Daemon:
+ def __init__(self, sock):
+ self.sock = sock
+ self.ids = itertools.count(1)
+ self.events = []
+ self.pending = {}
+ self.lines = {}
+ self.cv = threading.Condition()
+ self.dead = False
+ self.first = None # a response with id 0 (refusal) arrives before any request
+ threading.Thread(target=self._read, daemon=True).start()
+
+ @classmethod
+ def connect(cls, path, timeout=10):
+ s = socket.socket(socket.AF_UNIX)
+ s.settimeout(timeout)
+ s.connect(path)
+ s.settimeout(None)
+ return cls(s)
+
+ def _read(self):
+ while True:
+ try:
+ f = read_frame(self.sock)
+ except OSError:
+ f = None
+ if f is None:
+ with self.cv:
+ self.dead = True
+ self.cv.notify_all()
+ return
+ kind = f[0].decode(errors="replace")
+ with self.cv:
+ if kind == "e":
+ self.events.append(tuple(x.decode(errors="replace") for x in f[1:]))
+ elif kind == "r":
+ rid = f[1].decode()
+ if len(f) > 2 and f[2] == b"line":
+ self.lines.setdefault(rid, []).append(f[3].decode(errors="replace"))
+ else:
+ self.pending[rid] = f[2:]
+ self.cv.notify_all()
+
+ def req(self, cmd, *args, timeout=20, raw=False):
+ rid = str(next(self.ids))
+ try:
+ self.sock.sendall(encode([b"q", rid.encode(), cmd.encode()] + [a if isinstance(a, bytes) else str(a).encode() for a in args]))
+ except OSError:
+ pass # the service may already have refused us and closed; its refusal is waiting to be read
+ return self._wait(rid, timeout, raw)
+
+ def _wait(self, rid, timeout, raw=False):
+ with self.cv:
+ if not self.cv.wait_for(lambda: rid in self.pending or self.dead or "0" in self.pending, timeout):
+ raise TimeoutError("no answer to request " + rid)
+ r = self.pending.pop(rid, None) or self.pending.get("0")
+ if r is None:
+ raise ConnectionError("connection closed")
+ status = r[0].decode()
+ return status, (r[1:] if raw else [x.decode(errors="replace") for x in r[1:]])
+
+ def ok(self, cmd, *args, **kw):
+ st, f = self.req(cmd, *args, **kw)
+ if st != "ok":
+ raise AssertionError("%s failed: %s" % (cmd, f))
+ return f
+
+ def wait_event(self, pred, timeout=10):
+ with self.cv:
+ end = [None]
+
+ def check():
+ return any(pred(e) for e in self.events) or self.dead
+ if not self.cv.wait_for(check, timeout):
+ return None
+ for e in self.events:
+ if pred(e):
+ return e
+ return None
+
+ def close(self):
+ try:
+ self.sock.shutdown(socket.SHUT_RDWR) # the reader thread is blocked in recv(): close() alone would not end the connection
+ except OSError:
+ pass
+ try:
+ self.sock.close()
+ except OSError:
+ pass