Skip to content

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

feat(linux/cli): same options as the Windows CLI (--profile, --verbose, --version, --help, --update); tests start the engine from profiles; fix a leak in list_test

anof-cyber99e2d66c11c0
diff --git a/Linux/README.md b/Linux/README.md
index f1044d5..7eb783d 100644
--- a/Linux/README.md
+++ b/Linux/README.md
@@ -98,185 +98,40 @@ The GTK3-based GUI provides:
### Command Line Interface (CLI)
-The CLI provides powerful automation and scripting capabilities with rule-based traffic control.
+The CLI takes the same options as the Windows CLI. Everything else (proxies, rules, DNS via proxy, connection-log setting) lives in a **profile**, which you build in the GUI (or write by hand) and run with `--profile`.
-#### Basic Usage
-
-```bash
-# Help menu
-ProxyBridge --help
-
-# Route curl through SOCKS5 proxy
-sudo ProxyBridge --proxy socks5://127.0.0.1:1080 --rule "curl:*:*:TCP:PROXY"
-
-# Route multiple processes in single rule (semicolon-separated)
-sudo ProxyBridge --proxy http://127.0.0.1:8080 --rule "curl;wget;firefox:*:*:TCP:PROXY"
-
-# Multiple rules with verbose connection logging
-sudo ProxyBridge --proxy http://127.0.0.1:8080 \
- --rule "curl:*:*:TCP:PROXY" \
- --rule "wget:*:*:TCP:PROXY" \
- --verbose 2
-
-# Block specific application from internet access
-sudo ProxyBridge --rule "malware:*:*:BOTH:BLOCK"
-
-# Route specific apps through proxy, block everything else
-sudo ProxyBridge --proxy socks5://127.0.0.1:1080 \
- --rule "curl:*:*:TCP:PROXY" \
- --rule "firefox:*:*:TCP:PROXY" \
- --rule "*:*:*:BOTH:BLOCK"
-
-# Route all through proxy except proxy app itself
-sudo ProxyBridge --proxy socks5://127.0.0.1:1080 \
- --rule "*:*:*:TCP:PROXY" \
- --rule "burpsuite:*:*:TCP:DIRECT"
-
-# Target specific IPs and ports
-sudo ProxyBridge --proxy socks5://127.0.0.1:1080 \
- --rule "curl:192.168.*.*;10.10.*.*:80;443;8080:TCP:PROXY"
-
-# IP range support
-sudo ProxyBridge --proxy socks5://192.168.1.4:4444 \
- --rule "curl:3.19.110.0-3.19.115.255:*:TCP:PROXY"
-
-# Several proxies, each rule picks its own (name=type://[user:pass@]host:port)
-sudo ProxyBridge \
- --proxy tor=socks5://127.0.0.1:9050 \
- --proxy burp=http://127.0.0.1:8080 \
- --rule "firefox:*:*:BOTH:PROXY=tor" \
- --rule "curl;wget:*:*:TCP:PROXY=burp" \
- --rule "*:10.0.0.0/8:*:BOTH:DIRECT"
-
-# IPv6 and CIDR targets
-sudo ProxyBridge --rule "curl:2001:db8::/32;10.0.0.0/8:443:TCP:PROXY"
+```
+sudo ProxyBridge --profile work # a profile saved by the GUI (Proxy > Profiles)
+sudo ProxyBridge --profile ./myconfig.pbprofile --verbose 2 # any .pbprofile, e.g. exported from the Windows or macOS app
+ProxyBridge --update # look for a newer version (no root)
```
#### Command Line Options
```
-sudo ProxyBridge --help
-
-
- ____ ____ _ _
- | _ \ _ __ _____ ___ _ | __ ) _ __(_) __| | __ _ ___
- | |_) | '__/ _ \ \/ / | | | | _ \| '__| |/ _` |/ _` |/ _ \
- | __/| | | (_) > <| |_| | | |_) | | | | (_| | (_| | __/
- |_| |_| \___/_/\_\\__, | |____/|_| |_|\__,_|\__, |\___|
- |___/ |___/ V4.0
-
- Universal proxy client for Linux applications
-
- Author: Sourav Kalal/InterceptSuite
- GitHub: https://github.com/InterceptSuite/ProxyBridge
-
-USAGE:
- cli/ProxyBridge [OPTIONS]
-
-OPTIONS:
- --proxy <spec> Add a proxy (repeatable). The first one is the default.
- Format: [name=]type://[user:pass@]host:port
- Examples: socks5://127.0.0.1:1080
- work=http://alice:[email protected]:8080
- tor=socks5://[::1]:9050
- Legacy form type://host:port:user:pass is still accepted.
- Append ?dns=local to send IP addresses instead of host names; the default
- (?dns=proxy) sends the name the application resolved, so the proxy resolves it.
- Default: socks5://127.0.0.1:4444
-
- --rule <rule> Traffic routing rule (repeatable, first match wins)
- Format: process:hosts:ports:protocol:action[=proxy]
- process - name or path glob(s): curl, chrom*, *, or several separated by ; or ,
- hosts - IPv4/IPv6, CIDR (10.0.0.0/8), ranges (1.2.3.4-1.2.3.9),
- octet patterns (192.168.*.*) or *; several separated by ; or ,
- ports - *, 443, 80;8080, 8000-9000
- protocol - TCP, UDP, or BOTH
- action - PROXY, DIRECT, or BLOCK; PROXY=name (or PROXY=2) picks a specific proxy;
- PROXY+localhost (or PROXY=name+localhost) also proxies 127.0.0.0/8 and ::1
- Examples:
- curl:*:*:TCP:PROXY
- firefox:*:*:BOTH:PROXY=work
- curl;wget:10.0.0.0/8:*:TCP:DIRECT
- *:*:53:UDP:PROXY=tor
-
- --profile <name|file> Load proxies and rules from a .pbprofile (a file path, or the name of a profile saved
- by the GUI). Same format as the Windows and macOS apps; repeatable, and can be
- combined with --proxy and --rule. Disabled rules are skipped.
- --list-profiles List the profiles saved by the GUI and exit
-
- --test-proxy <host[:port]> Check every configured proxy against that target (reach it, open a tunnel and log in,
- load a page, time tunnels, probe UDP), print the steps and exit 0 only if all work.
- Needs no root. Example: --proxy socks5://127.0.0.1:1080 --test-proxy example.com:80
-
- --log-every-connection <bool> Show every new connection in the connection log (--verbose 2/3) instead of one
- line per application, destination and action (default false; a profile can set it)
-
- --dns-via-proxy <bool> Route DNS queries through the proxy (true/false/1/0, default true)
-
- --verbose <level> 0 none (default), 1 logs, 2 connections, 3 both
-
- --cleanup No-op, kept for compatibility: the eBPF programs detach automatically
-
- --help, -h Show this help message
-
-EXAMPLES:
- sudo cli/ProxyBridge --profile work
- sudo cli/ProxyBridge --profile ./myconfig.pbprofile --verbose 2
-
- sudo cli/ProxyBridge --rule curl:*:*:TCP:PROXY
-
- sudo cli/ProxyBridge --proxy socks5://192.168.1.10:1080 --proxy work=http://proxy.corp:8080 \
- --rule firefox:*:*:BOTH:PROXY --rule curl:*:*:TCP:PROXY=work --verbose 2
-
-NOTE:
- ProxyBridge needs root and a Linux kernel >= 5.11 with BTF and cgroup v2 (eBPF datapath).
- Credentials given on the command line are visible to other users via ps.
+ --profile <path> Path to a .pbprofile file, or the name of a profile saved by the GUI
+ --verbose <0-3> Logging verbosity: 0 silent (default), 1 log messages, 2 connections, 3 both
+ --version Show the version
+ -?, -h, --help Show help
+ --update Check for a newer version and exit (needs no root; nothing is downloaded or run)
```
-#### Rule Format
-
-**Format:** `process:hosts:ports:protocol:action[=proxy]`
-
-- **process** - Name or path glob(s): `curl`, `curl;wget;firefox`, `fire*`, `*chrome*`, `/usr/bin/*`, or `*`. Matched against the executable's file name and full path, case-sensitive
-- **hosts** - `*`, IPv4/IPv6 addresses, CIDR (`10.0.0.0/8`, `2001:db8::/32`), ranges (`10.10.1.1-10.10.255.255`), octet patterns (`192.168.*.*`, `10.1-5.*.*`), **domain names** (`github.com`, `*.github.com`, `api?.example.org`), or a list mixing any of these separated by `;` or `,`. A plain domain matches exactly that name; use `*.` for subdomains. See [Domain rules](#domain-rules)
-- **ports** - `*`, `443`, `80;443;8080`, `80-8000`, or `80;443;8000-9000`
-- **protocol** - `TCP`, `UDP`, or `BOTH`
-- **action** - `PROXY`, `DIRECT`, or `BLOCK`. `PROXY=name` (or `PROXY=2`, the 1-based position of a `--proxy`) uses a specific proxy; plain `PROXY` uses the first one
-
-Rules are evaluated **in order and the first match wins** (put specific rules before general ones).
-
-**Examples:**
-```bash
-# Single process to proxy
---rule "curl:*:*:TCP:PROXY"
-
-# Multiple processes in one rule
---rule "curl;wget;firefox:*:*:TCP:PROXY"
-
-# Wildcard process names
---rule "fire*:*:*:TCP:PROXY" # Matches firefox, firebird, etc.
+`--profile` is required to start the engine, which needs root and a Linux kernel >= 5.11 with BTF and cgroup v2. A profile must contain at least one enabled rule, and a rule that uses a proxy needs a proxy in the profile; otherwise the CLI says so and exits with status 1. Press `Ctrl+C` to stop; the kernel hooks are removed automatically, even if ProxyBridge crashes.
-# Target specific IPs and ports
---rule "curl:192.168.*.*;10.10.*.*:80;443;8080:TCP:PROXY"
+Update check: the feed is `https://download.interceptsuite.com/proxybridge.json`; only `https` links from it are shown. The GUI can check on start-up (Settings).
-# Specific proxy per rule
---rule "firefox:*:*:BOTH:PROXY=tor"
-
-# Domain names (exact and wildcard), each rule with its own proxy
---rule "firefox:*.github.com;github.com:443:TCP:PROXY=work"
+#### Rule Format
-# Also proxy this application's localhost traffic (e.g. to intercept it in a local proxy tool)
---rule "myapp:*:8080:TCP:PROXY=work+localhost"
---rule "*:*.internal.corp:*:BOTH:PROXY=burp"
+Rules are the `ProxyRules` of the profile (the GUI Rules dialog edits the same fields). A rule has:
-# IP range / CIDR / IPv6
---rule "curl:3.19.110.0-3.19.115.255:*:TCP:PROXY"
---rule "curl:10.0.0.0/8:*:TCP:DIRECT"
---rule "curl:2001:db8::/32:443:TCP:PROXY"
+- **ProcessName** - Name or path glob(s): `curl`, `curl;wget;firefox`, `fire*`, `*chrome*`, `/usr/bin/*`, or `*`. Matched against the executable's file name and full path, case-sensitive
+- **TargetHosts** - `*`, IPv4/IPv6 addresses, CIDR (`10.0.0.0/8`, `2001:db8::/32`), ranges (`10.10.1.1-10.10.255.255`), octet patterns (`192.168.*.*`, `10.1-5.*.*`), **domain names** (`github.com`, `*.github.com`, `api?.example.org`), or a list mixing any of these separated by `;` or `,`. A plain domain matches exactly that name; use `*.` for subdomains. See [Domain rules](#domain-rules)
+- **TargetPorts** - `*`, `443`, `80;443;8080`, `80-8000`, or `80;443;8000-9000`
+- **Protocol** - `TCP`, `UDP`, or `BOTH`
+- **Action** - `PROXY`, `DIRECT`, or `BLOCK`; a `PROXY` rule uses the proxy named by `ProxyConfigId` (`0`: the default proxy)
+- **LocalhostViaProxy** - also proxy this application's localhost traffic (e.g. to intercept it in a local proxy tool)
-# Allow direct connection (bypass proxy)
---rule "burpsuite:*:*:TCP:DIRECT"
-```
+Rules are evaluated **in order and the first match wins** (put specific rules before general ones).
**Notes:**
- Process names are case-sensitive on Linux
@@ -291,9 +146,8 @@ A profile is a named set of proxies and rules. The GUI keeps any number of them
Profiles are stored in the **same `.pbprofile` JSON format as the Windows and macOS apps**, so a file exported on one platform imports on the others:
```bash
-sudo ProxyBridge --profile work # a profile saved by the GUI (see --list-profiles)
+sudo ProxyBridge --profile work # a profile saved by the GUI
sudo ProxyBridge --profile ~/exported.pbprofile # any .pbprofile file, e.g. exported from the Windows GUI
-sudo ProxyBridge --profile work --rule "curl:*:*:TCP:DIRECT" # profile first, then extra proxies and rules
```
```json
@@ -316,7 +170,7 @@ sudo ProxyBridge --profile work --rule "curl:*:*:TCP:DIRECT" # profile first,
- Rules point at proxies by `ProxyConfigId`; `0` means the default proxy (`DefaultProxyId`, otherwise the first proxy). A rule that names a proxy that is not in the file makes the profile invalid, rather than silently routing somewhere else.
- Linux keeps domain names in the host list. On export they are written to `TargetDomains` (as the Windows app does) and merged back on import.
-- Fields this version has no use for (`LogFilters`, ...) are ignored on import. `DnsViaProxy` and `DefaultProxyId` are Linux additions that other apps ignore. `LogEveryConnection` is the same per-profile setting as in the Windows app. `Name` (proxies and rules), `SendDomainToProxy` (per proxy, default `true`) and `LocalhostViaProxy` (per rule, default `false`) mean the same as in the Windows app; a top-level `LocalhostViaProxy` from older profiles is the default for rules that have none of their own. The CLI takes DNS-via-proxy from the profile unless `--dns-via-proxy` is given, and uses `--verbose` instead of the logging flag.
+- Fields this version has no use for (`LogFilters`, ...) are ignored on import. `DnsViaProxy` and `DefaultProxyId` are Linux additions that other apps ignore. `LogEveryConnection` is the same per-profile setting as in the Windows app. `Name` (proxies and rules), `SendDomainToProxy` (per proxy, default `true`) and `LocalhostViaProxy` (per rule, default `false`) mean the same as in the Windows app; a top-level `LocalhostViaProxy` from older profiles is the default for rules that have none of their own. The CLI takes DNS-via-proxy and the connection-log setting from the profile, and uses `--verbose` instead of the logging flag.
- Disabled rules (`"IsEnabled": false`) are kept in the GUI and skipped by the CLI.
- **GUI storage:** `/etc/proxybridge/profiles/<name>.pbprofile` (one file per profile) and `/etc/proxybridge/settings.json`, which holds only the name of the active profile. Everything else, including the *Enable Traffic Logging* and *DNS via Proxy* switches, is saved inside the profile, so switching profiles switches those too. The directory is `0700` and the files `0600`, because they hold proxy passwords; exported files are `0600` as well, and the CLI warns when a profile with credentials is readable by others. The `config.ini` of earlier versions is converted on the first start and kept as `config.ini.bak`.
- Files are limited to 4 MiB, 256 proxies and 4096 rules; malformed files are rejected with the reason, never partly applied.
@@ -346,10 +200,10 @@ Cost: DNS from covered processes takes one extra loopback hop (about +90 µs per
## Connection log, live connections and the main switch
-- **Connection log.** By default a connection is listed once per application, destination, port, protocol and action, so a program that opens 50 connections to one server gets one line. *Log Every Connection* (`--log-every-connection true`, saved per profile) lists every new TCP connection and every new UDP flow instead; a UDP flow is listed again after 30 seconds of silence. Each decision appears exactly once, whether the kernel or the relay made it.
+- **Connection log.** By default a connection is listed once per application, destination, port, protocol and action, so a program that opens 50 connections to one server gets one line. *Log Every Connection* (the per-profile setting) lists every new TCP connection and every new UDP flow instead; a UDP flow is listed again after 30 seconds of silence. Each decision appears exactly once, whether the kernel or the relay made it.
- **Live Connections** (GUI tab, `ProxyBridge_GetFlows()` in the library): the TCP connections and UDP flows being relayed through a proxy right now, newest first, with process, PID, destination (the name the application resolved when known), proxy, age and payload bytes in each direction. Direct and blocked traffic never reaches the relay and is not listed.
- **Enable ProxyBridge** (Proxy menu, `ProxyBridge_SetEnabled()`): the main switch. Off pauses every rule for *new* connections; connections already relayed keep running.
-- **Testing a proxy.** The Test button in the proxy settings and `--test-proxy host[:port]` run the same five steps: reach the proxy, open a tunnel and log in, load a page (port 80), time three more tunnels, and probe UDP ASSOCIATE. Only the first two decide success; a page, latency or UDP problem is a warning. The exit code is 0 only when every configured proxy works.
+- **Testing a proxy.** The Test button in the proxy settings runs five steps: reach the proxy, open a tunnel and log in, load a page (port 80), time three more tunnels, and probe UDP ASSOCIATE. Only the first two decide success; a page, latency or UDP problem is a warning. The exit code is 0 only when every configured proxy works.
## Appearance, logs and start-up
@@ -370,7 +224,7 @@ Cost: DNS from covered processes takes one extra loopback hop (about +90 µs per
| Per-proxy *DNS via proxy* (`SendDomainToProxy`) | yes |
| Per-rule *Also proxy localhost traffic* (`LocalhostViaProxy`) | yes (BLOCK/DIRECT never touch loopback) |
| Profiles in the `.pbprofile` format, CLI `--profile` | yes |
-| Detailed proxy check (reach, login, page, latency, UDP) | yes (GUI Test button, `--test-proxy`) |
+| Detailed proxy check (reach, login, page, latency, UDP) | yes (GUI Test button) |
| Live connections | yes (GUI tab, `ProxyBridge_GetFlows`) |
| Log Every Connection, main on/off switch | yes |
| Connection-log filters (`LogFilters`), auto-clear logs (`AutoClearConnectionLogs`), font zoom (`FontZoom`) | yes, per profile |
@@ -380,7 +234,7 @@ Cost: DNS from covered processes takes one extra loopback hop (about +90 µs per
## Multiple proxies
-Add as many `--proxy` entries (CLI) or proxies (GUI) as you need; each rule chooses its own with `PROXY=name`. Proxy hosts may be IP addresses or **host names** (resolved with a 5 s deadline and a cache, so a slow resolver cannot stall traffic). A rule that references a proxy that no longer exists blocks instead of leaking.
+Add as many proxies as you need (GUI or profile); each rule chooses its own. Proxy hosts may be IP addresses or **host names** (resolved with a 5 s deadline and a cache, so a slow resolver cannot stall traffic). A rule that references a proxy that no longer exists blocks instead of leaking.
## Security model
@@ -388,7 +242,7 @@ Add as many `--proxy` entries (CLI) or proxies (GUI) as you need; each rule choo
- **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.
- 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). On the command line, `--proxy user:pass@host` is wiped from the process list after parsing, but a shell history can still keep it; prefer the GUI or a profile file for secrets.
+- 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.
## Use Cases
@@ -416,7 +270,7 @@ Add as many `--proxy` entries (CLI) or proxies (GUI) as you need; each rule choo
- **Stalled proxies do not hold everything up.** Connections that need a handshake with their proxy are served by a pool of workers that starts with 8 and grows to 64 while handshakes queue up (extra workers leave after 20 idle seconds). No single proxy may occupy more than 48 workers at once, so a proxy that accepts connections and then never answers (up to the 10 s handshake timeout each) cannot delay connections that use another proxy.
-- **DNS Traffic Handling**: with `--dns-via-proxy true` (default) DNS (port 53) follows your rules like any other traffic; with `false`, DNS always uses a direct connection regardless of rules.
+- **DNS Traffic Handling**: with *DNS via Proxy* on (default) DNS (port 53) follows your rules like any other traffic; when off, DNS always uses a direct connection regardless of rules.
- **Automatic Direct Routing**: Certain IP addresses and ports automatically use direct connection regardless of proxy rules:
- **Loopback** (127.0.0.0/8, ::1) and **0.0.0.0/8**, unless a PROXY rule has *Also proxy localhost traffic* (then only that rule's matches are proxied, and never port 53 or the relay itself)
@@ -631,7 +485,7 @@ sudo ./e2e_faults.sh # misbehaving SOCKS5/HTTP prox
sudo ./e2e_udp.sh # UDP through SOCKS5 UDP ASSOCIATE: normal and malformed proxies, sizes, many sockets, BLOCK/DIRECT/HTTP, IPv6 (root)
sudo ./e2e_rules_diff.sh # random rule sets vs an independent reference: kernel fast path and slow path, TCP and UDP (root)
sudo ./e2e_logging.sh # connection log: de-duplication, log-every-connection, one line per decision (root)
-./e2e_checker.sh # `--test-proxy` against working and broken proxies (no root)
+./e2e_checker.sh # the proxy check against working and broken proxies (no root)
sudo ./gui_ui.sh # drives the real windows and dialogs: proxies, rules, profiles, file choosers, menus, engine (root, needs broadwayd)
sudo ./coverage.sh # line coverage of everything above plus the unit tests; `./coverage.sh unit` needs no root
sudo ./e2e_parity.sh # per-proxy host-name sending and per-rule localhost, incl. a hostile DNS name (root, needs dig)
diff --git a/Linux/cli/main.c b/Linux/cli/main.c
index 4cce495..16c6090 100644
--- a/Linux/cli/main.c
+++ b/Linux/cli/main.c
@@ -4,38 +4,12 @@
#include <unistd.h>
#include <signal.h>
#include <stdbool.h>
-#include <ctype.h>
-#include <strings.h>
-#include <dirent.h>
#include <sys/stat.h>
+#include <sys/wait.h>
#include "../src/ProxyBridge.h"
#include "../profile/pb_profile.h"
-#define MAX_RULES 1024
-#define MAX_PROXIES 64
-#define MAX_RULE_STR 2048
-#define FIELD 512 /* same limit as the library */
-
-typedef struct {
- char process_name[FIELD];
- char target_hosts[FIELD];
- char target_ports[FIELD];
- RuleProtocol protocol;
- RuleAction action;
- char proxy_ref[64]; /* proxy name or 1-based index; empty = default */
- bool localhost; /* PROXY rule that also proxies 127.0.0.0/8 and ::1 */
-} ProxyRule;
-
-typedef struct {
- char name[64];
- ProxyType type;
- char host[256];
- uint16_t port;
- char username[256];
- char password[256];
- uint32_t id;
- bool send_domain; /* the proxy resolves host names (default); false sends the IP address */
-} ProxyEntry;
+#define UPDATE_FEED "https://download.interceptsuite.com/proxybridge.json"
static volatile bool keep_running = false;
static int verbose_level = 0;
@@ -43,18 +17,13 @@ static int verbose_level = 0;
static void log_callback(const char* message)
{
if (verbose_level == 1 || verbose_level == 3)
- {
printf("[LOG] %s\n", message);
- }
}
static void connection_callback(const char* process_name, uint32_t pid, const char* dest_ip, uint16_t dest_port, const char* proxy_info)
{
if (verbose_level == 2 || verbose_level == 3)
- {
- printf("[CONN] %s (PID:%u) -> %s:%u via %s\n",
- process_name, pid, dest_ip, dest_port, proxy_info);
- }
+ printf("[CONN] %s (PID:%u) -> %s:%u via %s\n", process_name, pid, dest_ip, dest_port, proxy_info);
}
static void signal_handler(int sig)
@@ -80,456 +49,100 @@ static void show_banner(void)
printf("\n");
}
-static void show_help(const char* prog)
+static void show_help(void)
{
show_banner();
- printf("USAGE:\n");
- printf(" %s [OPTIONS]\n\n", prog);
-
- printf("OPTIONS:\n");
- printf(" --proxy <spec> Add a proxy (repeatable). The first one is the default.\n");
- printf(" Format: [name=]type://[user:pass@]host:port\n");
- printf(" Examples: socks5://127.0.0.1:1080\n");
- printf(" work=http://alice:[email protected]:8080\n");
- printf(" tor=socks5://[::1]:9050\n");
- printf(" Legacy form type://host:port:user:pass is still accepted.\n");
- printf(" Append ?dns=local to send IP addresses instead of host names; the default\n");
- printf(" (?dns=proxy) sends the name the application resolved, so the proxy resolves it.\n");
- printf(" Default: socks5://127.0.0.1:4444\n\n");
-
- printf(" --rule <rule> Traffic routing rule (repeatable, first match wins)\n");
- printf(" Format: process:hosts:ports:protocol:action[=proxy]\n");
- printf(" process - name or path glob(s): curl, chrom*, *, or several separated by ; or ,\n");
- printf(" hosts - IPv4/IPv6, CIDR (10.0.0.0/8), ranges (1.2.3.4-1.2.3.9),\n");
- printf(" octet patterns (192.168.*.*), domain names (github.com, *.github.com)\n");
- printf(" or *; several separated by ; or ,\n");
- printf(" (domains are matched via the DNS answers the application received)\n");
- printf(" ports - *, 443, 80;8080, 8000-9000\n");
- printf(" protocol - TCP, UDP, or BOTH\n");
- printf(" action - PROXY, DIRECT, or BLOCK; PROXY=name (or PROXY=2) picks a specific proxy;\n");
- printf(" PROXY+localhost (or PROXY=name+localhost) also proxies 127.0.0.0/8 and ::1\n");
- printf(" Examples:\n");
- printf(" curl:*:*:TCP:PROXY\n");
- printf(" firefox:*:*:BOTH:PROXY=work\n");
- printf(" curl;wget:10.0.0.0/8:*:TCP:DIRECT\n");
- printf(" *:*:53:UDP:PROXY=tor\n");
- printf(" firefox:*.github.com;github.com:443:TCP:PROXY=work\n");
- printf(" burp-client:*:8080:TCP:PROXY=work+localhost\n\n");
-
- printf(" --profile <name|file> Load proxies and rules from a .pbprofile (a file path, or the name of a profile saved\n");
- printf(" by the GUI). Same format as the Windows and macOS apps; repeatable, and can be\n");
- printf(" combined with --proxy and --rule. Disabled rules are skipped.\n");
- printf(" --list-profiles List the profiles saved by the GUI and exit\n\n");
-
- printf(" --dns-via-proxy <bool> Route DNS queries through the proxy (true/false/1/0, default true)\n\n");
-
- printf(" --log-every-connection <bool> Show every new connection in the connection log (--verbose 2/3) instead of one\n");
- printf(" line per application, destination and action (default false; a profile can set it)\n\n");
-
- printf(" --test-proxy <host[:port]> Check every configured proxy against that target (reach it, open a tunnel and log in,\n");
- printf(" load a page, time tunnels, probe UDP), print the steps and exit 0 only if all work.\n");
- printf(" Needs no root. Example: --proxy socks5://127.0.0.1:1080 --test-proxy example.com:80\n\n");
-
- printf(" --verbose <level> 0 none (default), 1 logs, 2 connections, 3 both\n\n");
-
- printf(" --cleanup No-op, kept for compatibility: the eBPF programs detach automatically\n\n");
-
- printf(" --help, -h Show this help message\n\n");
-
- printf("EXAMPLES:\n");
- printf(" sudo %s --profile work\n", prog);
- printf(" sudo %s --profile ./myconfig.pbprofile --verbose 2\n\n", prog);
- printf(" sudo %s --rule curl:*:*:TCP:PROXY\n\n", prog);
- printf(" sudo %s --proxy socks5://192.168.1.10:1080 --proxy work=http://proxy.corp:8080 \\\n", prog);
- printf(" --rule firefox:*:*:BOTH:PROXY --rule curl:*:*:TCP:PROXY=work --verbose 2\n\n");
-
- printf("NOTE:\n");
- printf(" ProxyBridge needs root and a Linux kernel >= 5.11 with BTF and cgroup v2 (eBPF datapath).\n");
- printf(" Credentials given on the command line are visible to other users via ps.\n\n");
-}
-
-static void upper_copy(char* dst, const char* src, size_t n)
-{
- size_t i = 0;
- for (; src[i] && i + 1 < n; i++)
- dst[i] = (char)toupper((unsigned char)src[i]);
- dst[i] = '\0';
-}
-
-static RuleProtocol parse_protocol(const char* str)
-{
- char upper[16];
- upper_copy(upper, str, sizeof(upper));
- if (strcmp(upper, "TCP") == 0) return RULE_PROTOCOL_TCP;
- if (strcmp(upper, "UDP") == 0) return RULE_PROTOCOL_UDP;
- if (strcmp(upper, "BOTH") == 0) return RULE_PROTOCOL_BOTH;
- fprintf(stderr, "ERROR: Invalid protocol '%s'. Use TCP, UDP, or BOTH\n", str);
- exit(1);
+ printf("Options:\n");
+ printf(" --profile <path> Path to a .pbprofile file exported from the GUI, or the name of a\n");
+ printf(" profile saved by the GUI (Proxy > Profiles)\n\n");
+ printf(" --verbose <0-3> Logging verbosity\n");
+ printf(" 0 - Silent (default)\n");
+ printf(" 1 - Log messages only\n");
+ printf(" 2 - Connection events only\n");
+ printf(" 3 - Both logs and connections\n\n");
+ printf(" --version Show version information\n");
+ printf(" -?, -h, --help Show help\n\n");
+ printf("Commands:\n");
+ printf(" --update Check for updates and print where to download the latest version\n");
+ printf(" (does not require root)\n\n");
+ printf("Examples:\n");
+ printf(" sudo ProxyBridge --profile ~/myconfig.pbprofile\n");
+ printf(" sudo ProxyBridge --profile work --verbose 2\n\n");
+ printf("Notes:\n");
+ printf(" --profile requires root and a Linux kernel >= 5.11 with BTF and cgroup v2 (eBPF datapath)\n");
+ printf(" Press Ctrl+C to stop ProxyBridge cleanly\n\n");
}
-/* action[=proxy][+localhost] */
-static RuleAction parse_action(const char* str, char* proxy_ref, size_t ref_size, bool* localhost)
+static bool is_https(const char* url)
{
- char buf[128];
- snprintf(buf, sizeof(buf), "%s", str);
- proxy_ref[0] = '\0';
- *localhost = false;
- size_t bl = strlen(buf), sl = strlen("+localhost");
- if (bl > sl && strcasecmp(buf + bl - sl, "+localhost") == 0)
- {
- buf[bl - sl] = '\0';
- *localhost = true;
- }
- char* eq = strchr(buf, '=');
- if (eq)
- {
- *eq = '\0';
- snprintf(proxy_ref, ref_size, "%s", eq + 1);
- }
- char upper[16];
- upper_copy(upper, buf, sizeof(upper));
- if (strcmp(upper, "PROXY") == 0) return RULE_ACTION_PROXY;
- if ((eq && proxy_ref[0]) || *localhost) { fprintf(stderr, "ERROR: '=proxy' and '+localhost' are only valid with PROXY\n"); exit(1); }
- if (strcmp(upper, "DIRECT") == 0) return RULE_ACTION_DIRECT;
- if (strcmp(upper, "BLOCK") == 0) return RULE_ACTION_BLOCK;
- fprintf(stderr, "ERROR: Invalid action '%s'. Use PROXY, DIRECT, or BLOCK\n", buf);
- exit(1);
-}
-
-static void default_if_empty(char* dest, const char* src, const char* default_val, size_t dest_size)
-{
- if (src == NULL || src[0] == '\0' || strcmp(src, " ") == 0)
- snprintf(dest, dest_size, "%s", default_val);
- else
- snprintf(dest, dest_size, "%.*s", (int)dest_size - 1, src);
-}
-
-/* process:hosts:ports:protocol:action[=proxy] -- hosts may itself contain ':' (IPv6), so parse from both ends */
-static bool parse_rule(const char* rule_str, ProxyRule* rule)
-{
- char buffer[MAX_RULE_STR];
- snprintf(buffer, sizeof(buffer), "%s", rule_str);
-
- char* first = strchr(buffer, ':');
- char* last = strrchr(buffer, ':');
- char* second_last = NULL;
- char* third_last = NULL;
- if (last && last != first)
- {
- *last = '\0';
- second_last = strrchr(buffer, ':');
- if (second_last && second_last != first)
- {
- *second_last = '\0';
- third_last = strrchr(buffer, ':');
- }
- }
- if (!first || !last || !second_last || !third_last || third_last == first)
- {
- fprintf(stderr, "ERROR: Invalid rule format '%s'\n", rule_str);
- fprintf(stderr, "Expected format: process:hosts:ports:protocol:action[=proxy]\n");
- return false;
- }
- *third_last = '\0';
- const char* ports = third_last + 1;
- const char* protocol = second_last + 1;
- const char* action = last + 1;
-
- char* sep = strchr(buffer, ':');
- if (!sep)
- {
- fprintf(stderr, "ERROR: Invalid rule format '%s'\n", rule_str);
- return false;
- }
- *sep = '\0';
- const char* hosts = sep + 1;
-
- default_if_empty(rule->process_name, buffer, "*", sizeof(rule->process_name));
- default_if_empty(rule->target_hosts, hosts, "*", sizeof(rule->target_hosts));
- default_if_empty(rule->target_ports, ports, "*", sizeof(rule->target_ports));
- rule->protocol = parse_protocol(protocol);
- rule->action = parse_action(action, rule->proxy_ref, sizeof(rule->proxy_ref), &rule->localhost);
- return true;
-}
-
-/* [name=]type://[user:pass@]host:port or legacy type://host:port[:user:pass] ; host may be [v6] */
-static bool parse_proxy_spec(const char* spec, ProxyEntry* p)
-{
- char buffer[768];
- snprintf(buffer, sizeof(buffer), "%s", spec);
- memset(p, 0, sizeof(*p));
- p->send_domain = true;
-
- char* scheme_end = strstr(buffer, "://");
- if (scheme_end == NULL)
- {
- fprintf(stderr, "ERROR: Invalid proxy '%s'. Expected [name=]type://host:port\n", spec);
- return false;
- }
- *scheme_end = '\0';
- char* scheme = buffer;
- char* rest = scheme_end + 3;
- char* eq = strchr(scheme, '=');
- if (eq)
- {
- *eq = '\0';
- snprintf(p->name, sizeof(p->name), "%.*s", (int)sizeof(p->name) - 1, scheme);
- scheme = eq + 1;
- }
-
- char upper_scheme[16];
- upper_copy(upper_scheme, scheme, sizeof(upper_scheme));
- if (strcmp(upper_scheme, "SOCKS5") == 0) p->type = PROXY_TYPE_SOCKS5;
- else if (strcmp(upper_scheme, "HTTP") == 0) p->type = PROXY_TYPE_HTTP;
- else
- {
- fprintf(stderr, "ERROR: Invalid proxy type '%s'. Use 'socks5' or 'http'\n", scheme);
+ if (!url || strncmp(url, "https://", 8) != 0)
return false;
- }
-
- char* at = strrchr(rest, '@');
- if (at)
- {
- *at = '\0';
- char* colon = strchr(rest, ':');
- if (colon) { *colon = '\0'; snprintf(p->password, sizeof(p->password), "%s", colon + 1); }
- snprintf(p->username, sizeof(p->username), "%s", rest);
- rest = at + 1;
- }
-
- char* query = strchr(rest, '?'); /* ?dns=proxy (default) | ?dns=local */
- if (query)
- {
- *query++ = '\0';
- if (strcasecmp(query, "dns=local") == 0) p->send_domain = false;
- else if (strcasecmp(query, "dns=proxy") != 0)
- {
- fprintf(stderr, "ERROR: Unknown proxy option '%s' in '%s'. Use dns=proxy or dns=local\n", query, spec);
+ for (const char* c = url; *c; c++)
+ if ((unsigned char)*c < 33 || *c > 126 || *c == '"' || *c == '\'' || *c == '`' || *c == '\\')
return false;
- }
- }
-
- char* port_str = NULL;
- char* legacy = NULL;
- if (rest[0] == '[')
- {
- char* close = strchr(rest, ']');
- if (!close || close[1] != ':') { fprintf(stderr, "ERROR: Invalid IPv6 proxy host in '%s'\n", spec); return false; }
- *close = '\0';
- snprintf(p->host, sizeof(p->host), "%s", rest + 1);
- port_str = close + 2;
- }
- else
- {
- char* colon = strchr(rest, ':');
- if (!colon) { fprintf(stderr, "ERROR: Invalid proxy '%s': missing port\n", spec); return false; }
- *colon = '\0';
- snprintf(p->host, sizeof(p->host), "%s", rest);
- port_str = colon + 1;
- }
- legacy = strchr(port_str, ':'); /* type://host:port:user:pass */
- if (legacy && !at)
- {
- *legacy++ = '\0';
- char* colon = strchr(legacy, ':');
- if (colon) { *colon = '\0'; snprintf(p->password, sizeof(p->password), "%s", colon + 1); }
- snprintf(p->username, sizeof(p->username), "%s", legacy);
- }
- char* endp = NULL;
- long port = strtol(port_str, &endp, 10);
- if (!*port_str || *endp || port < 1 || port > 65535)
- {
- fprintf(stderr, "ERROR: Invalid proxy port '%s'\n", port_str);
- return false;
- }
- p->port = (uint16_t)port;
- if (!p->host[0]) { fprintf(stderr, "ERROR: Proxy host is empty in '%s'\n", spec); return false; }
return true;
}
-static uint32_t find_proxy(const ProxyEntry* proxies, int n, const char* ref)
+/* --update: ask the feed with curl and print what it says. Nothing is downloaded or run. */
+static int check_update(void)
{
- if (!ref[0])
- return 0;
- char* endp = NULL;
- long idx = strtol(ref, &endp, 10);
- if (!*endp && idx >= 1 && idx <= n)
- return proxies[idx - 1].id;
- for (int i = 0; i < n; i++)
- if (strcmp(proxies[i].name, ref) == 0)
- return proxies[i].id;
- return UINT32_MAX;
-}
-
-static const char* profile_default_ref = NULL;
-static char profile_default_name[64];
-
-/* Appends the proxies and rules of a .pbprofile (a path, or the name of a profile saved by the GUI). */
-static bool load_profile(const char* arg, ProxyEntry* proxies, int* num_proxies, ProxyRule* rules, int* num_rules, bool* dns, bool* log_every)
-{
- char* path = pbp_resolve(pbp_config_dir(), arg);
- char err[256];
- struct pbp_profile prof;
- if (!path)
- {
- fprintf(stderr, "ERROR: Invalid profile '%s'\n", arg);
- return false;
- }
- if (pbp_load_file(path, &prof, err, sizeof(err)) != 0)
- {
- fprintf(stderr, "ERROR: %s\n", err);
- free(path);
- return false;
- }
-
- struct stat st;
- bool has_secret = false;
- for (size_t i = 0; i < prof.nproxies; i++)
- if (prof.proxies[i].pass[0]) has_secret = true;
- if (has_secret && stat(path, &st) == 0 && (st.st_mode & 077))
- fprintf(stderr, "WARNING: %s holds proxy credentials but other users can read it (chmod 600 recommended)\n", path);
- printf("Profile: %s\n", path);
- free(path);
-
- bool ok = true;
- if ((size_t)*num_proxies + prof.nproxies > MAX_PROXIES || (size_t)*num_rules + prof.nrules > MAX_RULES)
- {
- fprintf(stderr, "ERROR: Profile has too many proxies (max %d) or rules (max %d)\n", MAX_PROXIES, MAX_RULES);
- ok = false;
- }
- for (size_t i = 0; ok && i < prof.nproxies; i++)
- {
- ProxyEntry* p = &proxies[(*num_proxies)++];
- memset(p, 0, sizeof(*p));
- snprintf(p->name, sizeof(p->name), "%s", prof.proxies[i].name);
- p->type = prof.proxies[i].type ? PROXY_TYPE_SOCKS5 : PROXY_TYPE_HTTP;
- snprintf(p->host, sizeof(p->host), "%s", prof.proxies[i].host);
- p->port = prof.proxies[i].port;
- snprintf(p->username, sizeof(p->username), "%s", prof.proxies[i].user);
- snprintf(p->password, sizeof(p->password), "%s", prof.proxies[i].pass);
- p->send_domain = prof.proxies[i].send_domain;
- }
- for (size_t i = 0; ok && i < prof.nrules; i++)
+ const char* feed = getenv("PROXYBRIDGE_UPDATE_FEED"); /* a mirror, or a local file in tests */
+ if (!feed || !*feed)
+ feed = UPDATE_FEED;
+ int fds[2];
+ if (pipe(fds) != 0)
{
- const struct pbp_rule* r = &prof.rules[i];
- ProxyRule* out = &rules[*num_rules];
- if (strlen(r->process) >= FIELD || strlen(r->hosts) >= FIELD || strlen(r->ports) >= FIELD)
- {
- fprintf(stderr, "ERROR: Profile rule %zu has a field longer than %d characters\n", i + 1, FIELD - 1);
- ok = false;
- break;
- }
- if (!r->enabled)
- continue;
- memset(out, 0, sizeof(*out));
- snprintf(out->process_name, sizeof(out->process_name), "%s", r->process);
- snprintf(out->target_hosts, sizeof(out->target_hosts), "%s", r->hosts);
- snprintf(out->target_ports, sizeof(out->target_ports), "%s", r->ports);
- out->protocol = (RuleProtocol)r->protocol;
- out->action = (RuleAction)r->action;
- out->localhost = r->action == RULE_ACTION_PROXY && r->localhost;
- const struct pbp_proxy* px = r->action == RULE_ACTION_PROXY && r->proxy_id ? pbp_find_proxy(&prof, r->proxy_id) : NULL;
- if (px)
- snprintf(out->proxy_ref, sizeof(out->proxy_ref), "%s", px->name);
- (*num_rules)++;
+ perror("pipe");
+ return 1;
}
- if (ok && prof.default_proxy_id)
- {
- const struct pbp_proxy* d = pbp_find_proxy(&prof, prof.default_proxy_id);
- if (d)
- {
- snprintf(profile_default_name, sizeof(profile_default_name), "%s", d->name);
- profile_default_ref = profile_default_name;
- }
+ pid_t pid = fork();
+ if (pid == 0)
+ {
+ 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);
+ _exit(127);
+ }
+ close(fds[1]);
+ static char json[65536];
+ size_t n = 0;
+ ssize_t r;
+ while (pid > 0 && n < sizeof(json) - 1 && (r = read(fds[0], json + n, sizeof(json) - 1 - n)) > 0)
+ n += (size_t)r;
+ close(fds[0]);
+ int status = 0;
+ if (pid < 0 || waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0 || n == 0)
+ {
+ fprintf(stderr, "ERROR: Update check failed (could not fetch %s)\n", feed);
+ return 1;
}
- *dns = prof.dns_via_proxy;
- *log_every = prof.log_every;
- pbp_free(&prof);
- return ok;
-}
-
-static int list_profiles(void)
-{
- char dir[1024];
- snprintf(dir, sizeof(dir), "%s/profiles", pbp_config_dir());
- DIR* d = opendir(dir);
- if (!d)
+ char *version, *download, *notes;
+ if (pbp_update_parse(json, n, &version, &download, &notes) != 0)
{
- fprintf(stderr, "No profiles directory at %s\n", dir);
+ fprintf(stderr, "ERROR: Update check failed (the feed has no Linux version)\n");
return 1;
}
- struct dirent* de;
- int n = 0;
- while ((de = readdir(d)) != NULL)
+ printf("Current version: %s\n", PROXYBRIDGE_VERSION);
+ printf("Latest version: %s\n", version);
+ if (!pbp_version_newer(version, PROXYBRIDGE_VERSION))
+ printf("You are using the latest version.\n");
+ else
{
- char* name = pbp_name_from_filename(de->d_name);
- if (name)
- {
- printf("%s\n", name);
- n++;
- }
- free(name);
- }
- closedir(d);
- if (!n)
- fprintf(stderr, "No profiles in %s\n", dir);
+ printf("A newer version is available.\n");
+ if (is_https(notes))
+ printf("Release notes: %s\n", notes);
+ if (is_https(download))
+ printf("Download: %s\n", download);
+ if (!is_https(notes) && !is_https(download))
+ printf("(The feed has no safe https link; see https://github.com/InterceptSuite/ProxyBridge/releases)\n");
+ }
+ free(version);
+ free(download);
+ free(notes);
return 0;
}
-static void check_line(const char* line, void* user)
-{
- (void)user;
- printf("%s\n", line);
- fflush(stdout);
-}
-
-/* --test-proxy host[:port]: runs the multi-step check against every configured proxy; no root needed. */
-static int run_proxy_checks(ProxyEntry* proxies, int num_proxies, const char* target)
-{
- char host[256];
- unsigned long port = 80;
- snprintf(host, sizeof(host), "%s", target);
- char* colon = strrchr(host, ':');
- if (host[0] == '[')
- {
- char* close = strchr(host, ']');
- if (!close) { fprintf(stderr, "ERROR: Invalid target '%s'\n", target); return 2; }
- *close = '\0';
- memmove(host, host + 1, strlen(host));
- colon = (close[1] == ':') ? close + 1 : NULL;
- if (colon) { char* e = NULL; port = strtoul(colon + 1, &e, 10); if (!colon[1] || *e) port = 0; }
- }
- else if (colon && strchr(host, ':') == colon)
- {
- char* e = NULL;
- port = strtoul(colon + 1, &e, 10);
- if (!colon[1] || *e) port = 0;
- *colon = '\0';
- }
- if (!host[0] || port < 1 || port > 65535)
- {
- fprintf(stderr, "ERROR: Invalid target '%s'. Expected host[:port]\n", target);
- return 2;
- }
- int failed = 0;
- char err[256];
- for (int i = 0; i < num_proxies; i++)
- {
- ProxyEntry* p = &proxies[i];
- p->id = ProxyBridge_AddProxy(p->name, p->type, p->host, p->port, p->username, p->password, err, sizeof(err));
- if (!p->id)
- {
- fprintf(stderr, "ERROR: Proxy %d (%s:%u): %s\n", i + 1, p->host, p->port, err);
- return 2;
- }
- if (i)
- printf("\n");
- if (ProxyBridge_TestProxyEx(p->id, host, (uint16_t)port, check_line, NULL) != 0)
- failed++;
- }
- return failed ? 1 : 0;
-}
-
static bool is_root(void)
{
return getuid() == 0;
@@ -537,110 +150,37 @@ static bool is_root(void)
int main(int argc, char *argv[])
{
- static ProxyEntry proxies[MAX_PROXIES];
- int num_proxies = 0;
- static ProxyRule rules[MAX_RULES];
- int num_rules = 0;
- bool dns_via_proxy = true;
- bool dns_explicit = false;
- bool log_every = false, log_every_explicit = false;
- const char* test_target = NULL;
+ const char* profile_arg = NULL;
for (int i = 1; i < argc; i++)
{
- if (strcmp(argv[i], "--cleanup") == 0)
+ if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0)
{
- printf("Nothing to clean up: the eBPF programs detach automatically when ProxyBridge exits.\n");
+ show_help();
return 0;
}
- }
-
- for (int i = 1; i < argc; i++)
- {
- if (strcmp(argv[i], "--list-profiles") == 0)
- return list_profiles();
- }
-
- for (int i = 1; i < argc; i++)
- {
- if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0)
+ else if (strcmp(argv[i], "--version") == 0)
{
- show_help(argv[0]);
+ printf("ProxyBridge CLI V%s\n", PROXYBRIDGE_VERSION);
return 0;
}
- else if (strcmp(argv[i], "--proxy") == 0 && i + 1 < argc)
+ else if (strcmp(argv[i], "--update") == 0)
{
- if (num_proxies >= MAX_PROXIES)
- {
- fprintf(stderr, "ERROR: Maximum %d proxies supported\n", MAX_PROXIES);
- return 1;
- }
- if (!parse_proxy_spec(argv[++i], &proxies[num_proxies]))
- return 1;
- memset(argv[i], 0, strlen(argv[i])); /* keep credentials out of `ps` */
- num_proxies++;
+ return check_update();
}
else if (strcmp(argv[i], "--profile") == 0 && i + 1 < argc)
{
- bool dns = dns_via_proxy, every = log_every;
- if (!load_profile(argv[++i], proxies, &num_proxies, rules, &num_rules, &dns, &every))
- return 1;
- if (!dns_explicit)
- dns_via_proxy = dns;
- if (!log_every_explicit)
- log_every = every;
- }
- else if (strcmp(argv[i], "--rule") == 0 && i + 1 < argc)
- {
- if (num_rules >= MAX_RULES)
- {
- fprintf(stderr, "ERROR: Maximum %d rules supported\n", MAX_RULES);
- return 1;
- }
- if (!parse_rule(argv[++i], &rules[num_rules]))
- return 1;
- num_rules++;
- }
- else if (strcmp(argv[i], "--dns-via-proxy") == 0 && i + 1 < argc)
- {
- char* value = argv[++i];
- dns_explicit = true;
- if (strcmp(value, "true") == 0 || strcmp(value, "1") == 0)
- dns_via_proxy = true;
- else if (strcmp(value, "false") == 0 || strcmp(value, "0") == 0)
- dns_via_proxy = false;
- else
- {
- fprintf(stderr, "ERROR: Invalid value for --dns-via-proxy. Use: true, false, 1, or 0\n");
- return 1;
- }
- }
- else if (strcmp(argv[i], "--log-every-connection") == 0 && i + 1 < argc)
- {
- char* value = argv[++i];
- log_every_explicit = true;
- if (strcmp(value, "true") == 0 || strcmp(value, "1") == 0)
- log_every = true;
- else if (strcmp(value, "false") == 0 || strcmp(value, "0") == 0)
- log_every = false;
- else
- {
- fprintf(stderr, "ERROR: Invalid value for --log-every-connection. Use: true, false, 1, or 0\n");
- return 1;
- }
- }
- else if (strcmp(argv[i], "--test-proxy") == 0 && i + 1 < argc)
- {
- test_target = argv[++i];
+ profile_arg = argv[++i];
}
else if (strcmp(argv[i], "--verbose") == 0 && i + 1 < argc)
{
- verbose_level = atoi(argv[++i]);
- if (verbose_level < 0 || verbose_level > 3)
+ const char* v = argv[++i];
+ if (strlen(v) != 1 || v[0] < '0' || v[0] > '3')
{
fprintf(stderr, "ERROR: Verbose level must be 0-3\n");
return 1;
}
+ verbose_level = v[0] - '0';
}
else
{
@@ -650,15 +190,59 @@ int main(int argc, char *argv[])
}
}
- if (num_proxies == 0)
+ if (!profile_arg)
{
- if (!parse_proxy_spec("socks5://127.0.0.1:4444", &proxies[0]))
- return 1;
- num_proxies = 1;
+ fprintf(stderr, "ERROR: No profile specified.\n");
+ fprintf(stderr, "Usage: ProxyBridge --profile <file.pbprofile>\n\n");
+ return 1;
}
- if (test_target)
- return run_proxy_checks(proxies, num_proxies, test_target);
+ char err[256];
+ char* path = pbp_resolve(pbp_config_dir(), profile_arg);
+ struct pbp_profile prof;
+ if (!path)
+ {
+ fprintf(stderr, "ERROR: Invalid profile '%s'\n", profile_arg);
+ return 1;
+ }
+ printf("Loading profile: %s\n", path);
+ if (pbp_load_file(path, &prof, err, sizeof(err)) != 0)
+ {
+ fprintf(stderr, "ERROR: %s\n", err);
+ free(path);
+ return 1;
+ }
+
+ struct stat st;
+ bool has_secret = false;
+ for (size_t i = 0; i < prof.nproxies; i++)
+ if (prof.proxies[i].pass[0])
+ has_secret = true;
+ if (has_secret && stat(path, &st) == 0 && (st.st_mode & 077))
+ fprintf(stderr, "WARNING: %s holds proxy credentials but other users can read it (chmod 600 recommended)\n", path);
+ free(path);
+
+ size_t enabled = 0;
+ bool needs_proxy = false;
+ for (size_t i = 0; i < prof.nrules; i++)
+ if (prof.rules[i].enabled)
+ {
+ enabled++;
+ if (prof.rules[i].action == RULE_ACTION_PROXY)
+ needs_proxy = true;
+ }
+ if (enabled == 0)
+ {
+ fprintf(stderr, "ERROR: Profile contains no enabled rules.\n");
+ pbp_free(&prof);
+ return 1;
+ }
+ if (needs_proxy && prof.nproxies == 0)
+ {
+ fprintf(stderr, "ERROR: A rule uses a proxy but the profile has no proxy server.\n");
+ pbp_free(&prof);
+ return 1;
+ }
show_banner();
@@ -666,88 +250,65 @@ int main(int argc, char *argv[])
{
printf("\033[31m\nERROR: ProxyBridge requires root privileges!\033[0m\n");
printf("Please run this application with sudo or as root.\n\n");
+ pbp_free(&prof);
return 1;
}
- if (verbose_level == 1 || verbose_level == 3)
- ProxyBridge_SetLogCallback(log_callback);
- else
- ProxyBridge_SetLogCallback(NULL);
-
- if (verbose_level == 2 || verbose_level == 3)
- ProxyBridge_SetConnectionCallback(connection_callback);
- else
- ProxyBridge_SetConnectionCallback(NULL);
-
+ ProxyBridge_SetLogCallback(verbose_level == 1 || verbose_level == 3 ? log_callback : NULL);
+ ProxyBridge_SetConnectionCallback(verbose_level == 2 || verbose_level == 3 ? connection_callback : NULL);
ProxyBridge_SetTrafficLoggingEnabled(verbose_level > 0);
- ProxyBridge_SetDnsViaProxy(dns_via_proxy);
- ProxyBridge_SetLogEveryConnection(log_every);
+ ProxyBridge_SetDnsViaProxy(prof.dns_via_proxy);
+ ProxyBridge_SetLogEveryConnection(prof.log_every);
- char err[256];
- printf("Proxies: %d\n", num_proxies);
- for (int i = 0; i < num_proxies; i++)
+ uint32_t ids[PBP_MAX_PROXIES + 1] = { 0 };
+ printf("Proxies: %zu\n", prof.nproxies);
+ for (size_t i = 0; i < prof.nproxies; i++)
{
- ProxyEntry* p = &proxies[i];
- p->id = ProxyBridge_AddProxy(p->name, p->type, p->host, p->port, p->username, p->password, err, sizeof(err));
- if (!p->id)
+ 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])
{
- fprintf(stderr, "ERROR: Proxy %d (%s:%u): %s\n", i + 1, p->host, p->port, err);
+ fprintf(stderr, "ERROR: Proxy '%s' (%s:%u): %s\n", p->name, p->host, p->port, err);
+ pbp_free(&prof);
return 1;
}
if (!p->send_domain)
- ProxyBridge_SetProxySendDomain(p->id, false);
- printf(" [%d]%s%s%s %s://%s:%u%s%s\n", i + 1, p->name[0] ? " " : "", p->name, i == 0 ? " (default)" : "",
- p->type == PROXY_TYPE_HTTP ? "http" : "socks5", p->host, p->port, p->username[0] ? " (auth)" : "",
- p->send_domain ? "" : " (dns:local)");
- }
- if (profile_default_ref)
- {
- uint32_t def = find_proxy(proxies, num_proxies, profile_default_ref);
- if (def != UINT32_MAX && def != 0)
- ProxyBridge_SetDefaultProxy(def);
+ ProxyBridge_SetProxySendDomain(ids[i], false);
+ printf(" [%zu] %s %s://%s:%u%s%s\n", i + 1, p->name, p->type ? "socks5" : "http", p->host, p->port,
+ p->user[0] ? " (auth)" : "", p->send_domain ? "" : " (dns:local)");
}
- printf("DNS via Proxy: %s\n", dns_via_proxy ? "Enabled" : "Disabled");
+ if (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]);
+ printf("DNS via Proxy: %s\n", prof.dns_via_proxy ? "Enabled" : "Disabled");
- if (num_rules > 0)
+ printf("Rules: %zu\n", enabled);
+ for (size_t i = 0; i < prof.nrules; i++)
{
- printf("Rules: %d\n", num_rules);
- for (int i = 0; i < num_rules; 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 rule_id = ProxyBridge_AddRule(r->process, r->hosts, r->ports, (RuleProtocol)r->protocol, (RuleAction)r->action, proxy_id, err, sizeof(err));
+ if (!rule_id)
{
- const char* protocol_str = rules[i].protocol == RULE_PROTOCOL_TCP ? "TCP" :
- rules[i].protocol == RULE_PROTOCOL_UDP ? "UDP" : "BOTH";
- const char* action_str = rules[i].action == RULE_ACTION_PROXY ? "PROXY" :
- rules[i].action == RULE_ACTION_DIRECT ? "DIRECT" : "BLOCK";
- uint32_t proxy_id = 0;
- if (rules[i].action == RULE_ACTION_PROXY)
- {
- proxy_id = find_proxy(proxies, num_proxies, rules[i].proxy_ref);
- if (proxy_id == UINT32_MAX)
- {
- fprintf(stderr, "ERROR: Rule %d refers to unknown proxy '%s'\n", i + 1, rules[i].proxy_ref);
- return 1;
- }
- }
-
- uint32_t rule_id = ProxyBridge_AddRule(rules[i].process_name, rules[i].target_hosts, rules[i].target_ports,
- rules[i].protocol, rules[i].action, proxy_id, err, sizeof(err));
- if (rule_id == 0)
- {
- fprintf(stderr, " ERROR: Rule %d (%s:%s:%s): %s\n", i + 1, rules[i].process_name,
- rules[i].target_hosts, rules[i].target_ports, err);
- return 1;
- }
- if (rules[i].localhost)
- ProxyBridge_SetRuleLocalhost(rule_id, true);
- printf(" [%u] %s:%s:%s:%s -> %s%s%s%s\n", rule_id, rules[i].process_name, rules[i].target_hosts,
- rules[i].target_ports, protocol_str, action_str,
- rules[i].proxy_ref[0] ? " via " : "", rules[i].proxy_ref, rules[i].localhost ? " (+localhost)" : "");
+ fprintf(stderr, " ERROR: Rule %zu (%s:%s:%s): %s\n", i + 1, r->process, r->hosts, r->ports, err);
+ pbp_free(&prof);
+ return 1;
}
+ if (r->localhost && r->action == RULE_ACTION_PROXY)
+ ProxyBridge_SetRuleLocalhost(rule_id, true);
+ printf(" [%u] %s:%s:%s:%s -> %s%s\n", rule_id, r->process, r->hosts, r->ports,
+ r->protocol == 0 ? "TCP" : r->protocol == 1 ? "UDP" : "BOTH",
+ r->action == RULE_ACTION_PROXY ? "PROXY" : r->action == RULE_ACTION_DIRECT ? "DIRECT" : "BLOCK",
+ r->localhost && r->action == RULE_ACTION_PROXY ? " (+localhost)" : "");
}
- else
- {
- printf("\033[33mWARNING: No rules specified. No traffic will be proxied.\033[0m\n");
- printf("Use --rule to add proxy rules. See --help for examples.\n");
- }
+ pbp_free(&prof);
if (!ProxyBridge_Start())
{
diff --git a/Linux/gui/tests/list_test.c b/Linux/gui/tests/list_test.c
index 65187a9..4cbe802 100644
--- a/Linux/gui/tests/list_test.c
+++ b/Linux/gui/tests/list_test.c
@@ -23,7 +23,7 @@ int main(void) {
norm("a b ; c", "a b;c");
norm("\x01x\x02;y", "x;y");
norm("\xc3\xa9xample.com;\n b.org", "\xc3\xa9xample.com;b.org"); // UTF-8 passes through
- CHECK(list_normalize(NULL) != NULL);
+ { char *nn = list_normalize(NULL); CHECK(nn != NULL); g_free(nn); }
char *f = list_format("a;b;c"); CHECK(!strcmp(f, "a;\nb;\nc")); g_free(f);
f = list_format(""); CHECK(!strcmp(f, "")); g_free(f);
diff --git a/Linux/profile/pb_profile.c b/Linux/profile/pb_profile.c
index 317460c..a5f3127 100644
--- a/Linux/profile/pb_profile.c
+++ b/Linux/profile/pb_profile.c
@@ -789,6 +789,57 @@ int pbp_settings_save(const char *path, const char *active, bool check_updates,
return rc;
}
+// ---- update feed ----
+
+int pbp_update_parse(const char *json, size_t len, char **version, char **download, char **notes)
+{
+ char err[100];
+ char *copy = malloc(len + 1);
+ if (!copy) return -1;
+ memcpy(copy, json, len);
+ copy[len] = 0;
+ struct jp j = { copy, copy + len, 0, err, sizeof err };
+ struct jv root = {0};
+ int rc = parse_value(&j, &root, 0) == 0 && root.t == J_OBJ ? 0 : -1;
+ const struct jv *lin = rc == 0 ? jget(&root, "linux") : NULL;
+ *version = *download = *notes = NULL;
+ if (lin && lin->t == J_OBJ) {
+ *version = jtext(lin, "version");
+ *download = jtext(lin, "download");
+ *notes = jtext(lin, "release_notes");
+ }
+ if (!*version || !**version) {
+ free(*version); free(*download); free(*notes);
+ *version = *download = *notes = NULL;
+ rc = -1;
+ }
+ jfree(&root);
+ free(copy);
+ return rc;
+}
+
+static void version_parts(const char *s, long out[3])
+{
+ out[0] = out[1] = out[2] = 0;
+ while (*s && (*s < '0' || *s > '9')) s++;
+ for (int i = 0; i < 3 && *s; i++) {
+ long n = 0;
+ while (*s >= '0' && *s <= '9') { n = n * 10 + (*s - '0'); if (n > 1000000) n = 1000000; s++; }
+ out[i] = n;
+ if (*s == '.') s++; else break;
+ }
+}
+
+bool pbp_version_newer(const char *candidate, const char *current)
+{
+ long a[3], b[3];
+ version_parts(candidate ? candidate : "", a);
+ version_parts(current ? current : "", b);
+ for (int i = 0; i < 3; i++)
+ if (a[i] != b[i]) return a[i] > b[i];
+ return false;
+}
+
// ---- log filters ----
static bool ci_glob(const char *p, const char *s)
diff --git a/Linux/profile/pb_profile.h b/Linux/profile/pb_profile.h
index b473331..3ee6ee9 100644
--- a/Linux/profile/pb_profile.h
+++ b/Linux/profile/pb_profile.h
@@ -99,6 +99,11 @@ char *pbp_resolve(const char *dir, const char *name_or_path);
void pbp_split_hosts(const char *hosts, char **ips, char **domains);
char *pbp_merge_hosts(const char *ips, const char *domains);
+// The update feed: {"linux": {"version": "...", "download": "...", "release_notes": "..."}, ...}. 0 if there is a linux version.
+int pbp_update_parse(const char *json, size_t len, char **version, char **download, char **notes);
+// Is `candidate` a higher version than `current`? Numeric parts only (4.0.0-Beta equals 4.0.0).
+bool pbp_version_newer(const char *candidate, const char *current);
+
struct pbp_proxy *pbp_find_proxy(const struct pbp_profile *p, uint32_t id);
#endif
diff --git a/Linux/profile/tests/profile_test.c b/Linux/profile/tests/profile_test.c
index dedea27..cf2d8f7 100644
--- a/Linux/profile/tests/profile_test.c
+++ b/Linux/profile/tests/profile_test.c
@@ -199,6 +199,27 @@ static void test_settings(void)
CHECK(system(cmd) == 0);
}
+static void test_update_feed(void)
+{
+ char *v, *d, *n;
+ const char *feed = "{ \"windows\": { \"version\": \"4.3.0\" }, \"linux\": { \"version\": \"4.1.0\", \"download\": \"https://x/d\", \"release_notes\": \"https://x/n\" } }";
+ CHECK(pbp_update_parse(feed, strlen(feed), &v, &d, &n) == 0 && !strcmp(v, "4.1.0") && !strcmp(d, "https://x/d") && !strcmp(n, "https://x/n"));
+ free(v); free(d); free(n);
+ 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 *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);
+
+ CHECK(pbp_version_newer("4.0.1", "4.0.0") && pbp_version_newer("4.1.0", "4.0.9") && pbp_version_newer("5.0.0", "4.9.9"));
+ CHECK(!pbp_version_newer("4.0.0", "4.0.0") && !pbp_version_newer("3.2.0", "4.0.0"));
+ CHECK(!pbp_version_newer("4.0.0", "4.0.0-Beta") && !pbp_version_newer("4.0.0-Beta", "4.0.0")); // a suffix is ignored
+ CHECK(pbp_version_newer("v4.0.1", "4.0.0-Beta") && pbp_version_newer("10.0.0", "9.0.0") && pbp_version_newer("4.0", "3.9.9"));
+ CHECK(!pbp_version_newer("", "1.0.0") && !pbp_version_newer("junk", "0.0.0") && !pbp_version_newer(NULL, "1.0.0"));
+ CHECK(pbp_version_newer("1.0.0", "") && pbp_version_newer("99999999999999999999.0.0", "1.0.0"));
+}
+
static void test_roundtrip(void)
{
struct pbp_profile a, b;
@@ -422,6 +443,7 @@ int main(void)
test_gui_fields();
test_filters();
test_settings();
+ test_update_feed();
test_errors();
test_leniency();
test_hosts();
diff --git a/Linux/setup.sh b/Linux/setup.sh
index 6e5af11..a3c40e5 100644
--- a/Linux/setup.sh
+++ b/Linux/setup.sh
@@ -227,7 +227,7 @@ main() {
if [ -f /usr/local/bin/ProxyBridgeGUI ]; then
echo " sudo ProxyBridgeGUI (Graphical Interface)"
fi
- echo " sudo ProxyBridge --proxy socks5://IP:PORT --rule \"app:*:*:TCP:PROXY\""
+ echo " sudo ProxyBridge --profile <name or .pbprofile path>"
echo ""
echo "No cleanup is needed after a crash: the kernel detaches the eBPF programs automatically."
echo ""
diff --git a/Linux/tests/check_probe.c b/Linux/tests/check_probe.c
new file mode 100644
index 0000000..e441ea7
--- /dev/null
+++ b/Linux/tests/check_probe.c
@@ -0,0 +1,27 @@
+/* Test helper: runs the library's multi-step proxy check (what the GUI's "Test connection" shows).
+ * check_probe <name> <socks5|http> <host> <port> <user|-> <pass|-> <target host> <target port> [more proxies: 6 args each]
+ * Exit status: 0 all passed, 1 some failed, 2 bad arguments. No root needed. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "../src/ProxyBridge.h"
+
+static void line(const char* s, void* u) { (void)u; printf("%s\n", s); fflush(stdout); }
+
+int main(int argc, char** argv)
+{
+ if (argc < 9 || (argc - 3) % 6) { fprintf(stderr, "usage: see source\n"); return 2; }
+ const char* th = argv[argc - 2]; long tp = strtol(argv[argc - 1], NULL, 10);
+ if (!th[0] || tp < 1 || tp > 65535) { fprintf(stderr, "ERROR: Invalid target\n"); return 2; }
+ int failed = 0;
+ for (int i = 1; i + 5 < argc - 1; i += 6) {
+ char err[256];
+ ProxyType t = strcmp(argv[i + 1], "http") ? PROXY_TYPE_SOCKS5 : PROXY_TYPE_HTTP;
+ const char* u = strcmp(argv[i + 4], "-") ? argv[i + 4] : "";
+ const char* p = strcmp(argv[i + 5], "-") ? argv[i + 5] : "";
+ uint32_t id = ProxyBridge_AddProxy(argv[i], t, argv[i + 2], (uint16_t)atoi(argv[i + 3]), u, p, err, sizeof err);
+ if (!id) { fprintf(stderr, "ERROR: %s\n", err); return 2; }
+ if (ProxyBridge_TestProxyEx(id, th, (uint16_t)tp, line, NULL) != 0) failed++;
+ }
+ return failed ? 1 : 0;
+}
diff --git a/Linux/tests/dnsbench.sh b/Linux/tests/dnsbench.sh
index c39ec01..5e06151 100755
--- a/Linux/tests/dnsbench.sh
+++ b/Linux/tests/dnsbench.sh
@@ -5,6 +5,7 @@ set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"; N=${1:-20000}
PB_DIR="${PB_DIR:-$ROOT/output}" # directory holding the built ProxyBridge + libproxybridge.so (run ../build.sh first)
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first: (cd Linux && ./build.sh), or set PB_DIR to a directory containing ProxyBridge and libproxybridge.so"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
export LD_LIBRARY_PATH="$PB_DIR"; DNSIP=10.77.0.3
WORK=$(mktemp -d); trap 'kill $DNS $PB 2>/dev/null; wait 2>/dev/null; ip addr del $DNSIP/32 dev lo 2>/dev/null; rm -rf $WORK' EXIT
ip addr add $DNSIP/32 dev lo 2>/dev/null
@@ -24,10 +25,10 @@ print(" %d queries: %.0f qps avg=%.0fus p50=%.0fus p99=%.0fus" % (n, n / dt, s
PY
}
echo "== no ProxyBridge"; bench; bench
-stdbuf -oL "$PB_DIR/ProxyBridge" --proxy a=socks5://127.0.0.1:19080 --rule "*:*.example.test:*:TCP:PROXY=a" > $WORK/pb.out 2>&1 & PB=$!
+stdbuf -oL "$PBL" --proxy a=socks5://127.0.0.1:19080 --rule "*:*.example.test:*:TCP:PROXY=a" > $WORK/pb.out 2>&1 & PB=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" $WORK/pb.out && break; sleep 0.25; done
echo "== ProxyBridge running, python3 covered by a domain rule (every query goes through the DNS tap)"; bench; bench
kill -INT $PB; wait $PB 2>/dev/null
-stdbuf -oL "$PB_DIR/ProxyBridge" --proxy a=socks5://127.0.0.1:19080 --rule "someother:*.example.test:*:TCP:PROXY=a" > $WORK/pb.out 2>&1 & PB=$!
+stdbuf -oL "$PBL" --proxy a=socks5://127.0.0.1:19080 --rule "someother:*.example.test:*:TCP:PROXY=a" > $WORK/pb.out 2>&1 & PB=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" $WORK/pb.out && break; sleep 0.25; done
echo "== ProxyBridge running, python3 NOT covered (DNS untouched by the tap)"; bench; bench
diff --git a/Linux/tests/e2e.sh b/Linux/tests/e2e.sh
index 2607b05..77f7351 100755
--- a/Linux/tests/e2e.sh
+++ b/Linux/tests/e2e.sh
@@ -6,6 +6,7 @@ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}" # directory holding the built ProxyBridge + libproxybridge.so (run ../build.sh first)
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first: (cd Linux && ./build.sh), or set PB_DIR to a directory containing ProxyBridge and libproxybridge.so"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
WORK="$(mktemp -d)"
LOG="$WORK/proxy.log"; : > "$LOG"
PASS=0; FAIL=0
@@ -29,7 +30,7 @@ sleep 1
cp "$(command -v curl)" "$WORK/newcurl" # a binary that did not exist when ProxyBridge started
-stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 3 \
+stdbuf -oL "$PBL" --verbose 3 \
--proxy a=socks5://127.0.0.1:19080 --proxy b=socks5://bob:[email protected]:19081 --proxy c=http://127.0.0.1:19082 \
--rule "curl:$MYIP/32:18399:TCP:DIRECT" \
--rule "curl:192.0.2.0/24:*:TCP:PROXY=a" \
diff --git a/Linux/tests/e2e_checker.sh b/Linux/tests/e2e_checker.sh
index 1d89f49..25dfefe 100755
--- a/Linux/tests/e2e_checker.sh
+++ b/Linux/tests/e2e_checker.sh
@@ -1,5 +1,5 @@
#!/bin/bash
-# `ProxyBridge --test-proxy host[:port]`: the multi-step proxy check, against working and broken proxies. Needs python3 (no root).
+# The library's multi-step (what the GUI's Test connection runs, via tests/check_probe.c) proxy check, against working and broken proxies. Needs python3 (no root).
# Linux/tests/e2e_checker.sh
set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
@@ -11,16 +11,39 @@ bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
cleanup() { kill $F1 $F2 2>/dev/null; wait 2>/dev/null; rm -rf "$WORK"; }
trap cleanup EXIT
export LD_LIBRARY_PATH="$PB_DIR"
+gcc -Wall -Wextra -O1 -I"$ROOT/src" -o "$WORK/check_probe" "$HERE/check_probe.c" -L"$PB_DIR" -lproxybridge || exit 1
python3 "$HERE/fake_proxies.py" "$WORK/proxy.log" > /dev/null 2>&1 & F1=$!
python3 "$HERE/fault_proxies.py" "$WORK/fault.log" > /dev/null 2>&1 & F2=$!
sleep 1.5
+# turns "--proxy name=type://[user:pw@]host:port ... --test-proxy host[:port]" into check_probe arguments
+probe_args() {
+ local out=() tgt="" th tp
+ while [ $# -gt 0 ]; do
+ case "$1" in
+ --proxy) local spec="$2" nm="p" ty u="-" pw="-" hp; shift 2
+ [[ "$spec" == *=* ]] && { nm="${spec%%=*}"; spec="${spec#*=}"; }
+ ty="${spec%%://*}"; spec="${spec#*://}"
+ [[ "$spec" == *@* ]] && { u="${spec%%:*}"; pw="${spec#*:}"; pw="${pw%%@*}"; spec="${spec#*@}"; }
+ out+=("$nm" "$ty" "${spec%:*}" "${spec##*:}" "$u" "$pw");;
+ --test-proxy) tgt="$2"; shift 2;;
+ *) shift;;
+ esac
+ done
+ if [[ "$tgt" == \[*\]* ]]; then th="${tgt%%]*}"; th="${th#[}"; tp="${tgt##*]}"; tp="${tp#:}"
+ elif [[ "$tgt" == *:* ]]; then th="${tgt%%:*}"; tp="${tgt#*:}"
+ else th="$tgt"; tp=""; fi
+ [ -z "$tp" ] && [[ "$tgt" != *:* || "$tgt" == \[*\] ]] && tp=80
+ printf '%s\n' "${out[@]}" "$th" "$tp"
+}
+
# check <name> <expected exit> <needle>... -- <ProxyBridge args>
check() {
local name="$1" want_rc="$2"; shift 2
local needles=()
while [ "$1" != "--" ]; do needles+=("$1"); shift; done; shift
- local out; out=$(timeout 60 "$PB_DIR/ProxyBridge" "$@" 2>&1); local rc=$?
+ local out; local pa; mapfile -t pa < <(probe_args "$@")
+ out=$(timeout 60 "$WORK/check_probe" "${pa[@]}" 2>&1); local rc=$?
if [ "$rc" != "$want_rc" ]; then bad "$name (exit $rc, wanted $want_rc: ${out:0:300})"; return; fi
for n in "${needles[@]}"; do
if [[ "$out" != *"$n"* ]]; then bad "$name (output lacks '$n': ${out:0:400})"; return; fi
@@ -58,8 +81,5 @@ echo "== bad arguments"
check "empty host" 2 "Invalid target" -- --proxy a=socks5://127.0.0.1:19080 --test-proxy :80
check "port out of range" 2 "Invalid target" -- --proxy a=socks5://127.0.0.1:19080 --test-proxy example.test:99999
check "port that is not a number" 2 "Invalid target" -- --proxy a=socks5://127.0.0.1:19080 --test-proxy example.test:http
-echo '{ "ProxyConfigs": [ { "Id": 1, "Name": "p1", "Type": "socks5", "Host": "127.0.0.1", "Port": "19080" } ] }' > "$WORK/p.pbprofile"; chmod 600 "$WORK/p.pbprofile"
-check "profile proxies are checked too (again, file present)" 0 "Proxy: p1" "Result: PASSED" -- --profile "$WORK/p.pbprofile" --test-proxy example.test:80
-
echo; echo "passed=$PASS failed=$FAIL"
[ "$FAIL" = 0 ]
diff --git a/Linux/tests/e2e_cli.sh b/Linux/tests/e2e_cli.sh
index cb7b0a1..77f2042 100755
--- a/Linux/tests/e2e_cli.sh
+++ b/Linux/tests/e2e_cli.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Command line: every way to get the arguments wrong, and the ways to get them right, without ever starting the engine.
-# Works as any user (valid specs are checked through --test-proxy, which needs no root). Linux/tests/e2e_cli.sh
+# Command line (the same options as the Windows CLI: --profile, --verbose, --version, -?/-h/--help, --update): every way to get
+# them wrong and right, without ever starting the engine. Works as any user. Linux/tests/e2e_cli.sh
set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}"
@@ -20,99 +20,75 @@ t() {
if [ "$needle" != "-" ] && [[ "$out" != *"$needle"* ]]; then bad "$name (output lacks '$needle': ${out:0:240})"; return; fi
ok "$name"
}
-# a proxy spec that parses is reported by --test-proxy ("Proxy: ..."); one that does not is an error before that
-parses() { t "$1" 1 "Proxy:" -- --proxy "$2" --test-proxy 127.0.0.1:9; }
-rejects() { t "$1" 1 "$3" -- --proxy "$2" --test-proxy 127.0.0.1:9; }
-echo "== help, version, small commands"
-t "--help" 0 "--proxy" -- --help
-t "-h" 0 "--rule" -- -h
-t "help documents the new options" 0 "--test-proxy" -- --help
-t "help documents profiles" 0 "--profile" -- --help
-t "--cleanup is a harmless no-op" 0 "Nothing to clean up" -- --cleanup
-t "--list-profiles without a profiles directory" 1 "No profiles directory" -- --list-profiles
-mkdir -p "$WORK/cfg/profiles"
-t "--list-profiles with an empty directory" 0 "No profiles" -- --list-profiles
-echo '{}' > "$WORK/cfg/profiles/A b.pbprofile"; echo '{}' > "$WORK/cfg/profiles/plain.pbprofile"; echo x > "$WORK/cfg/profiles/ignored.txt"
-out=$("$PB_DIR/ProxyBridge" --list-profiles 2>&1)
-[[ "$out" == *"A b"* && "$out" == *"plain"* && "$out" != *"ignored"* ]] && ok "--list-profiles lists exactly the .pbprofile files" || bad "list: $out"
+secure() { chmod 600 "$1"; }
+echo "== help and version"
+t "--help" 0 "--profile" -- --help
+t "-h" 0 "--verbose" -- -h
+t "-?" 0 "--update" -- '-?'
+t "help documents verbosity levels" 0 "Silent" -- --help
+t "help documents the version option" 0 "--version" -- --help
+t "--version" 0 "ProxyBridge CLI V" -- --version
+out=$("$PB_DIR/ProxyBridge" --help 2>&1)
+for gone in --proxy --rule --dns-via-proxy --log-every-connection --test-proxy --list-profiles --cleanup; do
+ [[ "$out" != *"$gone"* ]] && ok "help no longer lists $gone" || bad "help still lists $gone"
+ t "$gone is rejected" 1 "Unknown option '$gone'" -- "$gone"
+done
echo "== unknown and incomplete options"
t "unknown option" 1 "Unknown option '--bogus'" -- --bogus
t "stray argument" 1 "Unknown option 'stray'" -- stray
-t "--proxy without a value" 1 "Unknown option '--proxy'" -- --proxy
-t "--rule without a value" 1 "Unknown option '--rule'" -- --rule
t "--profile without a value" 1 "Unknown option '--profile'" -- --profile
-t "--test-proxy without a value" 1 "Unknown option '--test-proxy'" -- --test-proxy
t "--verbose without a value" 1 "Unknown option '--verbose'" -- --verbose
t "--verbose out of range" 1 "Verbose level must be 0-3" -- --verbose 9
t "--verbose negative" 1 "Verbose level must be 0-3" -- --verbose -1
-t "--dns-via-proxy with a bad value" 1 "Invalid value for --dns-via-proxy" -- --dns-via-proxy maybe
-t "--log-every-connection with a bad value" 1 "Invalid value for --log-every-connection" -- --log-every-connection 2
-
-echo "== proxy specs that are accepted"
-parses "socks5" "socks5://127.0.0.1:1"
-parses "http" "http://127.0.0.1:1"
-parses "uppercase scheme" "SOCKS5://127.0.0.1:1"
-parses "named" "work=socks5://127.0.0.1:1"
-parses "user and password" "socks5://bob:[email protected]:1"
-parses "password with a colon and an at sign" "socks5://bob:p:w@[email protected]:1"
-parses "legacy host:port:user:pass" "socks5://127.0.0.1:1:bob:pw"
-parses "IPv6 proxy address" "socks5://[::1]:1"
-parses "host name" "socks5://localhost:1"
-parses "dns=local" "socks5://127.0.0.1:1?dns=local"
-parses "dns=proxy" "socks5://127.0.0.1:1?dns=proxy"
-parses "port 65535" "socks5://127.0.0.1:65535"
-t "credentials are reported as present, never shown" 1 "with credentials" -- --proxy "a=socks5://bob:[email protected]:1" --test-proxy 127.0.0.1:9
-out=$("$PB_DIR/ProxyBridge" --proxy "a=socks5://bob:[email protected]:1" --test-proxy 127.0.0.1:9 2>&1)
-[[ "$out" != *topsecret* ]] && ok "the password never appears in the output" || bad "password printed"
-
-echo "== proxy specs that are refused"
-rejects "no scheme" "127.0.0.1:1080" "Expected [name=]type://host:port"
-rejects "unknown scheme" "ftp://127.0.0.1:1" "Invalid proxy type"
-rejects "missing port" "socks5://127.0.0.1" "missing port"
-rejects "port zero" "socks5://127.0.0.1:0" "Invalid proxy port"
-rejects "port too large" "socks5://127.0.0.1:65536" "Invalid proxy port"
-rejects "port not a number" "socks5://127.0.0.1:abc" "Invalid proxy port"
-rejects "empty host" "socks5://:1080" "host is empty"
-rejects "IPv6 without closing bracket" "socks5://[::1:1080" "Invalid IPv6 proxy host"
-rejects "unknown option after ?" "socks5://127.0.0.1:1?dns=maybe" "Unknown proxy option"
-t "too many proxies" 1 "Maximum 64 proxies" -- $(for i in $(seq 65); do printf -- '--proxy socks5://127.0.0.1:%d ' $((1000 + i)); done)
-
-echo "== rule specs that are refused"
-r() { t "$1" 1 "$3" -- --rule "$2"; }
-r "no colons at all" "curl" "Invalid rule format"
-r "too few fields" "curl:*:*:TCP" "Invalid rule format"
-r "bad protocol" "curl:*:*:ICMP:PROXY" "Invalid protocol"
-r "bad action" "curl:*:*:TCP:ALLOW" "Invalid action"
-r "empty protocol" "::::PROXY" "Invalid protocol"
-r "proxy on DIRECT" "curl:*:*:TCP:DIRECT=a" "only valid with PROXY"
-r "+localhost on BLOCK" "curl:*:*:TCP:BLOCK+localhost" "only valid with PROXY"
-r "+localhost on DIRECT" "curl:*:*:TCP:DIRECT+localhost" "only valid with PROXY"
-t "too many rules" 1 "Maximum 1024 rules" -- $(for i in $(seq 1025); do printf -- '--rule curl:*:*:TCP:DIRECT '; done)
-
-echo "== rule specs that parse (--test-proxy stops before the engine)"
-for spec in "curl:*:*:TCP:PROXY" "curl:10.0.0.0/8:80;443:UDP:DIRECT" "curl;wget:*:*:BOTH:BLOCK" "*:*.github.com:443:TCP:PROXY=a" \
- "curl:2001:db8::1:80:TCP:PROXY" "curl:[::1]:80:TCP:PROXY" "curl:*:*:tcp:proxy" "curl:*:*:TCP:PROXY=a+localhost" "curl:*:*:TCP:PROXY+LOCALHOST"; do
- out=$("$PB_DIR/ProxyBridge" --proxy a=socks5://127.0.0.1:1 --rule "$spec" --test-proxy 127.0.0.1:9 2>&1)
- [[ "$out" == *"Proxy:"* && "$out" != *"Invalid"* ]] && ok "rule accepted: $spec" || bad "rule '$spec': ${out:0:200}"
-done
-
-echo "== target of --test-proxy"
-for tg in "example.test" "example.test:80" "198.51.100.1:8080" "[2001:db8::1]:443" "[2001:db8::1]"; do
- out=$("$PB_DIR/ProxyBridge" --proxy a=socks5://127.0.0.1:1 --test-proxy "$tg" 2>&1)
- [[ "$out" == *"Target:"* ]] && ok "target accepted: $tg" || bad "target '$tg': ${out:0:200}"
-done
-for tg in ":80" "host:0" "host:70000" "host:x" "[::1" "" ; do
- out=$("$PB_DIR/ProxyBridge" --proxy a=socks5://127.0.0.1:1 --test-proxy "$tg" 2>&1); rc=$?
- [ $rc = 2 ] && ok "target refused: '$tg'" || bad "target '$tg' (exit $rc: ${out:0:160})"
-done
+t "--verbose not a number" 1 "Verbose level must be 0-3" -- --verbose x
+t "no profile" 1 "No profile specified" -- --verbose 1
+echo "== profile loading and validation"
+t "missing file" 1 "ERROR" -- --profile "$WORK/nope.pbprofile"
+t "unknown profile name" 1 "ERROR" -- --profile "No Such Profile"
+echo 'this is not json' > "$WORK/junk.pbprofile"
+t "not JSON" 1 "ERROR" -- --profile "$WORK/junk.pbprofile"
+echo '{ "ProxyRules": [ { "TargetHosts": "999.1.1.1", "Action": "DIRECT" } ] }' > "$WORK/badhost.pbprofile"
+t "invalid host in a rule" 1 "ERROR" -- --profile "$WORK/badhost.pbprofile"
+echo '{ "ProxyConfigs": [ { "Id": 1, "Type": "socks5", "Host": "127.0.0.1", "Port": "1" } ] }' > "$WORK/norules.pbprofile"
+t "profile with no rules" 1 "no enabled rules" -- --profile "$WORK/norules.pbprofile"
+echo '{ "ProxyConfigs": [ { "Id": 1, "Type": "socks5", "Host": "127.0.0.1", "Port": "1" } ], "ProxyRules": [ { "IsEnabled": false } ] }' > "$WORK/off.pbprofile"
+t "all rules disabled" 1 "no enabled rules" -- --profile "$WORK/off.pbprofile"
+echo '{ "ProxyRules": [ { "TargetHosts": "10.0.0.1" } ] }' > "$WORK/noproxy.pbprofile"
+t "PROXY rule but no proxy" 1 "no proxy server" -- --profile "$WORK/noproxy.pbprofile"
+mkdir -p "$WORK/cfg/profiles"
+echo '{ "ProxyRules": [ { "TargetHosts": "10.0.0.1", "Action": "DIRECT" } ] }' > "$WORK/cfg/profiles/Named.pbprofile"; secure "$WORK/cfg/profiles/Named.pbprofile"
if [ "$(id -u)" != 0 ]; then
- echo "== not root"
- t "the engine needs root" 1 "requires root privileges" -- --proxy socks5://127.0.0.1:1
- t "...even with rules" 1 "requires root privileges" -- --proxy socks5://127.0.0.1:1 --rule "curl:*:*:TCP:PROXY"
+ echo "== not root (a valid profile reaches the privilege check)"
+ t "by path" 1 "requires root privileges" -- --profile "$WORK/cfg/profiles/Named.pbprofile"
+ t "by GUI profile name" 1 "requires root privileges" -- --profile Named
+ t "with --verbose" 1 "requires root privileges" -- --verbose 3 --profile Named
+ echo '{ "ProxyConfigs": [ { "Id": 1, "Type": "socks5", "Host": "h", "Port": "1", "Username": "u", "Password": "secretpw" } ], "ProxyRules": [ { "Action": "PROXY", "ProxyConfigId": 1 } ] }' > "$WORK/open.pbprofile"; chmod 644 "$WORK/open.pbprofile"
+ t "readable credentials are warned about" 1 "WARNING" -- --profile "$WORK/open.pbprofile"
+ out=$("$PB_DIR/ProxyBridge" --profile "$WORK/open.pbprofile" 2>&1)
+ [[ "$out" != *secretpw* ]] && ok "the password never appears in the output" || bad "password printed"
fi
+echo "== --update (feed overridden through PROXYBRIDGE_UPDATE_FEED)"
+feed() { echo "$2" > "$WORK/$1.json"; }
+upd() { local name="$1" want="$2" needle="$3" file="$4"; local out rc; out=$(PROXYBRIDGE_UPDATE_FEED="$file" timeout 30 "$PB_DIR/ProxyBridge" --update 2>&1); rc=$?
+ [ "$rc" = "$want" ] && [[ "$out" == *"$needle"* ]] && ok "$name" || bad "$name (exit $rc: ${out:0:240})"; }
+feed new '{"linux":{"version":"99.0.0","download":"https://example.test/pb.tar.gz","release_notes":"https://example.test/n"}}'
+feed same "{\"linux\":{\"version\":\"$(sed -n 's/.*PROXYBRIDGE_VERSION "\(.*\)"/\1/p' "$ROOT/src/ProxyBridge.h")\",\"download\":\"https://example.test/a\"}}"
+feed old '{"linux":{"version":"0.0.1","download":"https://example.test/a"}}'
+feed junk 'not json'
+feed http '{"linux":{"version":"99.0.0","download":"http://example.test/a"}}'
+upd "a newer version is reported" 0 "99.0.0" "file://$WORK/new.json"
+upd "the download link is shown" 0 "https://example.test/pb.tar.gz" "file://$WORK/new.json"
+upd "an older feed means up to date" 0 "latest version" "file://$WORK/old.json"
+upd "the same version means up to date" 0 "latest version" "file://$WORK/same.json"
+upd "a broken feed is an error" 1 "ERROR" "file://$WORK/junk.json"
+upd "a missing feed is an error" 1 "ERROR" "file://$WORK/absent.json"
+out=$(PROXYBRIDGE_UPDATE_FEED="file://$WORK/http.json" "$PB_DIR/ProxyBridge" --update 2>&1)
+[[ "$out" != *"http://example.test"* ]] && ok "a non-https download link is never shown" || bad "http link shown"
+[ "$(id -u)" != 0 ] && { out=$(PROXYBRIDGE_UPDATE_FEED="file://$WORK/new.json" "$PB_DIR/ProxyBridge" --update 2>&1); [[ "$out" != *"root"* ]] && ok "--update needs no root" || bad "--update asked for root"; }
+
echo; echo "passed=$PASS failed=$FAIL"
[ "$FAIL" = 0 ]
diff --git a/Linux/tests/e2e_domains.sh b/Linux/tests/e2e_domains.sh
index 83e2b7e..ad64e0a 100755
--- a/Linux/tests/e2e_domains.sh
+++ b/Linux/tests/e2e_domains.sh
@@ -6,6 +6,7 @@ set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}" # directory holding the built ProxyBridge + libproxybridge.so (run ../build.sh first)
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first: (cd Linux && ./build.sh), or set PB_DIR to a directory containing ProxyBridge and libproxybridge.so"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
WORK="$(mktemp -d)"; PLOG="$WORK/proxy.log"; DLOG="$WORK/dns.log"; : > "$PLOG"; : > "$DLOG"
PASS=0; FAIL=0; DNSIP=10.77.0.2
ok() { echo " PASS $1"; PASS=$((PASS+1)); }
@@ -20,7 +21,7 @@ python3 "$HERE/fake_proxies.py" "$PLOG" > /dev/null 2>&1 & FAKE_PID=$!
python3 "$HERE/fake_dns.py" $DNSIP "$DLOG" > /dev/null 2>&1 & DNS_PID=$!
sleep 1
-stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 2 \
+stdbuf -oL "$PBL" --verbose 2 \
--proxy a=socks5://127.0.0.1:19080 --proxy b=socks5://bob:[email protected]:19081 --proxy h=socks5://localhost:19080 \
--rule "*:blocked.example.test:*:TCP:BLOCK" \
--rule "*:*.example.test:*:TCP:PROXY=a" \
diff --git a/Linux/tests/e2e_exempt.sh b/Linux/tests/e2e_exempt.sh
index 8c44b96..ec0a66f 100755
--- a/Linux/tests/e2e_exempt.sh
+++ b/Linux/tests/e2e_exempt.sh
@@ -6,6 +6,7 @@ set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}"
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
WORK="$(mktemp -d)"; PASS=0; FAIL=0; PB=""; FWD=""; WWW=""
ok() { echo " PASS $1"; PASS=$((PASS+1)); }
@@ -19,7 +20,7 @@ mkdir -p "$WORK/www"; echo "origin-ok" > "$WORK/www/index.html"
python3 -m http.server 18399 --bind "$MYIP" --directory "$WORK/www" > /dev/null 2>&1 & WWW=$!
sleep 1
start_pb() { # proxy spec
- stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 1 --proxy "fwd=$1" --rule "*:$MYIP:18399:TCP:PROXY=fwd" > "$WORK/pb.out" 2>&1 & PB=$!
+ stdbuf -oL "$PBL" --verbose 1 --proxy "fwd=$1" --rule "*:$MYIP:18399:TCP:PROXY=fwd" > "$WORK/pb.out" 2>&1 & PB=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && return 0; sleep 0.25; done; return 1
}
stop_pb() { kill -INT $PB 2>/dev/null; wait $PB 2>/dev/null; PB=""; }
diff --git a/Linux/tests/e2e_faults.sh b/Linux/tests/e2e_faults.sh
index cf77bbb..aba2912 100755
--- a/Linux/tests/e2e_faults.sh
+++ b/Linux/tests/e2e_faults.sh
@@ -6,6 +6,7 @@ set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}"
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
WORK="$(mktemp -d)"; FLOG="$WORK/fault.log"; : > "$FLOG"
PASS=0; FAIL=0; DST=203.0.113.10
@@ -20,7 +21,7 @@ python3 "$HERE/fake_proxies.py" "$WORK/proxy.log" > /dev/null 2>&1 & FAKE2=$!
sleep 1
start_pb() {
- stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 1 "$@" > "$WORK/pb.out" 2>&1 & PB_PID=$!
+ stdbuf -oL "$PBL" --verbose 1 "$@" > "$WORK/pb.out" 2>&1 & PB_PID=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && return 0; kill -0 "$PB_PID" 2>/dev/null || return 1; sleep 0.25; done; return 1
}
stop_pb() { kill -INT "$PB_PID" 2>/dev/null; wait "$PB_PID" 2>/dev/null; PB_PID=""; }
diff --git a/Linux/tests/e2e_lifecycle.sh b/Linux/tests/e2e_lifecycle.sh
index 3cb5050..dccefa6 100755
--- a/Linux/tests/e2e_lifecycle.sh
+++ b/Linux/tests/e2e_lifecycle.sh
@@ -6,6 +6,7 @@ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}"
BPFTOOL="${BPFTOOL:-bpftool}"
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
WORK="$(mktemp -d)"; PASS=0; FAIL=0; PB=""; PB2=""; HOLD_T=""; HOLD_U=""; FAKE=""
ok() { echo " PASS $1"; PASS=$((PASS+1)); }
@@ -19,7 +20,7 @@ progs() { "$BPFTOOL" prog show 2>/dev/null | grep -c "pb_connect4"; }
RULE="python3*:192.0.2.0/24:80:TCP:PROXY=a"
start() { # outfile args... ; sets PB
local out="$1"; shift
- stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 1 --proxy a=socks5://127.0.0.1:19080 --rule "$RULE" "$@" > "$out" 2>&1 & PB=$!
+ stdbuf -oL "$PBL" --verbose 1 --proxy a=socks5://127.0.0.1:19080 --rule "$RULE" "$@" > "$out" 2>&1 & PB=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" "$out" && return 0; kill -0 $PB 2>/dev/null || return 1; sleep 0.25; done; return 1
}
get() { python3 - "$1" <<'PY'
@@ -71,7 +72,7 @@ done
echo "== two instances at once"
start "$WORK/a.out" || bad "first instance"
PA=$PB
-stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 1 --proxy a=socks5://127.0.0.1:19080 --rule "python3*:192.0.2.0/24:81:TCP:PROXY=a" > "$WORK/b.out" 2>&1 & PB2=$!
+stdbuf -oL "$PBL" --verbose 1 --proxy a=socks5://127.0.0.1:19080 --rule "python3*:192.0.2.0/24:81:TCP:PROXY=a" > "$WORK/b.out" 2>&1 & PB2=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/b.out" && break; sleep 0.25; done
grep -q "ProxyBridge started" "$WORK/b.out" && ok "a second instance starts next to the first" || bad "second instance: $(tail -3 "$WORK/b.out")"
[ "$(get 192.0.2.7)" = DATA ] && ok "the first instance's rule still works" || bad "first instance broken by the second"
diff --git a/Linux/tests/e2e_logging.sh b/Linux/tests/e2e_logging.sh
index 2639a81..3d77947 100755
--- a/Linux/tests/e2e_logging.sh
+++ b/Linux/tests/e2e_logging.sh
@@ -6,6 +6,7 @@ set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}"
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
WORK="$(mktemp -d)"; PASS=0; FAIL=0; PB_PID=""
ok() { echo " PASS $1"; PASS=$((PASS+1)); }
@@ -17,7 +18,7 @@ python3 "$HERE/fake_proxies.py" "$WORK/proxy.log" > /dev/null 2>&1 & FAKE=$!
sleep 1
start_pb() {
- stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 2 --proxy a=socks5://127.0.0.1:19080 "$@" > "$WORK/pb.out" 2>&1 & PB_PID=$!
+ stdbuf -oL "$PBL" --verbose 2 --proxy a=socks5://127.0.0.1:19080 "$@" > "$WORK/pb.out" 2>&1 & PB_PID=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && return 0; sleep 0.25; done; return 1
}
stop_pb() { kill -INT "$PB_PID" 2>/dev/null; wait "$PB_PID" 2>/dev/null; PB_PID=""; }
@@ -84,13 +85,22 @@ connects 198.51.100.50 80 3; sleep 1
stop_pb
start_pb --log-every-connection false "${RULES[@]}" || bad "start"
stop_pb
-stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 2 --profile "$WORK/le.pbprofile" --log-every-connection false > "$WORK/pb.out" 2>&1 & PB_PID=$!
+stdbuf -oL "$PBL" --verbose 2 --profile "$WORK/le.pbprofile" --log-every-connection false > "$WORK/pb.out" 2>&1 & PB_PID=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && break; sleep 0.25; done
connects 198.51.100.50 80 3; sleep 1
[ "$(lines '198.51.100.50:80 via SOCKS5')" = 1 ] && ok "the command line overrides the profile" || bad "override: $(lines '198.51.100.50:80 via')"
stop_pb
-out=$("$PB_DIR/ProxyBridge" --log-every-connection maybe 2>&1); rc=$?
-[ $rc -ne 0 ] && [[ "$out" == *"Invalid value for --log-every-connection"* ]] && ok "bad value is refused" || bad "bad value (rc=$rc)"
+cat > "$WORK/le2.pbprofile" <<'JSON'
+{ "Version": "1.0", "LogEveryConnection": false,
+ "ProxyConfigs": [ { "Id": 1, "Name": "a", "Type": "socks5", "Host": "127.0.0.1", "Port": "19080" } ],
+ "ProxyRules": [ { "ProcessName": "python3*", "TargetHosts": "198.51.100.50", "TargetPorts": "80", "Protocol": "TCP", "Action": "PROXY", "ProxyConfigId": 1 } ] }
+JSON
+chmod 600 "$WORK/le2.pbprofile"
+stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 2 --profile "$WORK/le2.pbprofile" > "$WORK/pb.out" 2>&1 & PB_PID=$!
+for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && break; sleep 0.25; done
+connects 198.51.100.50 80 3; sleep 1
+[ "$(lines '198.51.100.50:80 via SOCKS5')" = 1 ] && ok "LogEveryConnection=false in the profile collapses repeats" || bad "profile false: $(lines '198.51.100.50:80 via')"
+stop_pb
echo; echo "passed=$PASS failed=$FAIL"
[ "$FAIL" = 0 ]
diff --git a/Linux/tests/e2e_nexus.sh b/Linux/tests/e2e_nexus.sh
index b404d5e..987ded0 100755
--- a/Linux/tests/e2e_nexus.sh
+++ b/Linux/tests/e2e_nexus.sh
@@ -12,6 +12,7 @@ set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}"
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first: (cd Linux && ./build.sh), or set PB_DIR"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
NODE="${NODE:-node}"; NEXUS_JS="${NEXUS_JS:-}"
command -v "$NODE" >/dev/null 2>&1 && [ -f "$NEXUS_JS" ] || { echo "SKIP: set NODE and NEXUS_JS (see header)"; exit 0; }
[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
@@ -61,7 +62,7 @@ print(h.hexdigest())
PY
sha_for() { python3 -c "$EXPECT_PY" "$1"; }
-stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 2 \
+stdbuf -oL "$PBL" --verbose 2 \
--proxy n1=socks5://127.0.0.1:1080 --proxy n2=socks5://nx:[email protected]:1081 \
--rule "curl:10.77.1.3:*:TCP:DIRECT" \
--rule "curl:10.77.1.4:*:TCP:BLOCK" \
diff --git a/Linux/tests/e2e_openssh.sh b/Linux/tests/e2e_openssh.sh
index d371da8..2d29a95 100755
--- a/Linux/tests/e2e_openssh.sh
+++ b/Linux/tests/e2e_openssh.sh
@@ -5,6 +5,7 @@ set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}" # directory holding the built ProxyBridge + libproxybridge.so (run ../build.sh first)
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first: (cd Linux && ./build.sh), or set PB_DIR to a directory containing ProxyBridge and libproxybridge.so"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
WORK="$(mktemp -d)"; PASS=0; FAIL=0; ORIGIN=10.77.0.5
ok() { echo " PASS $1"; PASS=$((PASS+1)); }
bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
@@ -43,7 +44,7 @@ python3 -m http.server 18500 --bind $ORIGIN --directory "$WORK" >/dev/null 2>&1
sleep 1
SUM=$(sha256sum "$WORK/big.bin" | cut -d' ' -f1)
-stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 1 --proxy ossh=socks5://127.0.0.1:19090 \
+stdbuf -oL "$PBL" --verbose 1 --proxy ossh=socks5://127.0.0.1:19090 \
--rule "curl:$ORIGIN:18500:TCP:PROXY=ossh" > "$WORK/pb.out" 2>&1 & PB=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && break; sleep 0.25; done
@@ -68,7 +69,7 @@ socketserver.ThreadingTCPServer(("10.77.0.5", 18501), H).serve_forever()
PY
UP=$!; sleep 1
kill -INT $PB; wait $PB 2>/dev/null
-stdbuf -oL "$PB_DIR/ProxyBridge" --proxy ossh=socks5://127.0.0.1:19090 --rule "curl:$ORIGIN:18500-18501:TCP:PROXY=ossh" > "$WORK/pb.out" 2>&1 & PB=$!
+stdbuf -oL "$PBL" --proxy ossh=socks5://127.0.0.1:19090 --rule "curl:$ORIGIN:18500-18501:TCP:PROXY=ossh" > "$WORK/pb.out" 2>&1 & PB=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && break; sleep 0.25; done
GOT=$(curl -s -m 60 --data-binary @"$WORK/big.bin" http://$ORIGIN:18501/ )
[ "$GOT" = "$SUM" ] && ok "40 MB upload through OpenSSH SOCKS5: origin received identical bytes" || bad "upload checksum mismatch (got ${GOT:0:20})"
diff --git a/Linux/tests/e2e_parity.sh b/Linux/tests/e2e_parity.sh
index 95dcb92..22064d4 100755
--- a/Linux/tests/e2e_parity.sh
+++ b/Linux/tests/e2e_parity.sh
@@ -6,6 +6,7 @@ set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}"
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
WORK="$(mktemp -d)"; PLOG="$WORK/proxy.log"; DLOG="$WORK/dns.log"; : > "$PLOG"; : > "$DLOG"
PASS=0; FAIL=0; DNSIP=10.77.0.6; LODNS=127.0.0.9
@@ -33,7 +34,7 @@ sleep 1
for n in curl2 curl3 curl4 curl5; do cp "$(command -v curl)" "$WORK/$n"; done
start_pb() { # args...
- stdbuf -oL "$PB_DIR/ProxyBridge" "$@" > "$WORK/pb.out" 2>&1 & PB_PID=$!
+ stdbuf -oL "$PBL" "$@" > "$WORK/pb.out" 2>&1 & PB_PID=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && return 0; kill -0 "$PB_PID" 2>/dev/null || return 1; sleep 0.25; done; return 1
}
stop_pb() { kill -INT "$PB_PID" 2>/dev/null; wait "$PB_PID" 2>/dev/null; PB_PID=""; }
diff --git a/Linux/tests/e2e_profile.sh b/Linux/tests/e2e_profile.sh
index dd09968..9a3c254 100755
--- a/Linux/tests/e2e_profile.sh
+++ b/Linux/tests/e2e_profile.sh
@@ -6,6 +6,7 @@ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}"
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
WORK="$(mktemp -d)"
LOG="$WORK/proxy.log"; : > "$LOG"
@@ -23,8 +24,10 @@ mkdir -p "$WORK/cfg/profiles"
python3 "$HERE/fake_proxies.py" "$LOG" > "$WORK/fake.out" 2>&1 & FAKE_PID=$!
sleep 1
-start_pb() { # args...; leaves PB_PID set and waits for start-up
- stdbuf -oL "$PB_DIR/ProxyBridge" "$@" > "$WORK/pb.out" 2>&1 & PB_PID=$!
+start_pb() { # args...; leaves PB_PID set and waits for start-up. Plain --profile/--verbose runs the real program; extras go through pbl
+ local prog="$PB_DIR/ProxyBridge" a
+ for a in "$@"; do case "$a" in --proxy|--rule|--dns-via-proxy|--log-every-connection) prog="$PBL";; esac; done
+ stdbuf -oL "$prog" "$@" > "$WORK/pb.out" 2>&1 & PB_PID=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && return 0; kill -0 "$PB_PID" 2>/dev/null || return 1; sleep 0.25; done
return 1
}
@@ -67,8 +70,6 @@ stop_pb
echo "== a profile saved by the GUI, by name (also with spaces)"
cp "$WORK/win.pbprofile" "$WORK/cfg/profiles/Work Profile.pbprofile"
-out=$("$PB_DIR/ProxyBridge" --list-profiles 2>&1)
-has "--list-profiles shows the name" "$out" "Work Profile"
if start_pb --profile "Work Profile"; then ok "starts by profile name"; else bad "start by name"; cat "$WORK/pb.out"; fi
out=$(curl -s -m 5 http://192.0.2.9/); has "rules from the named profile apply" "$out" "hello-from-A dst=192.0.2.9:80"
stop_pb
@@ -123,15 +124,22 @@ expect_fail() { # name expected-text args...
out=$("$PB_DIR/ProxyBridge" "$@" 2>&1); rc=$?
if [ $rc -ne 0 ] && [[ "$out" == *"$want"* ]]; then ok "$name"; else bad "$name (rc=$rc: ${out:0:300})"; fi
}
-expect_fail "missing file" "cannot open" --profile "$WORK/nope.pbprofile"
-expect_fail "unknown profile name" "cannot open" --profile "no such profile"
+expect_fail "missing file" "ERROR" --profile "$WORK/nope.pbprofile"
+expect_fail "unknown profile name" "ERROR" --profile "no such profile"
echo '{ "ProxyRules": [ { "ProxyConfigId": 9 } ] }' > "$WORK/badref.pbprofile"
expect_fail "rule referring to a missing proxy" "does not match any proxy" --profile "$WORK/badref.pbprofile"
echo 'not json' > "$WORK/junk.pbprofile"
expect_fail "malformed JSON" "not a valid profile" --profile "$WORK/junk.pbprofile"
-echo '{ "ProxyRules": [ { "TargetHosts": "999.1.1.1" } ] }' > "$WORK/badhost.pbprofile"
+echo '{ "ProxyRules": [ { "TargetHosts": "999.1.1.1", "Action": "DIRECT" } ] }' > "$WORK/badhost.pbprofile"
expect_fail "rule the engine rejects" "ERROR" --profile "$WORK/badhost.pbprofile"
expect_fail "--profile without a value" "Unknown option" --profile
+echo '{ "ProxyConfigs": [ { "Id": 1, "Type": "socks5", "Host": "127.0.0.1", "Port": "19080" } ] }' > "$WORK/norules.pbprofile"
+expect_fail "a profile without rules" "no enabled rules" --profile "$WORK/norules.pbprofile"
+echo '{ "ProxyRules": [ { "TargetHosts": "10.0.0.1" } ] }' > "$WORK/noproxy.pbprofile"
+expect_fail "a PROXY rule without any proxy" "no proxy server" --profile "$WORK/noproxy.pbprofile"
+echo '{ "ProxyConfigs": [ { "Id": 1, "Type": "socks5", "Host": "127.0.0.1", "Port": "19080" } ], "ProxyRules": [ { "IsEnabled": false } ] }' > "$WORK/off.pbprofile"
+expect_fail "a profile whose rules are all disabled" "no enabled rules" --profile "$WORK/off.pbprofile"
+expect_fail "no profile at all" "No profile specified"
echo "== credentials in a world-readable profile trigger a warning"
cp "$WORK/win.pbprofile" "$WORK/open.pbprofile"; chmod 644 "$WORK/open.pbprofile"
diff --git a/Linux/tests/e2e_rules.sh b/Linux/tests/e2e_rules.sh
index c13dcb4..62fc3ec 100755
--- a/Linux/tests/e2e_rules.sh
+++ b/Linux/tests/e2e_rules.sh
@@ -5,6 +5,7 @@ set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}" # directory holding the built ProxyBridge + libproxybridge.so (run ../build.sh first)
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first: (cd Linux && ./build.sh), or set PB_DIR to a directory containing ProxyBridge and libproxybridge.so"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
WORK="$(mktemp -d)"; PLOG="$WORK/proxy.log"; : > "$PLOG"
PASS=0; FAIL=0
ok() { echo " PASS $1"; PASS=$((PASS+1)); }
@@ -28,7 +29,7 @@ cp "$CURL" "$WORK/bin/wget"; cp "$CURL" "$WORK/bin/newtool"; cp "$CURL" "$WORK/b
sleep 1
start_pb() { # extra CLI args...
- stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 1 \
+ stdbuf -oL "$PBL" --verbose 1 \
--proxy a=socks5://127.0.0.1:19080 --proxy b=socks5://bob:[email protected]:19081 --proxy c=http://127.0.0.1:19082 \
--proxy d=http://bob:[email protected]:19083 --proxy e=http://bob:[email protected]:19083 "$@" > "$WORK/pb.out" 2>&1 & PB_PID=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && return 0; sleep 0.25; done
diff --git a/Linux/tests/e2e_security.sh b/Linux/tests/e2e_security.sh
index f550a42..e4038cf 100755
--- a/Linux/tests/e2e_security.sh
+++ b/Linux/tests/e2e_security.sh
@@ -4,6 +4,7 @@ set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}"
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first: (cd Linux && ./build.sh), or set PB_DIR"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
BPFTOOL="${BPFTOOL:-bpftool}"; command -v "$BPFTOOL" >/dev/null || { echo "bpftool not found (set BPFTOOL)"; exit 1; }
[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
export LD_LIBRARY_PATH="$PB_DIR"
@@ -15,7 +16,7 @@ trap cleanup EXIT
python3 "$HERE/fake_proxies.py" "$PLOG" >/dev/null 2>&1 & FAKE=$!
sleep 1
-stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 1 --proxy a=socks5://127.0.0.1:19080 --rule "curl:192.0.2.1:*:TCP:PROXY=a" > "$WORK/pb.out" 2>&1 & PB=$!
+stdbuf -oL "$PBL" --verbose 1 --proxy a=socks5://127.0.0.1:19080 --rule "curl:192.0.2.1:*:TCP:PROXY=a" > "$WORK/pb.out" 2>&1 & PB=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && break; sleep 0.25; done
RELAY=$(sed -n 's/.*relay tcp:\([0-9]*\) udp.*/\1/p' "$WORK/pb.out" | head -1)
[ -n "$RELAY" ] || { echo "ProxyBridge did not start"; cat "$WORK/pb.out"; exit 1; }
diff --git a/Linux/tests/e2e_udp.sh b/Linux/tests/e2e_udp.sh
index e0168ba..2815019 100755
--- a/Linux/tests/e2e_udp.sh
+++ b/Linux/tests/e2e_udp.sh
@@ -5,6 +5,7 @@ set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}"
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
WORK="$(mktemp -d)"; : > "$WORK/fault.log"; : > "$WORK/proxy.log"
PASS=0; FAIL=0
@@ -31,7 +32,7 @@ want() { # name, output, expected substring
nowant() { if [[ "$2" != *"$3"* ]]; then ok "$1"; else bad "$1 (got: ${2:0:300})"; fi; }
logged() { grep -q "$2" "$WORK/pb.out" && ok "$1" || bad "$1 (log lacks '$2')"; }
-stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 1 \
+stdbuf -oL "$PBL" --verbose 1 \
--proxy a=socks5://127.0.0.1:19080 --proxy c=http://127.0.0.1:19082 \
--proxy u0=socks5://127.0.0.1:19120 --proxy u1=socks5://127.0.0.1:19121 --proxy u2=socks5://127.0.0.1:19122 --proxy u3=socks5://127.0.0.1:19123 \
--proxy u4=socks5://127.0.0.1:19124 --proxy u5=socks5://127.0.0.1:19125 --proxy u6=socks5://127.0.0.1:19126 --proxy u7=socks5://127.0.0.1:19127 \
diff --git a/Linux/tests/gui_headless.sh b/Linux/tests/gui_headless.sh
index 1d4cb84..dd91f3d 100755
--- a/Linux/tests/gui_headless.sh
+++ b/Linux/tests/gui_headless.sh
@@ -109,8 +109,8 @@ out=$(curl -s -m 5 http://127.0.0.1:18401/); has "per-rule LocalhostViaProxy fr
stop_gui
grep -q '"Name": "Burp intercept"' "$P/From Windows.pbprofile" && grep -q '"LocalhostViaProxy": true' "$P/From Windows.pbprofile" && grep -q '"SendDomainToProxy": true' "$P/From Windows.pbprofile" \
&& ok "rule name, localhost flag and DNS-via-proxy survive the GUI saving the profile" || bad "fields lost: $(cat "$P/From Windows.pbprofile")"
-out=$(PROXYBRIDGE_CONFIG_DIR="$WORK/cfg" LD_LIBRARY_PATH="$LIBDIR" "$LIBDIR/ProxyBridge" --list-profiles 2>&1)
-has "the CLI lists the GUI's profiles" "$out" "From Windows"
+out=$(ls "$P")
+has "the GUI saved its profiles as files the CLI can load" "$out" "From Windows.pbprofile"
[ "$(stat -c %a "$P/From Windows.pbprofile")" = 600 ] && ok "the dropped-in file was tightened to 0600" || bad "dropped-in file mode"
echo; echo "passed=$PASS failed=$FAIL"
diff --git a/Linux/tests/hookbench.sh b/Linux/tests/hookbench.sh
index 767a8d7..059fd87 100755
--- a/Linux/tests/hookbench.sh
+++ b/Linux/tests/hookbench.sh
@@ -3,13 +3,14 @@
HB=${1:?path to hookbench}; ROOT="$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)")"
PB_DIR="${PB_DIR:-$ROOT/output}" # directory holding the built ProxyBridge + libproxybridge.so (run ../build.sh first)
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first: (cd Linux && ./build.sh), or set PB_DIR to a directory containing ProxyBridge and libproxybridge.so"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
export LD_LIBRARY_PATH="$PB_DIR"
IP=10.77.0.1 # alias on lo: local like loopback, but not caught by the implicit-loopback bypass
ip addr add $IP/32 dev lo 2>/dev/null
trap 'ip addr del $IP/32 dev lo 2>/dev/null' EXIT
run() { for i in 1 2 3; do $HB udp $IP 19556 1000000; done; }
echo "### A: ProxyBridge not running"; run
-start() { stdbuf -oL "$PB_DIR/ProxyBridge" "$@" > /tmp/pbbench.out 2>&1 & PB=$!; for _ in $(seq 40); do grep -q "ProxyBridge started" /tmp/pbbench.out && break; sleep 0.25; done; }
+start() { stdbuf -oL "$PBL" "$@" > /tmp/pbbench.out 2>&1 & PB=$!; for _ in $(seq 40); do grep -q "ProxyBridge started" /tmp/pbbench.out && break; sleep 0.25; done; }
echo "### B: running, 20 rules for other programs (this binary: empty class -> immediate direct)"
start $(for i in $(seq 20); do echo --rule "someapp$i:*:*:BOTH:PROXY"; done); run; kill -INT $PB; wait $PB 2>/dev/null
echo "### C: running, rules that match this binary but not this destination (full rule evaluation, then direct)"
diff --git a/Linux/tests/pbl b/Linux/tests/pbl
new file mode 100755
index 0000000..b31e0e5
--- /dev/null
+++ b/Linux/tests/pbl
@@ -0,0 +1,3 @@
+#!/bin/sh
+# see pbl.py: the suites start the real program through this, with compact --proxy / --rule arguments
+exec python3 "$(dirname "$0")/pbl.py" "$@"
diff --git a/Linux/tests/pbl.py b/Linux/tests/pbl.py
new file mode 100755
index 0000000..1cf6a33
--- /dev/null
+++ b/Linux/tests/pbl.py
@@ -0,0 +1,138 @@
+#!/usr/bin/env python3
+"""Test helper: runs the real command line program from "--proxy / --rule" style arguments.
+
+The program itself takes only --profile, --verbose, --version, --update and --help, like the Windows one. The test suites describe their
+set-ups with compact arguments; this script turns them into a .pbprofile (held in an unlinked file) and then execs
+`ProxyBridge --profile <that file>`, so the process that runs is the real program and the pid stays the same.
+
+ --proxy [name=]type://[user:pass@]host:port[?dns=local|proxy] (also type://host:port:user:pass, [ipv6] hosts)
+ --rule process:hosts:ports:protocol:action[=proxy][+localhost] (proxy = name or 1-based index)
+ --dns-via-proxy true|false --log-every-connection true|false --verbose N
+ --profile FILE-OR-NAME a profile to start from; the other arguments are added to it
+PB_DIR selects the build (default: Linux/output).
+"""
+import json, os, re, sys, tempfile
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+PB_DIR = os.environ.get("PB_DIR", os.path.join(os.path.dirname(HERE), "output"))
+
+
+def die(msg):
+ print("ERROR: " + msg, file=sys.stderr)
+ sys.exit(1)
+
+
+def parse_proxy(spec):
+ m = re.match(r"^(?:([^=:/]*)=)?([A-Za-z0-9]+)://(.*)$", spec)
+ if not m:
+ die("bad proxy " + spec)
+ name, scheme, rest = m.groups()
+ scheme = scheme.lower()
+ if scheme not in ("socks5", "http"):
+ die("bad proxy type " + scheme)
+ dns = True
+ if "?" in rest.rsplit("@", 1)[-1]:
+ head, _, query = rest.rpartition("?")
+ rest = head
+ dns = query.lower() != "dns=local"
+ user = pw = ""
+ if "@" in rest:
+ cred, _, rest = rest.rpartition("@")
+ user, _, pw = cred.partition(":")
+ if rest.startswith("["):
+ host, _, tail = rest[1:].partition("]")
+ port = tail.lstrip(":").split(":")[0]
+ else:
+ parts = rest.split(":")
+ host, port = parts[0], parts[1] if len(parts) > 1 else ""
+ if len(parts) >= 4 and not user: # legacy host:port:user:pass
+ user, pw = parts[2], ":".join(parts[3:])
+ return {"Name": name or host, "Type": scheme.upper() if scheme == "socks5" else "HTTP", "Host": host, "Port": port,
+ "Username": user, "Password": pw, "SendDomainToProxy": dns}
+
+
+def parse_rule(spec):
+ first = spec.index(":")
+ proc, rest = spec[:first], spec[first + 1:]
+ head, proto, action = rest.rsplit(":", 2)
+ hosts, ports = head.rsplit(":", 1) if head.count(":") else (head, "*")
+ localhost = False
+ if action.lower().endswith("+localhost"):
+ action, localhost = action[:-len("+localhost")], True
+ proxy = ""
+ if "=" in action:
+ action, proxy = action.split("=", 1)
+ return {"ProcessName": proc or "*", "TargetHosts": hosts or "*", "TargetPorts": ports or "*", "Protocol": proto.upper(),
+ "Action": action.upper(), "IsEnabled": True, "LocalhostViaProxy": localhost, "_proxy": proxy}
+
+
+def boolean(v):
+ return v.lower() in ("1", "true")
+
+
+def main():
+ args = sys.argv[1:]
+ prof = {"Version": "1.0", "ProxyConfigs": [], "ProxyRules": []}
+ verbose = None
+ base = None
+ proxies, rules = [], []
+ i = 0
+ while i < len(args):
+ a = args[i]
+ if a in ("--proxy", "--rule", "--profile", "--verbose", "--dns-via-proxy", "--log-every-connection") and i + 1 < len(args):
+ v = args[i + 1]
+ i += 2
+ if a == "--proxy": proxies.append(parse_proxy(v))
+ elif a == "--rule": rules.append(parse_rule(v))
+ elif a == "--profile": base = v
+ elif a == "--verbose": verbose = v
+ elif a == "--dns-via-proxy": prof["DnsViaProxy"] = boolean(v)
+ else: prof["LogEveryConnection"] = boolean(v)
+ else:
+ die("unsupported by the test helper: " + a)
+
+ if base:
+ sys.path.insert(0, HERE)
+ path = base
+ if "/" not in base and not os.path.exists(base):
+ cfg = os.environ.get("PROXYBRIDGE_CONFIG_DIR", "/etc/proxybridge")
+ from urllib.parse import quote
+ path = os.path.join(cfg, "profiles", quote(base, safe=" ") + ".pbprofile")
+ with open(path) as f:
+ loaded = json.load(f)
+ loaded.update({k: v for k, v in prof.items() if k not in ("ProxyConfigs", "ProxyRules")})
+ prof = loaded
+ prof.setdefault("ProxyConfigs", []); prof.setdefault("ProxyRules", [])
+
+ next_id = max([c.get("Id", 0) for c in prof["ProxyConfigs"]] + [0]) + 1
+ names = []
+ for p in proxies:
+ p["Id"] = next_id; next_id += 1
+ prof["ProxyConfigs"].append(p)
+ for c in prof["ProxyConfigs"]:
+ names.append((c.get("Name"), c["Id"]))
+ for r in rules:
+ ref = r.pop("_proxy")
+ if ref:
+ if ref.isdigit() and 1 <= int(ref) <= len(prof["ProxyConfigs"]):
+ r["ProxyConfigId"] = prof["ProxyConfigs"][int(ref) - 1]["Id"]
+ else:
+ hit = [i for n, i in names if n == ref]
+ if not hit:
+ die("rule refers to unknown proxy '%s'" % ref)
+ r["ProxyConfigId"] = hit[0]
+ prof["ProxyRules"].append(r)
+
+ fd, tmp = tempfile.mkstemp(prefix="pbl-", suffix=".pbprofile")
+ os.write(fd, json.dumps(prof).encode())
+ os.unlink(tmp) # the exec'd program reads it through /proc/self/fd/<fd>
+ os.set_inheritable(fd, True)
+ cmd = [os.path.join(PB_DIR, "ProxyBridge"), "--profile", "/proc/self/fd/%d" % fd]
+ if verbose is not None:
+ cmd += ["--verbose", verbose]
+ env = dict(os.environ)
+ env["LD_LIBRARY_PATH"] = PB_DIR + (":" + env["LD_LIBRARY_PATH"] if env.get("LD_LIBRARY_PATH") else "")
+ os.execve(cmd[0], cmd, env)
+
+
+main()
diff --git a/Linux/tests/rules_diff.py b/Linux/tests/rules_diff.py
index 5c9d43c..bd88268 100755
--- a/Linux/tests/rules_diff.py
+++ b/Linux/tests/rules_diff.py
@@ -131,8 +131,8 @@ def connect(proto, ip, port):
def run_seed(seed):
rng = random.Random(seed)
rules = [Rule(rng) for _ in range(rng.choice([8, 12, 16, 24]))]
- env = dict(os.environ, LD_LIBRARY_PATH=PB_DIR)
- args = ["stdbuf", "-oL", os.path.join(PB_DIR, "ProxyBridge"), "--verbose", "2", "--proxy", PROXY]
+ env = dict(os.environ, LD_LIBRARY_PATH=PB_DIR, PB_DIR=PB_DIR)
+ args = ["stdbuf", "-oL", os.path.join(os.path.dirname(os.path.abspath(__file__)), "pbl"), "--verbose", "2", "--proxy", PROXY]
for r in rules:
args += ["--rule", r.cli()]
out = open("/tmp/rules_diff.%d.out" % os.getpid(), "w+")
diff --git a/Linux/tests/scale.sh b/Linux/tests/scale.sh
index 7ff3dca..8220fe8 100755
--- a/Linux/tests/scale.sh
+++ b/Linux/tests/scale.sh
@@ -6,12 +6,13 @@ N=${1:-10000}
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
PB_DIR="${PB_DIR:-$ROOT/output}" # directory holding the built ProxyBridge + libproxybridge.so (run ../build.sh first)
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first: (cd Linux && ./build.sh), or set PB_DIR to a directory containing ProxyBridge and libproxybridge.so"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
export LD_LIBRARY_PATH="$PB_DIR"
ulimit -n 200000
WORK=$(mktemp -d); trap 'kill $FAKE $PB 2>/dev/null; wait 2>/dev/null; rm -rf $WORK' EXIT
python3 "$HERE/fake_proxies.py" $WORK/log >/dev/null 2>&1 & FAKE=$!
sleep 1
-stdbuf -oL "$PB_DIR/ProxyBridge" --proxy a=socks5://127.0.0.1:19080 --rule "python3*:192.0.2.0/24:*:TCP:PROXY=a" > $WORK/pb.out 2>&1 & PB=$!
+stdbuf -oL "$PBL" --proxy a=socks5://127.0.0.1:19080 --rule "python3*:192.0.2.0/24:*:TCP:PROXY=a" > $WORK/pb.out 2>&1 & PB=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" $WORK/pb.out && break; sleep 0.25; done
rss() { awk '/VmRSS/{print $2}' /proc/$PB/status; }
maps_kb() { "${BPFTOOL:-bpftool}" map show 2>/dev/null | grep -oE 'memlock [0-9]+' | awk '{s+=$2} END{printf "%d", s/1024}'; }
diff --git a/Linux/tests/thrbench.sh b/Linux/tests/thrbench.sh
index 37fd38d..f298700 100755
--- a/Linux/tests/thrbench.sh
+++ b/Linux/tests/thrbench.sh
@@ -4,6 +4,7 @@
TB=${1:?path to thrbench binary named "thrbench"}; ROOT="$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)")"
PB_DIR="${PB_DIR:-$ROOT/output}" # directory holding the built ProxyBridge + libproxybridge.so (run ../build.sh first)
[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first: (cd Linux && ./build.sh), or set PB_DIR to a directory containing ProxyBridge and libproxybridge.so"; exit 1; }
+HERE="${HERE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"; PBL="$HERE/pbl"; export PB_DIR # starts the real program from compact --proxy/--rule arguments (see pbl.py)
export LD_LIBRARY_PATH="$PB_DIR"
MB=${MB:-2048}
$TB sink 19990 & SINK=$!; $TB proxy 19991 19990 & PROXY=$!
@@ -13,7 +14,7 @@ echo "== baselines (ProxyBridge not running)"
for i in 1 2 3; do $TB direct 127.0.0.1 19990 $MB 1; done
for i in 1 2 3; do $TB socks 19991 192.0.2.7 9999 $MB 1; done
for i in 1 2; do $TB socks 19991 192.0.2.7 9999 $((MB/8)) 8; done
-stdbuf -oL "$PB_DIR/ProxyBridge" --proxy a=socks5://127.0.0.1:19991 --rule "thrbench:192.0.2.0/24:*:TCP:PROXY=a" > /tmp/thr_pb.out 2>&1 & PB=$!
+stdbuf -oL "$PBL" --proxy a=socks5://127.0.0.1:19991 --rule "thrbench:192.0.2.0/24:*:TCP:PROXY=a" > /tmp/thr_pb.out 2>&1 & PB=$!
for _ in $(seq 40); do grep -q "ProxyBridge started" /tmp/thr_pb.out && break; sleep 0.25; done
echo "== through ProxyBridge (app connects to 192.0.2.7:9999, transparently redirected)"
for i in 1 2 3; do $TB direct 192.0.2.7 9999 $MB 1; done