Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic
C ccybersecurityhttp3httpproxylinuxlinux-proxymacosmacos-appmacos-proxyproxifierproxifier-alternativeproxyclienttcpthick-clientudpwindivertwindows
security(linux): pre-release hardening from the vulnerability assessment
anof-cyberf9ab62330836
diff --git a/.github/workflows/release-linux.yml b/.github/workflows/release-linux.ymlindex 7d30d14..86d5986 100644--- a/.github/workflows/release-linux.yml+++ b/.github/workflows/release-linux.yml@@ -114,7 +114,6 @@ jobs:- name: Create release archiverun: |- VERSION="${{ steps.version.outputs.version }}"ARCHIVE_NAME="ProxyBridge-Linux-v${VERSION}.tar.gz"echo "Creating archive: $ARCHIVE_NAME"@@ -127,7 +126,12 @@ jobs:# Move archive to root for uploadmv "../$ARCHIVE_NAME" "../../$ARCHIVE_NAME"+ cd ../..+ sha256sum "$ARCHIVE_NAME" > "$ARCHIVE_NAME.sha256"+ cat "$ARCHIVE_NAME.sha256"shell: bash+ env:+ VERSION: ${{ steps.version.outputs.version }}- name: List release filesrun: |@@ -144,7 +148,7 @@ jobs:- name: Upload archive to releaserun: |- gh release upload "$TAG" ProxyBridge-Linux-v*.tar.gz --clobber+ gh release upload "$TAG" ProxyBridge-Linux-v*.tar.gz ProxyBridge-Linux-v*.tar.gz.sha256 --clobbershell: bashenv:GH_TOKEN: ${{ github.token }}@@ -154,5 +158,7 @@ jobs:uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4with:name: ProxyBridge-Linux-Release-${{ steps.version.outputs.version }}- path: ProxyBridge-Linux-*.tar.gz+ path: |+ ProxyBridge-Linux-*.tar.gz+ ProxyBridge-Linux-*.tar.gz.sha256retention-days: 90diff --git a/Linux/README.md b/Linux/README.mdindex 7eb783d..60f1800 100644--- a/Linux/README.md+++ b/Linux/README.md@@ -239,8 +239,14 @@ Add as many proxies as you need (GUI or profile); each rule chooses its own. Pro## Security model- **Redirected TCP connections** are bound to the client's source address and port. A process that connects to the relay from a different loopback address (for example `127.0.0.2`) cannot claim another process's pending flow, and an entry is consumed on first use.-- **Redirected UDP flows** are addressed by a loopback flow address that the relay maps back to the original destination. These addresses are not secret (they are visible in `/proc/net/udp`), so on a **multi-user host** another local user can send datagrams to the relay's UDP port and have them forwarded to a destination that some other process is already talking to, through the same proxy. Run ProxyBridge on machines you trust locally.-- A rule that needs a proxy that does not exist **blocks** instead of letting traffic through.+- **Redirected UDP flows** are addressed by a loopback flow address that the relay maps back to the original destination and to the process that opened it. These addresses are not secret (they are visible in `/proc/net/udp`), so the relay checks, for every new client port, that the sender really is that process (it owns a UDP socket on that port and is still the same executable); datagrams from anyone else are dropped. A process that opens UDP sockets at a high rate displaces only its own oldest sessions, never other programs'.+- **Decisions made in user space** (long host lists, domain rules) use the executable the kernel recorded when the connection was opened, not `/proc/<pid>/exe` looked up later, so a process that exits and has its PID reused cannot change a pending decision.+- **The DNS tap** only learns from answer records that belong to the question (the asked name, CNAMEs chained from it, and A records owned by those names); unrelated records in a response are ignored. Note that any local process whose DNS passes through the relay can still teach the engine a name→address mapping for *its own* lookups, and domain rules are matched by address, so on a shared host another user's resolver answers can influence which addresses a domain rule matches. Run ProxyBridge on machines you trust locally.+- **A local proxy is exempted** (its own connections go direct) when a process listens on the configured proxy address and port. While that port is free, for example because the proxy is not running yet, any local process that binds it is treated as the proxy. Point rules at proxies that are running, or at a proxy on another host, when other users share the machine.+- **Fail-open on exit.** The kernel removes the eBPF programs when ProxyBridge stops or crashes. From that moment traffic flows normally: `BLOCK` rules no longer block and nothing is proxied. ProxyBridge is a routing tool, not a firewall; use the "start at boot" service (which restarts it on failure) and a real firewall for enforcement.+- A rule that needs a proxy that does not exist **blocks** instead of letting traffic through. A connection whose proxy handshake fails is closed, never sent direct.+- **Start at boot** writes `/etc/systemd/system/proxybridge.service` with the absolute path of the active profile file and of the `ProxyBridge` binary. The binary is accepted only when it and every directory above it belong to root and are writable by root only (so an install under `/usr/local/bin`, not a copy run from a home directory); the unit runs with `NoNewPrivileges`, `ProtectSystem=strict`, `ProtectHome=read-only` and `PrivateTmp`.+- Anything shown in the log that another local user controls (an executable's name, a DNS name) has control characters replaced before it reaches the terminal or the GUI, and profiles that contain control characters in any field are rejected.- The relay listens on loopback only (UDP is additionally bound to the `lo` device). Other network namespaces (containers) are never redirected.- Proxy passwords are kept in the profile files under `/etc/proxybridge/profiles/` (mode 0600, directory 0700, root). Credentials are never taken from the command line, so they cannot show up in the process list or shell history.@@ -437,9 +443,14 @@ gcc -o ProxyBridge main.o \## Uninstallation-To remove ProxyBridge from your system:+To remove ProxyBridge from your system, run `sudo ./setup.sh --uninstall` from the extracted release (add `--purge` to delete the profiles under `/etc/proxybridge` too), or by hand:```bash+# Stop and remove the boot service, if it was enabled in the GUI+sudo systemctl disable --now proxybridge.service 2>/dev/null+sudo rm -f /etc/systemd/system/proxybridge.service+sudo systemctl daemon-reload+# Remove binariessudo rm -f /usr/local/bin/ProxyBridgesudo rm -f /usr/local/bin/ProxyBridgeGUI@@ -458,7 +469,9 @@ sudo rm -f /etc/ld.so.conf.d/proxybridge.confsudo ldconfig```-**Cleanup after crash:** nothing to do. ProxyBridge attaches its eBPF programs through BPF links, which the kernel removes when the process exits or crashes. To check: `sudo bpftool cgroup tree /sys/fs/cgroup` should list no `pb_*` programs.+**Cleanup after crash:** nothing to do. ProxyBridge attaches its eBPF programs through BPF links, which the kernel removes when the process exits or crashes (traffic then flows normally, see [Security model](#security-model)). To check: `sudo bpftool cgroup tree /sys/fs/cgroup` should list no `pb_*` programs.++**Verifying a download:** every release carries a `.sha256` file next to the tarball: `sha256sum -c ProxyBridge-Linux-v*.tar.gz.sha256`.## Licensediff --git a/Linux/SECURITY_AUDIT.md b/Linux/SECURITY_AUDIT.mdnew file mode 100644index 0000000..930b847--- /dev/null+++ b/Linux/SECURITY_AUDIT.md@@ -0,0 +1,171 @@+# ProxyBridge for Linux — pre-release security assessment (2026-10-20)++Scope: everything under `Linux/` as of commit 5f307c2 on `dev`: the eBPF program and its loader, the userspace relay+(SOCKS5/HTTP/UDP), the DNS tap, the rule engine, `/proc` scanning, the `.pbprofile` parser, the CLI, the GTK GUI, the+"start at boot" systemd unit, `setup.sh`, `build.sh` and the GitHub workflows. Four independent code reviews, one per area,+plus a 4-minute mutation fuzz of the profile parser (3.1 million inputs under ASan/UBSan, no crash) and `readelf`+checks of the shipped binaries.++Threat model: the engine runs as root on a desktop or shared host. Untrusted inputs are the proxy server's bytes, DNS+answers, the contents of `/proc` for other users' processes, other local users' processes (which may try to bypass their+own rules, hijack another process's flow, or exhaust the daemon), imported profile files, the update feed, and the+command line / environment.++**Result:** no memory-safety bug was found in any parser (SOCKS5, HTTP CONNECT, DNS decompression, UDP SOCKS header,+JSON). All findings concern trust between local processes, what the root daemon accepts from remote text, and the+boot service. Everything below marked *fixed* was fixed in the commit that follows this document; three design+limitations are documented in the README instead.++## Findings and fixes++### 1. Boot service could run a user-writable binary as root — medium, fixed+`gui/gui_boot.c`. The unit's `ExecStart` pointed at the `ProxyBridge` binary next to the running GUI. The README+encourages `sudo ./ProxyBridgeGUI` from the extracted tarball, so ticking "Start at Boot" from `~/Downloads/pb/`+produced a root service that executes `~/Downloads/pb/ProxyBridge` (and loads `libproxybridge.so` from the same+directory via `$ORIGIN`) at every boot. Anything that later gains write access to that user account owns root at boot.+**Fix:** the GUI accepts the binary only when it and every directory above it belong to root and are writable by root+only (`boot_path_trusted`), otherwise it refuses with "install ProxyBridge with setup.sh". Unit test added.++### 2. Boot service loaded the profile by *name* — medium, fixed+`gui/gui_boot.c`, `profile/pb_profile.c` (`pbp_resolve`). The unit contained `--profile "<name>"`. A name containing+`/` (typed, or carried in an imported file's `"Name"`) is a relative path, resolved against the service's working+directory `/`, so a profile named `tmp/.w.pbprofile` made the root CLI load `/tmp/.w.pbprofile` at boot — a file any+local user can create, redirecting all matching traffic to their proxy. **Fix:** the unit now carries the absolute path+of the stored profile file; `boot_unit_text` refuses relative paths.++### 3. `--profile name.pbprofile` shadowed by a file in the current directory — low, fixed+`pbp_resolve` tried a bare name ending in `.pbprofile` as a relative path first. `sudo ProxyBridge --profile Work.pbprofile`+run from `/tmp` loaded an attacker's `/tmp/Work.pbprofile` instead of the GUI profile. **Fix:** anything without `/` is a+profile name; a file in the current directory needs `./`.++### 4. Systemd unit ran unconfined — low, fixed+The unit had only `Type=simple`/`Restart=on-failure`. **Fix:** `NoNewPrivileges`, `ProtectSystem=strict`,+`ProtectHome=read-only`, `PrivateTmp`, `ProtectKernelModules`, `ProtectKernelLogs`, `ProtectClock`, `RestrictSUIDSGID`,+`LockPersonality`, `RestrictRealtime`. (Root and the eBPF capabilities are still needed; a capability bounding set was+not added without a real boot test.)++### 5. Uninstall left an enabled root service behind — low, fixed+The README's uninstall steps did not remove `/etc/systemd/system/proxybridge.service`. **Fix:** `setup.sh --uninstall+[--purge]` and README steps that disable and remove the unit.++### 6. Any local process could send UDP through another process's flow — medium, fixed+`src/pb_relay.c` (`udp_dgram`), `src/bpf/proxybridge.bpf.c` (`udp_flow_addr`). Redirected UDP is addressed to a+loopback "flow address" (127.x.y.z) that the relay maps back to the real destination. The relay never checked who sent+the datagram, and the address is a deterministic hash that is also visible in `/proc/net/udp`. A process whose own+traffic is BLOCKed could send to a flow address used by an allowed process and have its payload relayed through the+proxy with the configured credentials, logged as the victim. **Fix:** every flow address is now per process (pid in the+hash), and for each new client port the relay verifies through `/proc/net/udp{,6}` and `/proc/<pid>/fd` that the sender+holds a UDP socket on that port and is still the same executable (`pb_core_udp_sender_ok`); other senders are dropped.+Relay unit test added (impostor gets nothing, owner keeps working).++### 7. UDP session table exhaustion by one process — medium, fixed+1024 sessions total; one process sending from 1024 source ports filled the table, starving everyone else's UDP.+**Fix:** one process may hold at most a quarter of the table (together with fix 6, a process can only use its own flows).++### 8. Flow-address probe exhaustion borrowed another flow's address — low, fixed+In the eBPF program, when all 8 probed slots were occupied by other live flows, the loop fell through and returned the+last computed address — another flow's — so the datagram would have been delivered to another process's destination.+**Fix:** the send is refused (EPERM) instead.++### 9. Userspace decisions trusted a possibly reused PID — high (plausible), fixed+`src/ProxyBridge.c` (`pb_core_decide`). Flows the kernel cannot decide itself (long host lists, domain rules) are+decided by the relay later. It identified the program by reading `/proc/<pid>/exe` *first* and only fell back to the+executable identity the kernel had captured at `connect()`. If the process exited and its PID was reused before the+relay ran, the rule was evaluated against the new program. **Fix:** the kernel-captured identity (device + inode) is+preferred; `/proc` is the fallback.++### 10. DNS tap learned from unrelated answer records — medium, fixed+`src/pb_dns.c`. Every A record and every CNAME in a response was attached to every address in it, regardless of the+question. A response `q.example A 1.1.1.1; allowed.corp A 6.6.6.6; victim.bank CNAME …` taught the engine that all+three names belong to both addresses, which steers domain rules and, with "send domain to proxy", the host name the+proxy is asked to connect to. **Fix:** only the question name, CNAME targets chained from it, and A records owned by+those names are used. Unit test added.++### 11. SOCKS5 UDP ASSOCIATE relay address pointed at this host — low, fixed+A remote proxy could answer `BND.ADDR = 127.0.0.1:<port>`, making the root relay send application payloads to local+services. **Fix:** a loopback relay address is accepted only when the proxy itself is on loopback.++### 12. Exponential glob in log filters — high, fixed+`profile/pb_profile.c` (`ci_glob`). The filter matcher backtracked exponentially on patterns with many `*`. A filter+`*a*a*a*…*b` from an imported profile took 8 s *per connection event* while holding the engine's callback lock — one+crafted profile froze logging and the GUI. **Fix:** linear single-backtrack glob (the engine's own algorithm); timing+test added.++### 13. Control characters from profiles and the update feed reached the terminal — medium, fixed+The JSON parser accepted raw bytes 0x01–0x1F and `\u001b`, `\n`, `\u0007` etc. in any string. A proxy `Host` or `Name`+with `ESC]0;…BEL` set the operator's terminal title; a newline forged extra log lines; the update feed's `version`+field was printed raw (a MITM could inject escape sequences into the root operator's terminal). **Fix:** profiles with+control characters in any field are rejected; the feed `version` must be a plain version string (≤ 32 chars of+`[0-9A-Za-z.+-]`); the engine replaces control characters in anything it hands to the log and connection callbacks+(executable names, DNS names).++### 14. JSON parser leniency that diverges from Windows/.NET — low, fixed+`"Port": 1080e1` was read as 1080 (Windows reads 10800); `8.9` as 8; duplicate keys took the first value (Windows+takes the last), so a file could look different to a reviewer on Windows than what Linux applied. **Fix:** non-integral+numbers and duplicate keys (case-insensitive) are rejected.++### 15. Proxy Id wrap — low, fixed+`"Id": 4294967295` made the next auto-assigned id 0, which means "default proxy" everywhere. **Fix:** ids ≥ 2^31 are+rejected.++### 16. Double `close()` in profile writing — low, fixed+On a failed `rename`, the descriptor was closed twice; in the multithreaded GUI that can close an unrelated,+freshly reused descriptor. Fixed.++### 17. curl argument handling — low, fixed+The feed URL (overridable through `PROXYBRIDGE_UPDATE_FEED` in the CLI, test hook in the GUI) was passed to curl+without `--`, and any protocol was allowed. **Fix:** `--proto =https,file -- <url>`; the environment override is+ignored when running set-uid (`AT_SECURE`); `PROXYBRIDGE_CONFIG_DIR` uses `secure_getenv`.++### 18. GUI update check — low, fixed+The GUI parsed the feed with `strstr` and could hand any https URL to the browser, which runs as root. **Fix:** the GUI+uses the same strict parser and version comparison as the CLI, and only opens pages under `github.com/InterceptSuite/`+or `interceptsuite.com`.++### 19. Exported profiles unreadable by the user who exported them — low, fixed+Exports are written as root with mode 0600, so under `sudo` the invoking user cannot open their own export. **Fix:**+when started through `sudo`/`pkexec` and the destination directory belongs to the invoking user, the file is handed to+that user.++### 20. Release integrity — low, fixed+Release tarballs had no checksum, and the version from the manual `tag` input was interpolated into a shell script+(template-injection pattern; mitigated by the actor check). **Fix:** a `.sha256` file is published with each tarball and+the version is passed through `env`.++### 21. Smaller relay items — fixed+- Credentials copied onto worker stacks (`ab[]`, `cred[]`, `enc[]`, request buffer) are wiped with `explicit_bzero`.+- The "no original destination for client" log (triggered by anyone connecting to the relay port) is rate-limited.+- `teardown()` now takes the data-thread mutex while freeing connection lists that `pb_relay_flows()` may be walking.+- `setup.sh` installs with `install -o root -g root -m 0755` (a pre-existing file's owner is never kept) and creates+ `/etc/proxybridge` 0700.++## Documented design limitations (README → Security model)++- **Fail-open on exit.** The kernel removes the eBPF programs when ProxyBridge stops or crashes; from then on+ `BLOCK` rules no longer block and nothing is proxied. ProxyBridge is a routing tool, not a firewall.+- **Local-proxy exemption by listening port.** A process that listens on the configured proxy address and port is+ treated as the proxy and its connections go direct. While that port is free (proxy not running), any local process+ that binds it is exempted. Point rules at running proxies, or at a proxy on another host, on shared machines.+- **DNS tap mappings are per address, not per process.** A process's own DNS answers (now bailiwick-checked) still+ teach the engine name→address pairs that domain rules of other processes match by address.+- Running out of `exe2class` map space (16384 distinct executables) degrades unknown programs to the slower userspace+ decision path; decisions stay correct.++## Verified as solid+SOCKS5 greeting/auth/reply and HTTP CONNECT parsers (bounded, status checked before address), DNS name decompression+(hop limit, pointer bounds), UDP SOCKS header parsing, TCP-DNS framing, fd lifecycle in every relay error path,+handshake deadlines and worker-pool shedding, relay sockets bound to loopback only (UDP additionally to `lo` with an+`IP_PKTINFO` 127/8 filter), fail-closed on handshake failure, missing proxy and BLOCK; cgroup v2 root attach with+`ALLOW_MULTI`, v4-mapped v6 handling, implicit-direct consistency between kernel and userspace, first-match rule+ordering (covered by the 4800-case differential test); JSON nesting depth and node limits, surrogate handling,+file/proxy/rule/filter limits enforced before allocation, atomic 0600 writes via `mkstemp`+`rename`, percent-encoded+profile file names (no traversal); GTK markup only through `g_markup_printf_escaped`, `%s` everywhere a dialog shows+data, systemd quoting with control-character rejection, `systemctl`/`curl` spawned with fixed argv; all three binaries+PIE, full RELRO, BIND_NOW, NX, stack protector, FORTIFY_SOURCE=3, CET; actions SHA-pinned; libbpf source fetch+checksum-verified.++## Tests added+`profile_test`: control characters, non-integral numbers, duplicate keys, Id range, glob timing bound, strict+`pbp_resolve`, feed version validation. `dns_test`: out-of-bailiwick records. `relay_test`: impostor UDP sender.+`boot_test`: absolute profile path, hardening directives, `boot_path_trusted`. `ui_test`: escape sequences in the feed,+foreign download host refused. `e2e_cli`: unchanged surface, still 48/48.diff --git a/Linux/cli/main.c b/Linux/cli/main.cindex 16c6090..f48eeae 100644--- a/Linux/cli/main.c+++ b/Linux/cli/main.c@@ -6,6 +6,7 @@#include <stdbool.h>#include <sys/stat.h>#include <sys/wait.h>+#include <sys/auxv.h>#include "../src/ProxyBridge.h"#include "../profile/pb_profile.h"@@ -86,7 +87,7 @@ static bool is_https(const char* url)/* --update: ask the feed with curl and print what it says. Nothing is downloaded or run. */static int check_update(void){- const char* feed = getenv("PROXYBRIDGE_UPDATE_FEED"); /* a mirror, or a local file in tests */+ const char* feed = getauxval(AT_SECURE) ? NULL : getenv("PROXYBRIDGE_UPDATE_FEED"); /* a mirror, or a local file in tests; never under setuid */if (!feed || !*feed)feed = UPDATE_FEED;int fds[2];@@ -101,7 +102,7 @@ static int check_update(void)dup2(fds[1], STDOUT_FILENO);close(fds[0]);close(fds[1]);- execlp("curl", "curl", "-sS", "-m", "15", "-H", "User-Agent: ProxyBridge-UpdateChecker", feed, (char*)NULL);+ execlp("curl", "curl", "-sS", "-m", "15", "--proto", "=https,file", "-H", "User-Agent: ProxyBridge-UpdateChecker", "--", feed, (char*)NULL);_exit(127);}close(fds[1]);diff --git a/Linux/gui/gui.h b/Linux/gui/gui.hindex 4c000de..72c7031 100644--- a/Linux/gui/gui.h+++ b/Linux/gui/gui.h@@ -138,4 +138,7 @@ void on_search_log_changed(GtkSearchEntry *entry, gpointer user_data);void on_clear_conn_clicked(GtkButton *button, gpointer user_data);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);+#endifdiff --git a/Linux/gui/gui_boot.c b/Linux/gui/gui_boot.cindex b146dd2..eab4157 100644--- a/Linux/gui/gui_boot.c+++ b/Linux/gui/gui_boot.c@@ -4,6 +4,7 @@#include <string.h>#include <sys/stat.h>#include <unistd.h>+#include <errno.h>#define UNIT_NAME "proxybridge.service"@@ -25,22 +26,55 @@ static const char *systemctl_cmd() {static char *unit_path() { return g_strdup_printf("%s/" UNIT_NAME, unit_dir()); }+// A program that systemd will start as root at every boot must not be replaceable by an ordinary user: the file and+// every directory above it have to belong to root and be writable by root only. A copy run from ~/Downloads fails this.+bool boot_path_trusted(const char *path, char **why) {+ if (!path || path[0] != '/') { if (why) *why = g_strdup("not an absolute path"); return false; }+ char *cur = g_strdup(path);+ for (;;) {+ struct stat st;+ if (lstat(cur, &st) != 0) { if (why) *why = g_strdup_printf("%s: %s", cur, g_strerror(errno)); g_free(cur); return false; }+ bool file = !strcmp(cur, path);+ if (S_ISLNK(st.st_mode) || (file ? !S_ISREG(st.st_mode) : !S_ISDIR(st.st_mode))) {+ if (why) *why = g_strdup_printf("%s is a symbolic link or not a regular %s", cur, file ? "file" : "directory");+ g_free(cur); return false;+ }+ if (st.st_uid != 0 || (st.st_mode & (S_IWGRP | S_IWOTH))) {+ if (why) *why = g_strdup_printf("%s is not owned by root or is writable by other users", cur);+ g_free(cur); return false;+ }+ if (!strcmp(cur, "/")) break;+ char *up = g_path_get_dirname(cur);+ g_free(cur); cur = up;+ }+ g_free(cur);+ return true;+}+// The command line program that sits next to this one (an installed pair), otherwise the default install location.-static char *cli_path() {+static char *cli_path(char **error) {#ifdef PB_TEST_HOOKSconst char *e = getenv("PROXYBRIDGE_CLI");if (e && *e) return g_strdup(e);#endifchar self[4096];ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);+ char *cli = NULL;if (n > 0) {self[n] = 0;- char *dir = g_path_get_dirname(self), *cli = g_build_filename(dir, "ProxyBridge", NULL);+ char *dir = g_path_get_dirname(self);+ cli = g_build_filename(dir, "ProxyBridge", NULL);g_free(dir);- if (g_file_test(cli, G_FILE_TEST_IS_EXECUTABLE)) return cli;- g_free(cli);+ if (!g_file_test(cli, G_FILE_TEST_IS_EXECUTABLE)) { g_free(cli); cli = NULL; }+ }+ if (!cli) cli = g_strdup("/usr/local/bin/ProxyBridge");+ char *why = NULL;+ if (!boot_path_trusted(cli, &why)) {+ if (error) *error = g_strdup_printf("%s cannot be started at boot: %s. Install ProxyBridge with setup.sh and start the GUI from there.", cli, why);+ g_free(why); g_free(cli);+ return NULL;}- return g_strdup("/usr/local/bin/ProxyBridge");+ return cli;}// systemd's own quoting for one ExecStart word: backslash, double quote, % (specifier) and $ (variable) are escaped@@ -56,6 +90,10 @@ static void quote_word(GString *out, const char *s) {}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");+ 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");@@ -70,7 +108,11 @@ char *boot_unit_text(const char *cli, const char *profile, char **error) {quote_word(s, cli);g_string_append(s, " --profile ");quote_word(s, profile);- g_string_append(s, "\nRestart=on-failure\nRestartSec=5\n\n[Install]\nWantedBy=multi-user.target\n");+ 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+ "NoNewPrivileges=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);}@@ -101,7 +143,8 @@ static bool run_systemctl(const char *a, const char *b, char **error) {}static bool write_unit(const char *profile, char **error) {- char *cli = cli_path();+ char *cli = cli_path(error);+ if (!cli) return false;char *text = boot_unit_text(cli, profile, error);g_free(cli);if (!text) return false;diff --git a/Linux/gui/gui_boot.h b/Linux/gui/gui_boot.hindex 225ea88..973fade 100644--- a/Linux/gui/gui_boot.h+++ b/Linux/gui/gui_boot.h@@ -5,12 +5,16 @@#include <glib.h>#include <stdbool.h>-// Text of the unit file. NULL (with *error set) if the profile name cannot be written safely (control characters).-char *boot_unit_text(const char *cli_path, const char *profile, char **error);+// 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);+// 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.+// (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);diff --git a/Linux/gui/gui_config.c b/Linux/gui/gui_config.cindex 7b1fbf4..82114cf 100644--- a/Linux/gui/gui_config.c+++ b/Linux/gui/gui_config.c@@ -1,5 +1,6 @@#include "gui.h"#include <fcntl.h>+#include <errno.h>#include <dirent.h>#include "pb_profile.h"@@ -10,7 +11,7 @@ static char *config_dir() {return g_strdup(pbp_config_dir());}-static char *profile_path(const char *name) {+char *profile_path(const char *name) {char *file = pbp_filename_for(name);if (!file) return NULL;char *dir = config_dir();@@ -304,12 +305,32 @@ static void fill_profile_from_pbp(Profile *p, const struct pbp_profile *src) {p->nfilters = src->nfilters;}+// Under sudo or pkexec the file is written by root into the invoking user's directory: hand it to that user, so the+// "readable by you only" promise means the person at the keyboard. Only when the directory is theirs, never elsewhere.+static void give_to_invoker(const char *path) {+ const char *uid_s = getenv("PKEXEC_UID"), *gid_s = getenv("SUDO_GID");+ if (!uid_s) uid_s = getenv("SUDO_UID");+ if (!uid_s || !*uid_s) return;+ char *end = NULL;+ guint64 uid = g_ascii_strtoull(uid_s, &end, 10);+ if (!end || *end || uid == 0 || uid > 0xFFFFFFFEull) return;+ char *dir = g_path_get_dirname(path);+ struct stat st;+ bool theirs = stat(dir, &st) == 0 && st.st_uid == (uid_t)uid;+ g_free(dir);+ if (!theirs) return;+ guint64 gid = st.st_gid;+ if (gid_s && *gid_s) { gid = g_ascii_strtoull(gid_s, &end, 10); if (!end || *end || gid > 0xFFFFFFFEull) gid = st.st_gid; }+ if (chown(path, (uid_t)uid, (gid_t)gid) != 0) g_warning("could not hand %s to the invoking user: %s", path, g_strerror(errno));+}+bool profile_export(const Profile *prof, const char *path, char *err, size_t errlen) {profile_sync_active();struct pbp_profile view;profile_to_pbp(prof, &view);bool ok = pbp_save_file(path, &view, err, errlen) == 0;free_pbp_view(&view);+ if (ok) give_to_invoker(path);return ok;}diff --git a/Linux/gui/gui_settings.c b/Linux/gui/gui_settings.cindex 89c6110..1fefd25 100644--- a/Linux/gui/gui_settings.c+++ b/Linux/gui/gui_settings.c@@ -487,7 +487,10 @@ typedef struct {static void update_profile_ui() {char *boot_err = NULL;- if (!boot_refresh(g_active_profile, &boot_err)) { // the boot service runs the active profile+ 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);}diff --git a/Linux/gui/main.c b/Linux/gui/main.cindex 4061240..fa6d6e6 100644--- a/Linux/gui/main.c+++ b/Linux/gui/main.c@@ -60,7 +60,10 @@ 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;- if (!boot_set(want, g_active_profile, &err)) {+ char *ppath = profile_path(g_active_profile);+ bool set_ok = ppath && boot_set(want, ppath, &err);+ g_free(ppath);+ if (!set_ok) {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;@@ -117,65 +120,6 @@ void gui_sync_switches() {// same feed as windows/mac: https://download.interceptsuite.com/proxybridge.json#define UPD_FEED_URL "https://download.interceptsuite.com/proxybridge.json"-// match "linux": { ... } as a key, not a random "linux" string value-static char *extract_platform_block(const char *json, const char *platform) {- char needle[64];- snprintf(needle, sizeof(needle), "\"%s\"", platform);- size_t nlen = strlen(needle);- const char *p = json;- const char *key = NULL;- while ((p = strstr(p, needle)) != NULL) {- const char *after = p + nlen;- while (*after == ' ' || *after == '\t' || *after == '\n' || *after == '\r') after++;- if (*after == ':') {- key = p;- break;- }- p += nlen;- }- if (!key) return NULL;- const char *brace = strchr(key, '{');- if (!brace) return NULL;- int depth = 0;- for (const char *q = brace; *q; q++) {- if (*q == '{') depth++;- else if (*q == '}') {- depth--;- if (depth == 0)- return g_strndup(brace, (gsize)(q - brace + 1));- }- }- return NULL;-}--static void parse_ver(const char *s, int out[3]) {- out[0] = out[1] = out[2] = 0;- if (!s) return;- while (*s && (*s < '0' || *s > '9')) s++;- int i = 0;- while (*s && i < 3) {- if (*s >= '0' && *s <= '9') {- int n = 0;- while (*s >= '0' && *s <= '9') {- n = n * 10 + (*s - '0');- s++;- }- out[i++] = n;- } else if (*s == '.') {- s++;- } else {- break;- }- }-}--static int ver_cmp(const int a[3], const int b[3]) {- for (int i = 0; i < 3; i++) {- if (a[i] != b[i]) return a[i] < b[i] ? -1 : 1;- }- return 0;-}-static int https_url_ok(const char *url) {if (!url || strncmp(url, "https://", 8) != 0) return 0;for (const char *p = url; *p; p++) {@@ -186,6 +130,14 @@ static int https_url_ok(const char *url) {return 1;}+// The browser is opened as root: only the project's own release pages are handed to it.+static int release_host_ok(const char *url) {+ static const char *const hosts[] = { "https://github.com/InterceptSuite/", "https://download.interceptsuite.com/", "https://interceptsuite.com/", "https://www.interceptsuite.com/" };+ for (size_t i = 0; i < sizeof hosts / sizeof *hosts; i++)+ if (g_str_has_prefix(url, hosts[i])) return 1;+ return 0;+}+static const char *update_feed_url() {#ifdef PB_TEST_HOOKSconst char *override = getenv("PB_UPDATE_FEED"); // only in the UI test build: the shipped program always uses the real feed@@ -211,8 +163,8 @@ static void update_free(UpdateInfo *u) {static UpdateInfo *update_lookup(void) {UpdateInfo *u = g_malloc0(sizeof *u);char *argv[] = {- (char *)"curl", (char *)"-sS", (char *)"-m", (char *)"15",- (char *)"-H", (char *)"User-Agent: ProxyBridge-UpdateChecker",+ (char *)"curl", (char *)"-sS", (char *)"-m", (char *)"15", (char *)"--proto", (char *)"=https,file",+ (char *)"-H", (char *)"User-Agent: ProxyBridge-UpdateChecker", (char *)"--",(char *)update_feed_url(),NULL};@@ -226,33 +178,25 @@ static UpdateInfo *update_lookup(void) {g_free(curl_err);return u;}- if (exit_code != 0 || !json || json[0] == '\0') {- u->problem = g_strdup_printf("Update check failed (curl exit %d).", exit_code);+ if (!g_spawn_check_wait_status(exit_code, NULL) || !json || json[0] == '\0') {+ u->problem = g_strdup("Update check failed (could not fetch the update feed).");u->problem_type = GTK_MESSAGE_ERROR;g_free(json); g_free(curl_err);return u;}- char *linux_obj = extract_platform_block(json, "linux");+ // the same strict parser and version check as the command line program (the feed is remote input)+ char *version = NULL, *download = NULL, *notes = NULL;+ int rc = pbp_update_parse(json, strlen(json), &version, &download, ¬es);g_free(json);g_free(curl_err);- if (!linux_obj) {+ if (rc != 0) {u->problem = g_strdup("Could not parse linux update info.");u->problem_type = GTK_MESSAGE_WARNING;return u;}- u->version = extract_sub_json_str(linux_obj, "version");- u->download = extract_sub_json_str(linux_obj, "download");- u->notes = extract_sub_json_str(linux_obj, "release_notes");- g_free(linux_obj);- if (!u->version || !u->version[0]) {- u->problem = g_strdup("Could not parse version info.");- u->problem_type = GTK_MESSAGE_WARNING;- return u;- }- int cur[3], lat[3];- parse_ver(PROXYBRIDGE_VERSION, cur);- parse_ver(u->version, lat);- u->newer = ver_cmp(lat, cur) > 0;+ u->version = g_strdup(version); u->download = g_strdup(download ? download : ""); u->notes = g_strdup(notes ? notes : "");+ free(version); free(download); free(notes);+ u->newer = pbp_version_newer(u->version, PROXYBRIDGE_VERSION);return u;}@@ -280,9 +224,9 @@ static void update_show(UpdateInfo *u) {save_config();sync_update_item();} else if (resp == GTK_RESPONSE_ACCEPT) {- const char *url = NULL;- if (https_url_ok(u->notes)) url = u->notes;- else if (https_url_ok(u->download)) url = u->download;+ const char *url = NULL; // only pages of the project itself are opened in a browser running as root+ if (https_url_ok(u->notes) && release_host_ok(u->notes)) url = u->notes;+ else if (https_url_ok(u->download) && release_host_ok(u->download)) url = u->download;if (!url) {show_message(GTK_WINDOW(window), GTK_MESSAGE_ERROR, "No safe https url in update feed.");} else {diff --git a/Linux/gui/tests/boot_test.c b/Linux/gui/tests/boot_test.cindex a5cb770..45e6d82 100644--- a/Linux/gui/tests/boot_test.c+++ b/Linux/gui/tests/boot_test.c@@ -30,31 +30,49 @@ int main(void)setenv("PROXYBRIDGE_CLI", "/opt/pb dir/ProxyBridge", 1);char *unit = g_build_filename(units, "proxybridge.service", NULL);char *err = NULL;+ char *t;// unit text- char *t = boot_unit_text("/usr/local/bin/ProxyBridge", "Work", &err);- CHECK(t && strstr(t, "ExecStart=\"/usr/local/bin/ProxyBridge\" --profile \"Work\"\n") && strstr(t, "WantedBy=multi-user.target") &&+ t = boot_unit_text("/x/ProxyBridge", "Work", &err); // a name 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, "NoNewPrivileges=yes") && strstr(t, "ProtectSystem=strict") && strstr(t, "ProtectHome=read-only"));+ g_free(t);++ // only root-owned, root-writable-only paths may be started at boot+ char *why = NULL;+ CHECK(!boot_path_trusted(fake, &why) && why && strstr(why, "owned by root")); // our own temp file+ g_free(why); why = NULL;+ CHECK(!boot_path_trusted("relative/ProxyBridge", &why) && why); g_free(why); why = NULL;+ CHECK(!boot_path_trusted("/nonexistent/ProxyBridge", &why) && why); g_free(why); why = NULL;+ if (access("/usr/bin/true", X_OK) == 0) CHECK(boot_path_trusted("/usr/bin/true", &why) && why == NULL);+ 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"));g_free(t);- t = boot_unit_text("/x/ProxyBridge", "a \"b\" \\c %h $HOME", &err);- CHECK(t && strstr(t, "--profile \"a \\\"b\\\" \\\\c %%h $$HOME\"\n")); // quoting that systemd understands+ 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 understandsg_free(t);- t = boot_unit_text("/x/ProxyBridge", "line\nbreak", &err);+ t = boot_unit_text("/x/ProxyBridge", "/p/line\nbreak", &err);CHECK(t == NULL && err && strstr(err, "control characters"));g_free(err); err = NULL;- t = boot_unit_text("/x/ProxyBridge", "tab\there", &err);+ t = boot_unit_text("/x/ProxyBridge", "/p/tab\there", &err);CHECK(t == NULL);g_free(err); err = NULL;- t = boot_unit_text("/x/Proxy\nBridge", "ok", &err);+ t = boot_unit_text("/x/Proxy\nBridge", "/p/ok", &err);CHECK(t == NULL && err);g_free(err); err = NULL;// enableCHECK(!boot_is_enabled());- CHECK(boot_set(true, "Work", &err) && err == NULL);+ CHECK(boot_set(true, "/etc/proxybridge/profiles/Work.pbprofile", &err) && err == NULL);CHECK(boot_is_enabled());char *content = slurp(unit);- CHECK(strstr(content, "ExecStart=\"/opt/pb dir/ProxyBridge\" --profile \"Work\"\n")); // a path with a space is quoted+ CHECK(strstr(content, "ExecStart=\"/opt/pb dir/ProxyBridge\" --profile \"/etc/proxybridge/profiles/Work.pbprofile\"\n")); // a path with a space is quotedstruct stat st;CHECK(stat(unit, &st) == 0 && (st.st_mode & 0777) == 0644);char *log = slurp(calls);@@ -62,53 +80,53 @@ int main(void)g_free(content); g_free(log);// another active profile rewrites the unit- CHECK(boot_refresh("Home", &err));+ CHECK(boot_refresh("/etc/proxybridge/profiles/Home.pbprofile", &err));content = slurp(unit);- CHECK(strstr(content, "--profile \"Home\"") && !strstr(content, "Work"));+ CHECK(strstr(content, "--profile \"/etc/proxybridge/profiles/Home.pbprofile\"") && !strstr(content, "/etc/proxybridge/profiles/Work.pbprofile"));g_free(content);// disableg_unlink(calls);- CHECK(boot_set(false, "Home", &err));+ CHECK(boot_set(false, "/etc/proxybridge/profiles/Home.pbprofile", &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("Work", &err) && !boot_is_enabled()); // refresh does not enable anything- CHECK(boot_set(false, "Work", &err)); // disabling twice is fine and runs nothing+ 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 nothinglog = slurp(calls);CHECK(strlen(log) == 0);g_free(log);// a failing systemctl: report it and leave no unit behindsetenv("FAKE_FAIL", "enable", 1);- CHECK(!boot_set(true, "Work", &err) && err && strstr(err, "systemctl enable") && strstr(err, "boom"));+ CHECK(!boot_set(true, "/etc/proxybridge/profiles/Work.pbprofile", &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, "Work", &err) && err && strstr(err, "daemon-reload"));+ CHECK(!boot_set(true, "/etc/proxybridge/profiles/Work.pbprofile", &err) && err && strstr(err, "daemon-reload"));CHECK(!boot_is_enabled());g_free(err); err = NULL;unsetenv("FAKE_FAIL");- CHECK(boot_set(true, "Work", &err));+ CHECK(boot_set(true, "/etc/proxybridge/profiles/Work.pbprofile", &err));setenv("FAKE_FAIL", "disable", 1);- CHECK(!boot_set(false, "Work", &err) && err && strstr(err, "disable"));+ CHECK(!boot_set(false, "/etc/proxybridge/profiles/Work.pbprofile", &err) && err && strstr(err, "disable"));CHECK(boot_is_enabled()); // still enabled: the disable failedg_free(err); err = NULL;unsetenv("FAKE_FAIL");- CHECK(boot_set(false, "Work", &err));+ CHECK(boot_set(false, "/etc/proxybridge/profiles/Work.pbprofile", &err));// systemctl missing, and a directory that cannot be writtensetenv("PROXYBRIDGE_SYSTEMCTL", "/nonexistent/systemctl", 1);- CHECK(!boot_set(true, "Work", &err) && err && strstr(err, "could not run"));+ CHECK(!boot_set(true, "/etc/proxybridge/profiles/Work.pbprofile", &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, "Work", &err) && err && strstr(err, "cannot write"));+ CHECK(!boot_set(true, "/etc/proxybridge/profiles/Work.pbprofile", &err) && err && strstr(err, "cannot write"));g_free(err); err = NULL;- CHECK(!boot_set(true, "bad\nname", &err) && err && strstr(err, "control characters"));+ 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/ui_test.c b/Linux/gui/tests/ui_test.cindex c12ee0d..00a1aaf 100644--- a/Linux/gui/tests/ui_test.c+++ b/Linux/gui/tests/ui_test.c@@ -689,7 +689,8 @@ static void updates_scenario(void) {feed_case("feed_missing.json", NULL, GTK_RESPONSE_OK, "Update check failed", false);feed_case("feed_empty.json", "", GTK_RESPONSE_OK, "Update check failed", false);feed_case("feed_nolinux.json", "{\"windows\": {\"version\": \"9.0.0\"}}", GTK_RESPONSE_OK, "Could not parse linux update info", false);- feed_case("feed_noversion.json", "{\"linux\": {\"download\": \"https://example.test/d\"}}", GTK_RESPONSE_OK, "Could not parse version info", false);+ feed_case("feed_noversion.json", "{\"linux\": {\"download\": \"https://example.test/d\"}}", GTK_RESPONSE_OK, "Could not parse", false);+ feed_case("feed_escape.json", "{\"linux\": {\"version\": \"9.9.9\\u001b[31m\"}}", GTK_RESPONSE_OK, "Could not parse", false); // remote text never reaches a dialog rawfeed_case("feed_same.json", "{\"linux\": {\"version\": \"" PROXYBRIDGE_VERSION "\"}}", GTK_RESPONSE_OK, "latest version", false);feed_case("feed_beta_suffix.json", "{\"linux\": {\"version\": \"4.0.0\"}}", GTK_RESPONSE_OK, "latest version", false);feed_case("feed_older.json", "{\"linux\": {\"version\": \"3.2.0\"}}", GTK_RESPONSE_OK, "latest version", false);@@ -700,6 +701,10 @@ static void updates_scenario(void) {feed_case("feed_unsafe.json", "{\"linux\": {\"version\": \"9.9.9\", \"download\": \"http://insecure.test/x\", \"release_notes\": \"javascript:alert(1)\"}}",GTK_RESPONSE_ACCEPT, "Version 9.9.9 is available", true);CHECK_HAS(last_msg, "No safe https url");+ // ...and, since the browser runs as root, only the project's own pages: a feed pointing elsewhere is not opened+ feed_case("feed_foreign.json", "{\"linux\": {\"version\": \"9.9.9\", \"download\": \"https://evil.example/x\", \"release_notes\": \"https://evil.example/n\"}}",+ GTK_RESPONSE_ACCEPT, "Version 9.9.9 is available", true);+ CHECK_HAS(last_msg, "No safe https url");unsetenv("PB_UPDATE_FEED");}diff --git a/Linux/profile/pb_profile.c b/Linux/profile/pb_profile.cindex a5f3127..8c82b2b 100644--- a/Linux/profile/pb_profile.c+++ b/Linux/profile/pb_profile.c@@ -97,14 +97,12 @@ static int parse_string(struct jp *j, char **out)char *buf = malloc((size_t)(q - s) + 1), *o = buf;if (!buf) return jfail(j, "out of memory");for (const char *r = s; r < q; r++) {+ if ((unsigned char)*r < 0x20 || *r == 0x7F) { free(buf); return jfail(j, "control character in string"); }if (*r != '\\') { *o++ = *r; continue; }r++;switch (*r) {- case 'n': *o++ = '\n'; break;- case 't': *o++ = '\t'; break;- case 'r': *o++ = '\r'; break;- case 'b': *o++ = '\b'; break;- case 'f': *o++ = '\f'; break;+ case 'n': case 't': case 'r': case 'b': case 'f':+ free(buf); return jfail(j, "control character in string"); // no field of a profile may hold onecase '"': case '\\': case '/': *o++ = *r; break;case 'u': {int cp = (q - r >= 5) ? hex4(r + 1) : -1;@@ -116,7 +114,7 @@ static int parse_string(struct jp *j, char **out)cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);r += 6;} else if (cp >= 0xDC00 && cp <= 0xDFFF) { free(buf); return jfail(j, "bad surrogate pair"); }- if (cp == 0) { free(buf); return jfail(j, "NUL in string"); }+ if (cp < 0x20 || cp == 0x7F) { free(buf); return jfail(j, "control character in string"); }o = put_utf8(o, (unsigned)cp);break;}@@ -164,6 +162,8 @@ static int parse_container(struct jp *j, struct jv *v, int depth, bool obj)if (parse_string(j, &key) < 0) return -1;skip_ws(j);if (j->p >= j->end || *j->p != ':') { free(key); return jfail(j, "expected ':'"); }+ for (size_t i = 0; i < v->nk; i++)+ if (!strcasecmp(v->key[i], key)) { free(key); return jfail(j, "duplicate key"); } // other readers take the last onej->p++;}struct jv child = {0};@@ -198,15 +198,8 @@ static int parse_value(struct jp *j, struct jv *v, int depth)j->p += neg;if (j->p >= j->end || *j->p < '0' || *j->p > '9') return jfail(j, "bad number");while (j->p < j->end && *j->p >= '0' && *j->p <= '9') n = n * 10 + (*j->p++ - '0');- if (j->p < j->end && *j->p == '.') {- j->p++;- while (j->p < j->end && *j->p >= '0' && *j->p <= '9') j->p++;- }- if (j->p < j->end && (*j->p == 'e' || *j->p == 'E')) {- j->p++;- if (j->p < j->end && (*j->p == '+' || *j->p == '-')) j->p++;- while (j->p < j->end && *j->p >= '0' && *j->p <= '9') j->p++;- }+ if (j->p < j->end && (*j->p == '.' || *j->p == 'e' || *j->p == 'E'))+ return jfail(j, "numbers must be whole"); // 1080e1 or 8.9 would be read differently elsewherev->t = J_NUM;v->n = neg ? -n : n;return 0;@@ -401,6 +394,10 @@ static int read_proxy(struct pbp_profile *p, const struct jv *o, size_t idx, chalong id = jnum(o, "Id", 0);uint32_t want = id > 0 ? (uint32_t)id : 0;+ if (id > 0x7FFFFFFF) {+ snprintf(err, errlen, "ProxyConfigs[%zu]: Id out of range", idx);+ return -1;+ }uint32_t max = 0;for (size_t i = 0; i + 1 < p->nproxies; i++) {if (p->proxies[i].id > max) max = p->proxies[i].id;@@ -734,10 +731,11 @@ int pbp_write_file(const char *path, const char *data, char *err, size_t errlen)if (w <= 0) break;off += (size_t)w;}- if (off == n && fsync(fd) == 0 && close(fd) == 0 && rename(tmp, path) == 0) rc = 0;+ bool written = off == n && fsync(fd) == 0;+ int closed = close(fd);+ if (written && closed == 0 && rename(tmp, path) == 0) rc = 0;else {snprintf(err, errlen, "cannot write %s: %s", path, strerror(errno));- close(fd);unlink(tmp);}}@@ -808,6 +806,8 @@ int pbp_update_parse(const char *json, size_t len, char **version, char **downlo*download = jtext(lin, "download");*notes = jtext(lin, "release_notes");}+ if (*version && (strlen(*version) > 32 || strspn(*version, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.+-") != strlen(*version)))+ **version = 0; // the feed is remote input: only a plain version string is shownif (!*version || !**version) {free(*version); free(*download); free(*notes);*version = *download = *notes = NULL;@@ -842,19 +842,19 @@ bool pbp_version_newer(const char *candidate, const char *current)// ---- log filters ----+// Case-insensitive glob with a single backtrack point (linear time): a pattern from an imported profile must not be able+// to stall the connection callback, which runs this for every event.static bool ci_glob(const char *p, const char *s){- while (*p) {- if (*p == '*') {- while (*p == '*') p++;- if (!*p) return true;- for (; *s; s++) if (ci_glob(p, s)) return true;- return false;- }- if (!*s || (*p != '?' && tolower((unsigned char)*p) != tolower((unsigned char)*s))) return false;- p++; s++;+ const char *star = NULL, *mark = NULL;+ while (*s) {+ if (*p == '*') { star = ++p; mark = s; continue; }+ if (*p == '?' || tolower((unsigned char)*p) == tolower((unsigned char)*s)) { p++; s++; continue; }+ if (!star) return false;+ p = star; s = ++mark;}- return !*s;+ while (*p == '*') p++;+ return !*p;}static bool pat_ok(const char *pat, const char *actual)@@ -928,7 +928,7 @@ char *pbp_name_from_filename(const char *filename)const char *pbp_config_dir(void){- const char *env = getenv("PROXYBRIDGE_CONFIG_DIR");+ const char *env = secure_getenv("PROXYBRIDGE_CONFIG_DIR");return (env && *env) ? env : "/etc/proxybridge";}@@ -937,8 +937,7 @@ char *pbp_resolve(const char *dir, const char *s)if (!s || !*s) return NULL;size_t n = strlen(s), e = sizeof PBP_EXT - 1;bool has_ext = n > e && !strcmp(s + n - e, PBP_EXT);- if (strchr(s, '/')) return strdup(s);- if (has_ext && access(s, R_OK) == 0) return strdup(s);+ if (strchr(s, '/')) return strdup(s); // a path; a file in the current directory needs "./"char *name = strndup(s, has_ext ? n - e : n);char *file = name ? pbp_filename_for(name) : NULL, *path = NULL;if (file && asprintf(&path, "%s/profiles/%s", dir, file) < 0) path = NULL;diff --git a/Linux/profile/tests/profile_test.c b/Linux/profile/tests/profile_test.cindex cf2d8f7..ebeca08 100644--- a/Linux/profile/tests/profile_test.c+++ b/Linux/profile/tests/profile_test.c@@ -4,6 +4,7 @@#include <stdio.h>#include <stdlib.h>#include <string.h>+#include <time.h>#include <sys/stat.h>#include <unistd.h>@@ -141,6 +142,23 @@ static void test_gui_fields(void)static void test_filters(void){+ { // a hostile pattern must not backtrack exponentially: the callback runs this for every connection+ struct pbp_filter evil[] = { flt(true, "*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*b", "", "", "All", "All") };+ char subj[200];+ memset(subj, 'a', sizeof subj - 1); subj[sizeof subj - 1] = 0;+ struct timespec t0, t1;+ clock_gettime(CLOCK_MONOTONIC, &t0);+ for (int i = 0; i < 1000; i++) CHECK(pbp_filters_pass(evil, 1, subj, "1.2.3.4", "80", "TCP", "Proxy"));+ clock_gettime(CLOCK_MONOTONIC, &t1);+ CHECK((t1.tv_sec - t0.tv_sec) * 1000 + (t1.tv_nsec - t0.tv_nsec) / 1000000 < 2000);+ struct pbp_filter g[] = { flt(true, "*a*b", "", "", "All", "All") };+ CHECK(!pbp_filters_pass(g, 1, "xaxbxb", "", "", "TCP", "Proxy")); // still a correct glob+ CHECK(pbp_filters_pass(g, 1, "xaxbxbx", "", "", "TCP", "Proxy"));+ CHECK(!pbp_filters_pass(g, 1, "ab", "", "", "TCP", "Proxy"));+ struct pbp_filter q[] = { flt(true, "c?rl", "", "", "All", "All") };+ CHECK(!pbp_filters_pass(q, 1, "CURL", "", "", "TCP", "Proxy"));+ CHECK(pbp_filters_pass(q, 1, "crl", "", "", "TCP", "Proxy"));+ }struct pbp_filter none[1] = { { 0 } };CHECK(pbp_filters_pass(none, 0, "curl", "1.2.3.4", "80", "TCP", "Proxy")); // no filters: everything shows@@ -208,6 +226,11 @@ static void test_update_feed(void)const char *bare = "{ \"linux\": { \"version\": \"9\" } }";CHECK(pbp_update_parse(bare, strlen(bare), &v, &d, &n) == 0 && !strcmp(v, "9") && d == NULL && n == NULL);free(v);+ const char *esc = "{\"linux\":{\"version\":\"9.9\\u001b[31mX\"}}"; // escapes are refused by the parser+ CHECK(pbp_update_parse(esc, strlen(esc), &v, &d, &n) == -1 && !v);+ const char *odd = "{\"linux\":{\"version\":\"9.9 (nightly build!)\"}}"; // and anything but a plain version string+ CHECK(pbp_update_parse(odd, strlen(odd), &v, &d, &n) == -1 && !v);+ free(v);const char *bad[] = { "", "not json", "[]", "{}", "{ \"linux\": 5 }", "{ \"linux\": {} }", "{ \"linux\": { \"version\": \"\" } }", "{ \"windows\": { \"version\": \"1\" } }" };for (size_t i = 0; i < sizeof bad / sizeof *bad; i++)CHECK(pbp_update_parse(bad[i], strlen(bad[i]), &v, &d, &n) == -1 && !v && !d && !n);@@ -264,7 +287,15 @@ static void test_errors(void)expect_error("{\"Name\": \"abc}", "unterminated");expect_error("{\"Name\": \"\\q\"}", "escape");expect_error("{\"Name\": \"\\ud800\"}", "surrogate");- expect_error("{\"Name\": \"\\u0000\"}", "NUL");+ expect_error("{\"Name\": \"\\u0000\"}", "control character");+ expect_error("{\"Name\": \"a\\u001b]0;x\\u0007\"}", "control character"); // terminal escapes never reach a log or screen+ expect_error("{\"Name\": \"a\\nb\"}", "control character");+ expect_error("{\"Name\": \"a\tb\"}", "control character"); // raw tab+ expect_error("{\"Name\": \"a\x1b" "b\"}", "control character"); // raw ESC+ expect_error("{\"ProxyConfigs\":[{\"Type\":\"socks5\",\"Host\":\"h\",\"Port\":1080e1}]}", "whole"); // .NET reads 10800+ expect_error("{\"ProxyConfigs\":[{\"Type\":\"socks5\",\"Host\":\"h\",\"Port\":8.9}]}", "whole");+ expect_error("{\"Name\":\"a\",\"name\":\"b\"}", "duplicate"); // other readers take the last one+ expect_error("{\"ProxyConfigs\":[{\"Type\":\"socks5\",\"Host\":\"h\",\"Port\":1,\"Id\":4294967295}]}", "Id");expect_error("{\"ProxyConfigs\":[{\"Type\":\"socks5\",\"Host\":\"h\",\"Port\":\"0\"}]}", "Port");expect_error("{\"ProxyConfigs\":[{\"Type\":\"socks5\",\"Host\":\"\",\"Port\":\"1\"}]}", "Host");expect_error("{\"ProxyConfigs\":[{\"Type\":\"ftp\",\"Host\":\"h\",\"Port\":\"1\"}]}", "Type");@@ -387,6 +418,9 @@ static void test_files(void)char *r = pbp_resolve("/etc/proxybridge", "Work");CHECK(r && !strcmp(r, "/etc/proxybridge/profiles/Work.pbprofile")); free(r);+ r = pbp_resolve("/etc/proxybridge", "Work.pbprofile"); // a bare name is a GUI profile even when such a file is in the cwd+ CHECK(r && !strcmp(r, "/etc/proxybridge/profiles/Work.pbprofile"));+ free(r);r = pbp_resolve("/etc/proxybridge", "/tmp/x.pbprofile");CHECK(r && !strcmp(r, "/tmp/x.pbprofile")); free(r);r = pbp_resolve("/etc/proxybridge", "Work.pbprofile"); // no such file in the cwd: treated as the namediff --git a/Linux/setup.sh b/Linux/setup.shindex a3c40e5..f0764b1 100644--- a/Linux/setup.sh+++ b/Linux/setup.sh@@ -130,22 +130,18 @@ install_files() {# Create directories if they don't existmkdir -p "$LIB_PATH" /usr/local/bin /etc/proxybridge- chmod 755 /etc/proxybridge-- # Copy library+ chmod 700 /etc/proxybridge # holds profiles with proxy passwords++ # install(1) replaces the file and sets owner and mode, so a file left by someone else is never keptecho "Installing libproxybridge.so to $LIB_PATH..."- cp "$SCRIPT_DIR/libproxybridge.so" "$LIB_PATH/"- chmod 755 "$LIB_PATH/libproxybridge.so"-- # Copy binary+ install -o root -g root -m 0755 "$SCRIPT_DIR/libproxybridge.so" "$LIB_PATH/libproxybridge.so"+echo "Installing ProxyBridge to /usr/local/bin..."- cp "$SCRIPT_DIR/ProxyBridge" /usr/local/bin/- chmod 755 /usr/local/bin/ProxyBridge+ install -o root -g root -m 0755 "$SCRIPT_DIR/ProxyBridge" /usr/local/bin/ProxyBridgeif [ -f "$SCRIPT_DIR/ProxyBridgeGUI" ]; thenecho "Installing ProxyBridgeGUI to /usr/local/bin..."- cp "$SCRIPT_DIR/ProxyBridgeGUI" /usr/local/bin/- chmod 755 /usr/local/bin/ProxyBridgeGUI+ install -o root -g root -m 0755 "$SCRIPT_DIR/ProxyBridgeGUI" /usr/local/bin/ProxyBridgeGUIfiecho "Files installed"@@ -207,6 +203,34 @@ verify_installation() {fi}+# Removes everything setup.sh and the GUI installed, including the boot service. Profiles are kept unless --purge is given.+uninstall() {+ echo "Removing ProxyBridge..."+ if [ -f /etc/systemd/system/proxybridge.service ]; then+ systemctl disable --now proxybridge.service 2>/dev/null || true+ rm -f /etc/systemd/system/proxybridge.service+ systemctl daemon-reload 2>/dev/null || true+ echo " boot service removed"+ fi+ rm -f /usr/local/bin/ProxyBridge /usr/local/bin/ProxyBridgeGUI+ rm -f /usr/local/lib/libproxybridge.so /usr/local/lib64/libproxybridge.so /usr/lib/libproxybridge.so /usr/lib64/libproxybridge.so+ rm -f /etc/ld.so.conf.d/proxybridge.conf+ ldconfig 2>/dev/null || true+ if [ "$1" = "--purge" ]; then+ rm -rf /etc/proxybridge+ echo " profiles and settings removed"+ else+ echo " profiles kept in /etc/proxybridge (use --uninstall --purge to remove them)"+ fi+ echo "Done."+}++if [ "$1" = "--uninstall" ]; then+ [ "$(id -u)" = 0 ] || { echo "Please run as root: sudo $0 --uninstall"; exit 1; }+ uninstall "$2"+ exit 0+fi+# Main deploymentmain() {detect_distrodiff --git a/Linux/src/ProxyBridge.c b/Linux/src/ProxyBridge.cindex a474cf9..a6c5222 100644--- a/Linux/src/ProxyBridge.c+++ b/Linux/src/ProxyBridge.c@@ -8,6 +8,7 @@#include <stdlib.h>#include <string.h>#include <sys/stat.h>+#include <sys/sysmacros.h>#include <time.h>#include <unistd.h>#include "ProxyBridge.h"@@ -52,6 +53,14 @@ static void set_err(char *err, size_t n, const char *fmt, ...)va_end(ap);}+// Anything shown to the operator may carry bytes chosen by another local user (an executable's name, a DNS answer);+// a terminal or a log file must not receive control characters from them.+static void sanitize(char *s)+{+ for (unsigned char *p = (unsigned char *)s; *p; p++)+ if (*p < 0x20 || *p == 0x7F) *p = '?';+}+void pb_core_log(const char *fmt, ...){char buf[1024];@@ -59,6 +68,7 @@ void pb_core_log(const char *fmt, ...)va_start(ap, fmt);vsnprintf(buf, sizeof buf, fmt, ap);va_end(ap);+ sanitize(buf);pthread_mutex_lock(&cb_lock);if (G.log_cb) G.log_cb(buf);pthread_mutex_unlock(&cb_lock);@@ -136,12 +146,15 @@ static bool log_wanted(uint64_t key, bool udp)static void emit_connection(uint32_t pid, const char *comm, int family, const uint8_t addr[16], uint16_t port, int proto, int action, uint32_t proxy_id){if (!atomic_load(&G.traffic_logging)) return;- char path[4096], dest[INET6_ADDRSTRLEN + 280], info[400];+ char path[4096], dest[INET6_ADDRSTRLEN + 280], info[400], shown[256];const char *name = comm && *comm ? comm : "unknown";if (exe_path_of_pid(pid, path, sizeof path)) {const char *base = strrchr(path, '/');name = base ? base + 1 : path;}+ snprintf(shown, sizeof shown, "%s", name);+ sanitize(shown);+ name = shown;if (!log_wanted(conn_key(name, family, addr, port, proto, action, proxy_id), proto == IPPROTO_UDP)) return;if (family == AF_INET) {inet_ntop(AF_INET, addr + 12, dest, sizeof dest);@@ -159,6 +172,7 @@ static void emit_connection(uint32_t pid, const char *comm, int family, const uisnprintf(info, sizeof info, "%s %s:%u", p.type == PROXY_TYPE_SOCKS5 ? "SOCKS5" : "HTTP", p.host, p.port);elsesnprintf(info, sizeof info, "%s", action == PB_ACT_PROXY ? "PROXY" : action == PB_ACT_BLOCK ? "BLOCK" : "DIRECT");+ sanitize(dest);pthread_mutex_lock(&cb_lock);if (G.conn_cb) G.conn_cb(name, pid, dest, port, info);if (G.conn_cb_ex) G.conn_cb_ex(name, pid, dest, port, proto == IPPROTO_UDP ? "UDP" : "TCP", info);@@ -349,7 +363,9 @@ int pb_core_name_for(const struct pb_orig *o, char *out, size_t n)void pb_core_decide(const struct pb_orig *o, struct pb_decision *out){char path[4096];- if (!exe_path_of_pid(o->pid, path, sizeof path) && !pb_bpf_exe_path(o->exe_dev, o->exe_ino, path, sizeof path)) path[0] = 0;+ // The executable the kernel saw at connect() time is authoritative; /proc/<pid>/exe may already belong to another+ // program if the process exited and its PID was reused before this flow reached the relay.+ if (!(o->exe_ino && pb_bpf_exe_path(o->exe_dev, o->exe_ino, path, sizeof path)) && !exe_path_of_pid(o->pid, path, sizeof path)) path[0] = 0;out->action = PB_ACT_DIRECT;out->proxy_id = 0;@@ -428,6 +444,18 @@ static unsigned loop_next;static struct host_cache loop_hosts[4];static pthread_mutex_t loop_mu = PTHREAD_MUTEX_INITIALIZER;+int pb_core_udp_sender_ok(const struct pb_orig *o, uint16_t client_port)+{+ if (!pb_proc_pid_owns_udp(o->pid, client_port)) return 0;+ if (!o->exe_ino) return 1; // kernel-side identity is only recorded for DECIDE flows+ char link[64];+ struct stat st;+ snprintf(link, sizeof link, "/proc/%u/exe", o->pid);+ if (stat(link, &st) != 0) return 0;+ uint32_t dev = (major(st.st_dev) << 20) | minor(st.st_dev); // same encoding as the BPF program's exe2class key+ return dev == o->exe_dev && st.st_ino == o->exe_ino;+}+int pb_core_is_proxy_process(uint32_t pid, uint32_t proxy_id){int64_t now = mono_ms();diff --git a/Linux/src/bpf/proxybridge.bpf.c b/Linux/src/bpf/proxybridge.bpf.cindex 8d225dc..e00ed12 100644--- a/Linux/src/bpf/proxybridge.bpf.c+++ b/Linux/src/bpf/proxybridge.bpf.c@@ -211,24 +211,25 @@ static __always_inline void orig_from_v6(struct pb_orig *o, const __u32 ip6[4],o->family = (ip6[0] == 0 && ip6[1] == 0 && ip6[2] == bpf_htonl(0x0000ffff)) ? AF_INET : AF_INET6;}-// Loopback flow address 127.1-255.x.y standing for one UDP destination; the relay recovers the destination from it.+// Loopback flow address 127.1-255.x.y standing for one UDP destination of one process; the relay recovers the destination+// from it and checks that the datagram really comes from that process. 0 when no address is free (the caller refuses the+// send rather than borrowing another flow's address).static __always_inline __u32 udp_flow_addr(struct pb_orig *o){const __u32 *w = (const __u32 *)o->addr;__u32 h = w[0] * 2654435761u ^ w[1] * 40503u ^ w[2] * 2246822519u ^ w[3] * 3266489917u;h ^= ((__u32)o->port << 16) | o->proxy_id;h ^= (__u32)o->action * 668265263u;- if (o->action == ACT_DECIDE) h ^= o->pid * 374761393u;+ h ^= o->pid * 374761393u;h ^= h >> 15; h *= 2246822519u; h ^= h >> 13;- __u32 addr = 0;for (int i = 0; i < 8; i++) {- addr = bpf_htonl(0x7f000000 | (((h + i) & 0x00ffffff) | 0x00010000));+ __u32 addr = bpf_htonl(0x7f000000 | (((h + i) & 0x00ffffff) | 0x00010000));struct pb_orig *ex = bpf_map_lookup_elem(&flows, &addr);- if (!ex) { bpf_map_update_elem(&flows, &addr, o, BPF_NOEXIST); break; }+ if (!ex) { bpf_map_update_elem(&flows, &addr, o, BPF_NOEXIST); return addr; }if (!__builtin_memcmp(ex->addr, o->addr, 16) && ex->port == o->port && ex->proxy_id == o->proxy_id &&- ex->action == o->action && (o->action != ACT_DECIDE || ex->pid == o->pid)) break;+ ex->action == o->action && ex->pid == o->pid) return addr;}- return addr;+ return 0;}// 0: leave the call untouched, 1: redirected to the relay, -1: block.@@ -259,7 +260,9 @@ int pb_connect4(struct bpf_sock_addr *ctx)ctx->user_ip4 = bpf_htonl(0x7f000001);ctx->user_port = bpf_htons(cfg.tcp_port);} else {- ctx->user_ip4 = udp_flow_addr(&o);+ __u32 fa = udp_flow_addr(&o);+ if (!fa) return 0;+ ctx->user_ip4 = fa;ctx->user_port = bpf_htons(cfg.udp_port);}return 1;@@ -280,7 +283,9 @@ int pb_connect6(struct bpf_sock_addr *ctx)set_mapped_v4(ctx->user_ip6, bpf_htonl(0x7f000001));ctx->user_port = bpf_htons(cfg.tcp_port);} else {- set_mapped_v4(ctx->user_ip6, udp_flow_addr(&o));+ __u32 fa = udp_flow_addr(&o);+ if (!fa) return 0;+ set_mapped_v4(ctx->user_ip6, fa);ctx->user_port = bpf_htons(cfg.udp_port);}return 1;@@ -294,7 +299,9 @@ int pb_sendmsg4(struct bpf_sock_addr *ctx)orig_from_v4(&o, ctx->user_ip4, ctx->user_port, IPPROTO_UDP);int r = route(&o);if (r <= 0) return r == 0;- ctx->user_ip4 = udp_flow_addr(&o);+ __u32 fa = udp_flow_addr(&o);+ if (!fa) return 0;+ ctx->user_ip4 = fa;ctx->user_port = bpf_htons(cfg.udp_port);return 1;}diff --git a/Linux/src/pb_dns.c b/Linux/src/pb_dns.cindex 035d181..063dace 100644--- a/Linux/src/pb_dns.c+++ b/Linux/src/pb_dns.c@@ -168,26 +168,33 @@ int pb_dns_observe(const uint8_t *m, size_t len, struct pb_dns_result *res)strcpy(rr[nrr].owner, owner); rr[nrr].type = type; rr[nrr].rdlen = rdlen; rr[nrr].rdata = rd; nrr++;off = rd + rdlen;}- for (int i = 0; i < nrr; i++) {- char target[256];- if (rr[i].type == 5) { // CNAME: owner and target are both names of the final address+ // Only records that descend from the question count: the question names, the targets of CNAMEs owned by one of+ // those names (chained), and A records owned by a name in that set. An answer section that also carries+ // "other.example A 1.2.3.4" or an unrelated CNAME must not teach the engine anything about those names.+ bool in_set[128] = { false };+ for (int round = 0; round < 8; round++) {+ bool grew = false;+ for (int i = 0; i < nrr; i++) {+ if (rr[i].type != 5 || in_set[i]) continue;+ bool owner_known = false;+ for (int k = 0; k < nn; k++) if (!strcmp(names[k], rr[i].owner)) owner_known = true;+ if (!owner_known) continue;+ in_set[i] = true;+ char target[256];size_t o2 = rr[i].rdata;- if (read_name(m, len, &o2, target, sizeof target)) {- for (int pass = 0; pass < 2; pass++) {- const char *nm = pass ? target : rr[i].owner;- bool dup = false;- for (int k = 0; k < nn; k++) if (!strcmp(names[k], nm)) dup = true;- if (!dup && nn < PB_DNS_MAX_NAMES) strcpy(names[nn++], nm);- }- }- } else if (rr[i].type == 1 && rr[i].rdlen == 4) {- if (nips < 64) {- ips[nips++] = ((uint32_t)m[rr[i].rdata] << 24) | ((uint32_t)m[rr[i].rdata + 1] << 16) | ((uint32_t)m[rr[i].rdata + 2] << 8) | m[rr[i].rdata + 3];- bool dup = false;- for (int k = 0; k < nn; k++) if (!strcmp(names[k], rr[i].owner)) dup = true;- if (!dup && nn < PB_DNS_MAX_NAMES) strcpy(names[nn++], rr[i].owner);- }+ if (!read_name(m, len, &o2, target, sizeof target)) continue;+ bool dup = false;+ for (int k = 0; k < nn; k++) if (!strcmp(names[k], target)) dup = true;+ if (!dup && nn < PB_DNS_MAX_NAMES) { strcpy(names[nn++], target); grew = true; }}+ if (!grew) break;+ }+ for (int i = 0; i < nrr; i++) {+ if (rr[i].type != 1 || rr[i].rdlen != 4 || nips >= 64) continue;+ bool owner_known = false;+ for (int k = 0; k < nn; k++) if (!strcmp(names[k], rr[i].owner)) owner_known = true;+ if (!owner_known) continue; // out of bailiwick+ ips[nips++] = ((uint32_t)m[rr[i].rdata] << 24) | ((uint32_t)m[rr[i].rdata + 1] << 16) | ((uint32_t)m[rr[i].rdata + 2] << 8) | m[rr[i].rdata + 3];}if (!nips || !nn) return 0;diff --git a/Linux/src/pb_internal.h b/Linux/src/pb_internal.hindex 9c99d04..12bb4db 100644--- a/Linux/src/pb_internal.h+++ b/Linux/src/pb_internal.h@@ -63,6 +63,11 @@ int pb_core_name_for(const struct pb_orig *o, char *out, size_t n);// exemption refresh normally covers this; the relay asks for connections made in the moment before it ran.int pb_core_is_proxy_process(uint32_t pid, uint32_t proxy_id);+// True when the UDP datagram that arrived from 127.0.0.1:client_port really comes from the process that owns flow `o`+// (that process holds a UDP socket on that port and is still the same executable). Flow addresses are guessable, so+// without this any local process could send through another one's flow.+int pb_core_udp_sender_ok(const struct pb_orig *o, uint16_t client_port);+// Full rule evaluation for a PB_ACT_DECIDE flow.void pb_core_decide(const struct pb_orig *o, struct pb_decision *out);diff --git a/Linux/src/pb_proc.c b/Linux/src/pb_proc.cindex c6a382d..9ac4d88 100644--- a/Linux/src/pb_proc.c+++ b/Linux/src/pb_proc.c@@ -64,6 +64,25 @@ static size_t listen_inodes(uint32_t ip_be, uint16_t port, uint64_t *inodes)return n;}+// Sockets (any state, any local address) of /proc/net/udp or udp6 bound to `port`. The v6 address column is 32 hex digits,+// which parse_number wraps; only the port is used here.+static size_t udp_inodes(const char *file, uint16_t port, uint64_t *inodes, size_t n)+{+ FILE *f = fopen(file, "r");+ if (!f) return n;+ char line[512];+ if (!fgets(line, sizeof line, f)) { fclose(f); return n; }+ while (n < MAX_INODES && fgets(line, sizeof line, f)) {+ uint32_t addr, lport;+ unsigned state;+ unsigned long long inode;+ if (!parse_tcp_row(line, &addr, &lport, &state, &inode)) continue;+ if (lport == port && inode) inodes[n++] = inode;+ }+ fclose(f);+ return n;+}+static bool pid_has_socket(const char *pid, uint64_t inode){char dir[300], link[400], want[40], got[64];@@ -115,6 +134,18 @@ bool pb_proc_pid_listens(uint32_t pid, uint32_t ip_be, uint16_t port)return false;}+bool pb_proc_pid_owns_udp(uint32_t pid, uint16_t port)+{+ uint64_t inodes[MAX_INODES];+ size_t ni = udp_inodes("/proc/net/udp", port, inodes, 0);+ ni = udp_inodes("/proc/net/udp6", port, inodes, ni);+ char name[24];+ snprintf(name, sizeof name, "%u", pid);+ for (size_t i = 0; i < ni; i++)+ if (pid_has_socket(name, inodes[i])) return true;+ return false;+}+bool pb_proc_is_local_ip(uint32_t ip_be){if ((ntohl(ip_be) >> 24) == 127) return true;diff --git a/Linux/src/pb_proc.h b/Linux/src/pb_proc.hindex a7c3fc1..edf3ac3 100644--- a/Linux/src/pb_proc.h+++ b/Linux/src/pb_proc.h@@ -12,6 +12,9 @@ size_t pb_proc_listeners(uint32_t ip_be, uint16_t port, uint32_t *tgids, size_t// True if the process `pid` (a tgid) holds a LISTEN socket on `port` bound to `ip_be` or to 0.0.0.0. Looks at that one process only.bool pb_proc_pid_listens(uint32_t pid, uint32_t ip_be, uint16_t port);+// True if the process `pid` holds a UDP socket (v4 or v6) bound to local `port`. Looks at that one process only.+bool pb_proc_pid_owns_udp(uint32_t pid, uint16_t port);+// True for 127.0.0.0/8 and for any IPv4 address configured on a local interface.bool pb_proc_is_local_ip(uint32_t ip_be);diff --git a/Linux/src/pb_relay.c b/Linux/src/pb_relay.cindex cd51797..d1bcd08 100644--- a/Linux/src/pb_relay.c+++ b/Linux/src/pb_relay.c@@ -413,7 +413,9 @@ static int socks5_request(struct io *x, const struct pb_proxy *p, uint8_t cmd, csize_t o = 0;ab[o++] = 1; ab[o++] = (uint8_t)ul; memcpy(ab + o, p->user, ul); o += ul;ab[o++] = (uint8_t)pl; memcpy(ab + o, p->pass, pl); o += pl;- if (io_send(x, ab, o)) return -1;+ int sent = io_send(x, ab, o);+ explicit_bzero(ab, sizeof ab);+ if (sent) return -1;if (io_recv_exact(x, r, 2)) return -1;if (r[1] != 0) { seterr(x, "SOCKS5 authentication failed (wrong username or password)"); return -1; }} else if (r[1] != 0) {@@ -486,9 +488,13 @@ static int http_connect(struct io *x, const struct pb_proxy *p, const char *hostif (cl < 0 || cl >= (int)sizeof cred) { seterr(x, "HTTP proxy credentials too long"); return -1; }b64(cred, (size_t)cl, enc);n += snprintf(req + n, sizeof req - (size_t)n, "Proxy-Authorization: Basic %s\r\n", enc);+ explicit_bzero(cred, sizeof cred);+ explicit_bzero(enc, sizeof enc);}n += snprintf(req + n, sizeof req - (size_t)n, "\r\n");- if (io_send(x, req, (size_t)n)) return -1;+ int sent = io_send(x, req, (size_t)n);+ explicit_bzero(req, sizeof req);+ if (sent) return -1;uint8_t buf[HDR_MAX];size_t tot = 0, hend = 0;@@ -589,6 +595,7 @@ struct sess {socklen_t dstlen;uint16_t dport;bool dead, ok, warned;+ uint32_t pid; // process the session belongs toint64_t last, fail_until;struct pb_proxy proxy;char err[700];@@ -834,14 +841,25 @@ static void udp_job_run(struct sess *s)if (getpeername(ctl, (struct sockaddr *)&ra, &rl) < 0) { snprintf(s->err, sizeof s->err, "%s: getpeername: %s", desc, strerror(errno)); goto out; }if (ra.ss_family == AF_INET) ((struct sockaddr_in *)&ra)->sin_port = htons(b.port);else ((struct sockaddr_in6 *)&ra)->sin6_port = htons(b.port);- } else if (b.atyp == 1) {- struct sockaddr_in *a = (struct sockaddr_in *)&ra;- a->sin_family = AF_INET; a->sin_port = htons(b.port); memcpy(&a->sin_addr, b.addr, 4);- rl = sizeof *a;} else {- struct sockaddr_in6 *a = (struct sockaddr_in6 *)&ra;- a->sin6_family = AF_INET6; a->sin6_port = htons(b.port); memcpy(&a->sin6_addr, b.addr, 16);- rl = sizeof *a;+ // A relay address inside this host is only plausible when the proxy itself is here; a remote proxy that names+ // 127.x or ::1 would turn the relay into a blind sender towards local services.+ struct sockaddr_storage pa;+ socklen_t pl = sizeof pa;+ bool peer_local = getpeername(ctl, (struct sockaddr *)&pa, &pl) == 0 &&+ ((pa.ss_family == AF_INET && (ntohl(((struct sockaddr_in *)&pa)->sin_addr.s_addr) >> 24) == 127) ||+ (pa.ss_family == AF_INET6 && IN6_IS_ADDR_LOOPBACK(&((struct sockaddr_in6 *)&pa)->sin6_addr)));+ bool bnd_local = b.atyp == 1 ? b.addr[0] == 127 : IN6_IS_ADDR_LOOPBACK((const struct in6_addr *)b.addr);+ if (bnd_local && !peer_local) { snprintf(s->err, sizeof s->err, "%s: UDP relay address points at this host", desc); goto out; }+ if (b.atyp == 1) {+ struct sockaddr_in *a = (struct sockaddr_in *)&ra;+ a->sin_family = AF_INET; a->sin_port = htons(b.port); memcpy(&a->sin_addr, b.addr, 4);+ rl = sizeof *a;+ } else {+ struct sockaddr_in6 *a = (struct sockaddr_in6 *)&ra;+ a->sin6_family = AF_INET6; a->sin6_port = htons(b.port); memcpy(&a->sin6_addr, b.addr, 16);+ rl = sizeof *a;+ }}up = socket(ra.ss_family, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);if (up < 0 || connect(up, (struct sockaddr *)&ra, rl) < 0) {@@ -918,7 +936,13 @@ static void *acceptor_main(void *arg)}struct pb_orig o;if (pb_core_take_tcp_orig(pa.sin_addr.s_addr, ntohs(pa.sin_port), &o) != 0) {- pb_core_log("relay: no original destination for client %s:%u, closing", inet_ntoa(pa.sin_addr), ntohs(pa.sin_port));+ static int64_t last_log; static unsigned long unknown; // anyone can connect to the port: one line per 5 s+ unknown++;+ int64_t t = now_ms();+ if (t - last_log > 5000) {+ pb_core_log("relay: no original destination for client %s:%u, closing (%lu such connections)", inet_ntoa(pa.sin_addr), ntohs(pa.sin_port), unknown);+ last_log = t;+ }close(fd);continue;}@@ -1257,12 +1281,21 @@ static void sess_free_grave(void)while (R.sgrave) { struct sess *n = R.sgrave->next; free(R.sgrave); R.sgrave = n; }}-static struct sess *sess_new(const struct sockaddr_in *cli, uint32_t id, uint32_t flow, int kind)+// One process gets at most half of the session table: past that, its own least recently used session makes room, so a+// program that opens UDP sockets at a high rate only ever displaces itself and cannot starve every other one of UDP.+#define MAX_UDP_SESS_PER_PID (MAX_UDP_SESS / 2)++static struct sess *sess_new(const struct sockaddr_in *cli, uint32_t id, uint32_t flow, int kind, uint32_t pid){+ int mine = 0;+ struct sess *oldest = NULL;+ for (struct sess *t = R.sess_head; t; t = t->next)+ if (t->pid == pid) { mine++; if (!oldest || t->last < oldest->last) oldest = t; }+ if (mine >= MAX_UDP_SESS_PER_PID && oldest) sess_destroy(oldest);if (R.nsess >= MAX_UDP_SESS) return NULL;struct sess *s = calloc(1, sizeof *s);if (!s) return NULL;- s->cli = *cli; s->id = id; s->flow_be = flow; s->kind = kind;+ s->cli = *cli; s->id = id; s->flow_be = flow; s->kind = kind; s->pid = pid;s->up_fd = s->ctl_fd = -1;s->ref[0].s = s->ref[1].s = s;s->ref[0].which = 0; s->ref[1].which = 1;@@ -1349,7 +1382,10 @@ static void udp_dgram(const struct sockaddr_in *cli, uint32_t flow_be, const uinif (!keep) {int act = o.action;uint32_t pid = o.proxy_id;- if (act == PB_ACT_DECIDE) {+ if (!pb_core_udp_sender_ok(&o, ntohs(cli->sin_port))) {+ udp_droplog("datagram from a process other than the flow's");+ act = PB_ACT_BLOCK;+ } else if (act == PB_ACT_DECIDE) {struct pb_decision d;pb_core_decide(&o, &d);act = d.action;@@ -1389,7 +1425,7 @@ static void udp_dgram(const struct sockaddr_in *cli, uint32_t flow_be, const uinif (e->action == PB_ACT_DIRECT) {s = sess_find(cli, DIRECT_ID, flow_be);if (!s) {- s = sess_new(cli, DIRECT_ID, flow_be, SK_DIRECT);+ s = sess_new(cli, DIRECT_ID, flow_be, SK_DIRECT, o->pid);if (!s) { udp_droplog("UDP session limit reached"); return; }s->dstlen = orig_to_sa(o, &s->dst);s->dport = o->port;@@ -1412,7 +1448,7 @@ static void udp_dgram(const struct sockaddr_in *cli, uint32_t flow_be, const uinif (!s) {struct pb_proxy px;if (pb_core_get_proxy(e->pid, &px) != 0) { udp_droplog("proxy vanished"); return; }- s = sess_new(cli, px.id, 0, px.type == PROXY_TYPE_SOCKS5 ? SK_SOCKS5 : SK_DROP);+ s = sess_new(cli, px.id, 0, px.type == PROXY_TYPE_SOCKS5 ? SK_SOCKS5 : SK_DROP, o->pid);if (!s) { udp_droplog("UDP session limit reached"); return; }s->proxy = px;if (s->kind == SK_DROP) {@@ -1660,10 +1696,12 @@ static void teardown(void)R.jtail = NULL; R.jcount = 0;for (int i = 0; i < R.ndata; i++) {struct dthread *t = &R.data[i];+ pthread_mutex_lock(&t->mu); // pb_relay_flows may still be walking the listfor (struct conn *c = t->inq_head, *n; c; c = n) { n = c->next; close(c->fd[0]); close(c->fd[1]); conn_bufs_free(c); free(c); atomic_fetch_sub(&R.nconn, 1); }t->inq_head = t->inq_tail = NULL;for (struct conn *c = t->conns, *n; c; c = n) { n = c->next; close(c->fd[0]); close(c->fd[1]); conn_bufs_free(c); free(c); atomic_fetch_sub(&R.nconn, 1); }t->conns = NULL;+ pthread_mutex_unlock(&t->mu);free_grave(t);free(t->scratch); t->scratch = NULL;close_fd(&t->pfd[0]); close_fd(&t->pfd[1]);diff --git a/Linux/src/tests/dns_test.c b/Linux/src/tests/dns_test.cindex 928b9cf..9a5025a 100644--- a/Linux/src/tests/dns_test.c+++ b/Linux/src/tests/dns_test.c@@ -48,6 +48,17 @@ int main(void)CHECK(pb_dns_observe(m.b, m.n, &r) == 1);CHECK(has(H("198.51.100.7"), "www.shop.test") && has(H("198.51.100.7"), "cdn.edge.net"));+ // 2b. out-of-bailiwick records are ignored: an unrelated A record and a CNAME that the question does not lead to+ header(&m, 0x8180, 1, 3); q = wname(&m, "q.example"); w16(&m, 1); w16(&m, 1);+ a_rr(&m, q, "203.0.113.1");+ { size_t o = wname(&m, "allowed.corp"); (void)o; w16(&m, 1); w16(&m, 1); w32(&m, 60); w16(&m, 4);+ struct in_addr a; inet_pton(AF_INET, "203.0.113.2", &a); memcpy(m.b + m.n, &a, 4); m.n += 4; }+ { size_t o = wname(&m, "victim.bank"); (void)o; w16(&m, 5); w16(&m, 1); w32(&m, 60); size_t lp = m.n; w16(&m, 0);+ wname(&m, "q.example"); m.b[lp + 1] = (uint8_t)(m.n - lp - 2); }+ CHECK(pb_dns_observe(m.b, m.n, &r) == 1 && r.nips == 1); // only q.example's own address+ CHECK(has(H("203.0.113.1"), "q.example") && !has(H("203.0.113.1"), "allowed.corp") && !has(H("203.0.113.1"), "victim.bank"));+ CHECK(!has(H("203.0.113.2"), "allowed.corp") && !has(H("203.0.113.2"), "q.example"));+// 3. rejects: query (QR=0), NXDOMAIN, no answers, loopback answersheader(&m, 0x0100, 1, 0); q = wname(&m, "x.test"); w16(&m, 1); w16(&m, 1);CHECK(pb_dns_observe(m.b, m.n, &r) == 0);diff --git a/Linux/src/tests/relay_test.c b/Linux/src/tests/relay_test.cindex 8a553c7..717d8ae 100644--- a/Linux/src/tests/relay_test.c+++ b/Linux/src/tests/relay_test.c@@ -122,6 +122,12 @@ static uint32_t fnv(const uint8_t *p, size_t n)while (n--) { h ^= *p++; h *= 16777619u; }return h;}+static atomic_int g_sender_bad;+int pb_core_udp_sender_ok(const struct pb_orig *o, uint16_t client_port)+{+ (void)o; (void)client_port;+ return !atomic_load(&g_sender_bad);+}int pb_core_is_proxy_process(uint32_t pid, uint32_t proxy_id){(void)pid; (void)proxy_id;@@ -1261,6 +1267,16 @@ static void test_udp(void)CHECK(udp_echo_ok(c, "127.1.2.3", "hello-one"), "UDP via SOCKS5 UDP ASSOCIATE, reply from flow address 127.1.2.3");CHECK(udp_echo_ok(c, "127.1.2.4", "hello-two"), "second destination from same client socket, reply from 127.1.2.4");CHECK(udp_echo_ok(c, "127.1.2.3", "again"), "first destination again");+ { // a datagram that does not come from the flow's own process is dropped, and the flow keeps working for its owner+ atomic_store(&g_sender_bad, 1);+ int imp = udp_client();+ char b[64], ip[32]; uint16_t sp;+ udp_send_flow(imp, "127.1.2.3", "impostor");+ CHECK(udp_recv_neg(imp, b, sizeof b, ip, &sp) < 0, "UDP from a process that does not own the flow gets nothing back");+ atomic_store(&g_sender_bad, 0);+ close(imp);+ CHECK(udp_echo_ok(c, "127.1.2.3", "owner-again"), "the owner's datagrams still flow");+ }CHECK(g_assoc_count - a0 == 1, "exactly one UDP ASSOCIATE for the session (got %d)", (int)g_assoc_count - a0);int c2 = udp_client();