Skip to content

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

feat(linux): per-proxy DNS via proxy and per-rule localhost, as in the Windows and macOS apps

anof-cyber4ede65f1f5a0
diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml
index 896205a..01c11ce 100644
--- a/.github/workflows/build-linux.yml
+++ b/.github/workflows/build-linux.yml
@@ -186,7 +186,7 @@ jobs:
uname -r
ls /sys/kernel/btf/vmlinux && mount | grep -q "type cgroup2" || { echo "kernel lacks BTF or cgroup2: skipping"; exit 0; }
fail=0
- for t in e2e e2e_rules e2e_domains e2e_security e2e_profile api_live; do
+ for t in e2e e2e_rules e2e_domains e2e_security e2e_profile e2e_parity api_live; do
echo "::group::$t"
sudo env PB_DIR="$PWD/Linux/output" BPFTOOL="$BPFTOOL" bash "Linux/tests/$t.sh" || fail=1
echo "::endgroup::"
diff --git a/Linux/README.md b/Linux/README.md
index 0ca3fda..b785863 100644
--- a/Linux/README.md
+++ b/Linux/README.md
@@ -179,6 +179,8 @@ OPTIONS:
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)
@@ -188,7 +190,8 @@ OPTIONS:
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
+ 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
@@ -253,6 +256,9 @@ Rules are evaluated **in order and the first match wins** (put specific rules be
# Domain names (exact and wildcard), each rule with its own proxy
--rule "firefox:*.github.com;github.com:443:TCP:PROXY=work"
+
+# 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"
# IP range / CIDR / IPv6
@@ -290,19 +296,19 @@ sudo ProxyBridge --profile work --rule "curl:*:*:TCP:DIRECT" # profile first,
"DnsViaProxy": true,
"DefaultProxyId": 1,
"ProxyConfigs": [
- { "Id": 1, "Name": "corp", "Type": "SOCKS5", "Host": "proxy.corp", "Port": "1080", "Username": "", "Password": "", "SendDomainToProxy": false },
+ { "Id": 1, "Name": "corp", "Type": "SOCKS5", "Host": "proxy.corp", "Port": "1080", "Username": "", "Password": "", "SendDomainToProxy": true },
{ "Id": 2, "Name": "web", "Type": "HTTP", "Host": "10.0.0.2", "Port": "8080", "Username": "bob", "Password": "secret" }
],
"ProxyRules": [
- { "ProcessName": "firefox;chrome", "TargetHosts": "*", "TargetPorts": "80;443", "TargetDomains": "*.github.com",
- "Protocol": "TCP", "Action": "PROXY", "IsEnabled": true, "ProxyConfigId": 2 }
+ { "Name": "Browsers", "ProcessName": "firefox;chrome", "TargetHosts": "*", "TargetPorts": "80;443", "TargetDomains": "*.github.com",
+ "Protocol": "TCP", "Action": "PROXY", "IsEnabled": true, "ProxyConfigId": 2, "LocalhostViaProxy": false }
]
}
```
- 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 (`LocalhostViaProxy`, `LogFilters`, `SendDomainToProxy`, ...) are ignored on import. `DnsViaProxy` and `DefaultProxyId` are Linux additions that other apps ignore. 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. `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.
- 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.
@@ -324,6 +330,12 @@ Cost: DNS from covered processes takes one extra loopback hop (about +90 µs per
- IPv6 destinations (`AAAA` records are not mapped yet)
- Shared hosting: if two names share one IP, whichever name was resolved last matches; a rule for the other name matches too
+## Options shared with the Windows and macOS apps
+
+- **Names.** Every proxy and every rule can carry a name (the GUI shows it, profiles store it).
+- **DNS via proxy, per proxy** (*SendDomainToProxy*, on by default, like Windows and macOS). When a connection goes to an address whose name the application resolved, the proxy is asked for the *name* (SOCKS5 domain address, or `CONNECT host:port`), so the proxy does the resolving. Off sends the IP address (`?dns=local` on the command line). The name comes from the application's own unencrypted DNS answers (the DNS tap that already powers domain rules; DoH/DoT bypass it), the most recent lookup for that address wins, and without a known name the IP is sent. UDP datagrams always carry the IP. Names are checked before they reach a proxy, so a hostile DNS answer cannot inject anything into a request. This is separate from the menu switch **DNS via Proxy**, which decides whether DNS queries themselves are routed through the rules.
+- **Also proxy localhost traffic, per rule** (*LocalhostViaProxy*, off by default, PROXY rules only). Without it a PROXY rule leaves connections to this computer (`127.0.0.0/8`, `::1`) direct, as on Windows, which is usually what you want. With it, matching loopback TCP and UDP connections go to the proxy, for example to inspect a local application in an intercepting proxy. First match still wins: a PROXY rule without the option stops the walk and the connection stays local. Differences from Windows: BLOCK and DIRECT rules never touch loopback, and DNS to a local resolver (port 53, e.g. `127.0.0.53`) is never proxied, so a broad rule cannot break name resolution.
+
## 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.
@@ -571,6 +583,7 @@ cd ../../tests && sudo ./e2e.sh # end-to-end with real kernel
sudo ./e2e_domains.sh # domain rules with a real resolver client (root, needs dig)
sudo ./e2e_rules.sh # every rule form + every proxy type, incl. HTTP auth and UDP rules (root)
sudo ./e2e_profile.sh # `ProxyBridge --profile`: Windows-format profiles on the live datapath (root)
+sudo ./e2e_parity.sh # per-proxy host-name sending and per-rule localhost, incl. a hostile DNS name (root, needs dig)
sudo ./api_live.sh # library API: edit/move/disable/delete rules and proxies on the live datapath (root)
sudo BPFTOOL=$(command -v bpftool) ./e2e_security.sh # relay hand-off cannot be hijacked from another loopback address (root)
sudo ./churn.sh 3000 # rule/proxy churn with live traffic: memory, fds and threads must stay flat (root)
diff --git a/Linux/cli/main.c b/Linux/cli/main.c
index 81cd9d6..0acf85b 100644
--- a/Linux/cli/main.c
+++ b/Linux/cli/main.c
@@ -5,6 +5,7 @@
#include <signal.h>
#include <stdbool.h>
#include <ctype.h>
+#include <strings.h>
#include <dirent.h>
#include <sys/stat.h>
#include "../src/ProxyBridge.h"
@@ -22,6 +23,7 @@ typedef struct {
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 {
@@ -32,6 +34,7 @@ typedef struct {
char username[256];
char password[256];
uint32_t id;
+ bool send_domain; /* the proxy resolves host names (default); false sends the IP address */
} ProxyEntry;
static volatile bool keep_running = false;
@@ -90,6 +93,8 @@ static void show_help(const char* prog)
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");
@@ -101,13 +106,15 @@ static void show_help(const char* prog)
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(" 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\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");
@@ -153,12 +160,19 @@ static RuleProtocol parse_protocol(const char* str)
exit(1);
}
-/* action[=proxy] */
-static RuleAction parse_action(const char* str, char* proxy_ref, size_t ref_size)
+/* action[=proxy][+localhost] */
+static RuleAction parse_action(const char* str, char* proxy_ref, size_t ref_size, bool* localhost)
{
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)
{
@@ -168,7 +182,7 @@ static RuleAction parse_action(const char* str, char* proxy_ref, size_t ref_size
char upper[16];
upper_copy(upper, buf, sizeof(upper));
if (strcmp(upper, "PROXY") == 0) return RULE_ACTION_PROXY;
- if (eq && proxy_ref[0]) { fprintf(stderr, "ERROR: '=proxy' is only valid with PROXY\n"); exit(1); }
+ 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);
@@ -227,7 +241,7 @@ static bool parse_rule(const char* rule_str, ProxyRule* rule)
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->action = parse_action(action, rule->proxy_ref, sizeof(rule->proxy_ref), &rule->localhost);
return true;
}
@@ -237,6 +251,7 @@ 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)
@@ -275,6 +290,18 @@ static bool parse_proxy_spec(const char* spec, ProxyEntry* p)
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);
+ return false;
+ }
+ }
+
char* port_str = NULL;
char* legacy = NULL;
if (rest[0] == '[')
@@ -373,6 +400,7 @@ static bool load_profile(const char* arg, ProxyEntry* proxies, int* num_proxies,
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++)
{
@@ -392,6 +420,7 @@ static bool load_profile(const char* arg, ProxyEntry* proxies, int* num_proxies,
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);
@@ -577,8 +606,11 @@ int main(int argc, char *argv[])
fprintf(stderr, "ERROR: Proxy %d (%s:%u): %s\n", i + 1, p->host, p->port, err);
return 1;
}
- printf(" [%d]%s%s%s %s://%s:%u%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)" : "");
+ 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)
{
@@ -616,9 +648,11 @@ int main(int argc, char *argv[])
rules[i].target_hosts, rules[i].target_ports, err);
return 1;
}
- printf(" [%u] %s:%s:%s:%s -> %s%s%s\n", rule_id, rules[i].process_name, rules[i].target_hosts,
+ 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].proxy_ref[0] ? " via " : "", rules[i].proxy_ref, rules[i].localhost ? " (+localhost)" : "");
}
}
else
diff --git a/Linux/profile/pb_profile.c b/Linux/profile/pb_profile.c
index d00b267..f6871e9 100644
--- a/Linux/profile/pb_profile.c
+++ b/Linux/profile/pb_profile.c
@@ -339,7 +339,7 @@ void pbp_free(struct pbp_profile *p)
free(p->proxies[i].name); free(p->proxies[i].host); free(p->proxies[i].user); free(p->proxies[i].pass);
}
for (size_t i = 0; i < p->nrules; i++) {
- free(p->rules[i].process); free(p->rules[i].hosts); free(p->rules[i].ports);
+ free(p->rules[i].name); free(p->rules[i].process); free(p->rules[i].hosts); free(p->rules[i].ports);
}
free(p->proxies);
free(p->rules);
@@ -409,13 +409,14 @@ static int read_proxy(struct pbp_profile *p, const struct jv *o, size_t idx, cha
free(x->name);
x->name = strdup(fallback);
}
+ x->send_domain = jbool(o, "SendDomainToProxy", true);
x->user = dup_or(jtext(o, "Username"), "");
x->pass = dup_or(jtext(o, "Password"), "");
if (!x->name || !x->user || !x->pass) { snprintf(err, errlen, "out of memory"); return -1; }
return 0;
}
-static int read_rule(struct pbp_profile *p, const struct jv *o, size_t idx, char *err, size_t errlen)
+static int read_rule(struct pbp_profile *p, const struct jv *o, size_t idx, bool default_localhost, char *err, size_t errlen)
{
struct pbp_rule *r = &p->rules[p->nrules];
memset(r, 0, sizeof *r);
@@ -425,9 +426,10 @@ static int read_rule(struct pbp_profile *p, const struct jv *o, size_t idx, char
r->hosts = pbp_merge_hosts(hosts, domains);
free(hosts);
free(domains);
+ r->name = dup_or(jtext(o, "Name"), "");
r->process = dup_or(jtext(o, "ProcessName"), "*");
r->ports = dup_or(jtext(o, "TargetPorts"), "*");
- if (!r->hosts || !r->process || !r->ports) { snprintf(err, errlen, "out of memory"); return -1; }
+ if (!r->name || !r->hosts || !r->process || !r->ports) { snprintf(err, errlen, "out of memory"); return -1; }
char *proto = jtext(o, "Protocol"), *act = jtext(o, "Action");
int rc = 0;
@@ -446,6 +448,7 @@ static int read_rule(struct pbp_profile *p, const struct jv *o, size_t idx, char
if (rc) return rc;
r->enabled = jbool(o, "IsEnabled", true);
+ r->localhost = r->action == 0 && jbool(o, "LocalhostViaProxy", default_localhost);
long pid = jnum(o, "ProxyConfigId", 0);
if (pid < 0 || (pid > 0 && !pbp_find_proxy(p, (uint32_t)pid))) {
snprintf(err, errlen, "ProxyRules[%zu]: ProxyConfigId %ld does not match any proxy", idx, pid);
@@ -504,11 +507,12 @@ int pbp_parse(const char *json, size_t len, struct pbp_profile *out, char *err,
rc = -1;
}
}
+ bool default_localhost = jbool(&root, "LocalhostViaProxy", false); // profiles from before the setting became per rule
for (size_t i = 0; rc == 0 && cfgs && i < cfgs->nk; i++)
rc = cfgs->kid[i].t == J_OBJ ? read_proxy(out, &cfgs->kid[i], i, err, errlen)
: (snprintf(err, errlen, "ProxyConfigs[%zu] is not an object", i), -1);
for (size_t i = 0; rc == 0 && rules && i < rules->nk; i++)
- rc = rules->kid[i].t == J_OBJ ? read_rule(out, &rules->kid[i], i, err, errlen)
+ rc = rules->kid[i].t == J_OBJ ? read_rule(out, &rules->kid[i], i, default_localhost, err, errlen)
: (snprintf(err, errlen, "ProxyRules[%zu] is not an object", i), -1);
if (rc == 0 && out->default_proxy_id && !pbp_find_proxy(out, out->default_proxy_id)) {
snprintf(err, errlen, "DefaultProxyId %u does not match any proxy", out->default_proxy_id);
@@ -585,7 +589,6 @@ char *pbp_serialize(const struct pbp_profile *p)
struct sb b = {0};
sb_puts(&b, "{\n \"Version\": \"1.0\",\n");
sb_kv(&b, " ", "Name", p->name ? p->name : "", ",\n");
- sb_puts(&b, " \"LocalhostViaProxy\": false,\n");
sb_puts(&b, p->logging ? " \"IsTrafficLoggingEnabled\": true,\n" : " \"IsTrafficLoggingEnabled\": false,\n");
sb_puts(&b, p->dns_via_proxy ? " \"DnsViaProxy\": true,\n" : " \"DnsViaProxy\": false,\n");
sb_fmt(&b, " \"DefaultProxyId\": %u,\n", p->default_proxy_id);
@@ -603,7 +606,7 @@ char *pbp_serialize(const struct pbp_profile *p)
sb_kv(&b, " ", "Port", port, ",\n");
sb_kv(&b, " ", "Username", x->user, ",\n");
sb_kv(&b, " ", "Password", x->pass, ",\n");
- sb_puts(&b, " \"SendDomainToProxy\": false\n }");
+ sb_puts(&b, x->send_domain ? " \"SendDomainToProxy\": true\n }" : " \"SendDomainToProxy\": false\n }");
}
sb_puts(&b, p->nproxies ? "\n ],\n" : "],\n");
@@ -613,7 +616,7 @@ char *pbp_serialize(const struct pbp_profile *p)
char *ips, *doms;
pbp_split_hosts(r->hosts, &ips, &doms);
sb_puts(&b, i ? ",\n {\n" : "\n {\n");
- sb_kv(&b, " ", "Name", "", ",\n");
+ sb_kv(&b, " ", "Name", r->name ? r->name : "", ",\n");
sb_kv(&b, " ", "ProcessName", r->process, ",\n");
sb_kv(&b, " ", "TargetHosts", ips && *ips ? ips : "*", ",\n");
sb_kv(&b, " ", "TargetPorts", r->ports, ",\n");
@@ -621,7 +624,8 @@ char *pbp_serialize(const struct pbp_profile *p)
sb_kv(&b, " ", "Protocol", r->protocol == 1 ? "UDP" : r->protocol == 2 ? "BOTH" : "TCP", ",\n");
sb_kv(&b, " ", "Action", r->action == 1 ? "DIRECT" : r->action == 2 ? "BLOCK" : "PROXY", ",\n");
sb_puts(&b, r->enabled ? " \"IsEnabled\": true,\n" : " \"IsEnabled\": false,\n");
- sb_fmt(&b, " \"ProxyConfigId\": %u\n }", r->proxy_id);
+ sb_fmt(&b, " \"ProxyConfigId\": %u,\n", r->proxy_id);
+ sb_puts(&b, r->localhost ? " \"LocalhostViaProxy\": true\n }" : " \"LocalhostViaProxy\": false\n }");
free(ips);
free(doms);
}
diff --git a/Linux/profile/pb_profile.h b/Linux/profile/pb_profile.h
index e0e99ad..b7f7fcd 100644
--- a/Linux/profile/pb_profile.h
+++ b/Linux/profile/pb_profile.h
@@ -2,13 +2,14 @@
//
// { "Version": "1.0", "Name": "...", "IsTrafficLoggingEnabled": true,
// "ProxyConfigs": [ { "Id": 1, "Name": "work", "Type": "SOCKS5", "Host": "...", "Port": "1080",
-// "Username": "", "Password": "", "SendDomainToProxy": false } ],
-// "ProxyRules": [ { "ProcessName": "...", "TargetHosts": "...", "TargetPorts": "...", "TargetDomains": "...",
+// "Username": "", "Password": "", "SendDomainToProxy": true } ],
+// "ProxyRules": [ { "Name": "...", "ProcessName": "...", "TargetHosts": "...", "TargetPorts": "...", "TargetDomains": "...",
// "Protocol": "TCP|UDP|BOTH", "Action": "PROXY|DIRECT|BLOCK", "IsEnabled": true,
-// "ProxyConfigId": 1 } ] }
+// "ProxyConfigId": 1, "LocalhostViaProxy": false } ] }
//
// Linux keeps domain names in the host list; they are split into TargetDomains on export and merged back on import.
-// Fields this program does not use (LocalhostViaProxy, LogFilters, ...) are ignored on import.
+// Fields this program does not use (LogFilters, ...) are ignored on import. A top-level LocalhostViaProxy from older profiles
+// becomes the default for rules that do not carry their own.
#ifndef PB_PROFILE_H
#define PB_PROFILE_H
@@ -28,13 +29,16 @@ struct pbp_proxy {
char *host;
uint16_t port;
char *user, *pass;
+ bool send_domain; // SendDomainToProxy: the proxy resolves host names (default true)
};
struct pbp_rule {
+ char *name; // label shown in the rule list; may be empty
char *process, *hosts, *ports; // hosts holds IPs and domain names together
int protocol; // 0 TCP, 1 UDP, 2 BOTH (RuleProtocol)
int action; // 0 PROXY, 1 DIRECT, 2 BLOCK (RuleAction)
bool enabled;
+ bool localhost; // LocalhostViaProxy: a PROXY rule that also proxies 127.0.0.0/8 and ::1
uint32_t proxy_id; // 0 = default proxy
};
diff --git a/Linux/profile/tests/profile_test.c b/Linux/profile/tests/profile_test.c
index f5fdcb8..1f13df8 100644
--- a/Linux/profile/tests/profile_test.c
+++ b/Linux/profile/tests/profile_test.c
@@ -47,6 +47,35 @@ static void test_windows_sample(void)
pbp_free(&p);
}
+static void test_parity_fields(void)
+{
+ struct pbp_profile p, q;
+ char err[256];
+ // per-rule names and localhost flag, per-proxy host-name sending, and the pre-4.2 global LocalhostViaProxy as the default
+ CHECK(parse("{ \"LocalhostViaProxy\": true, \"ProxyConfigs\": ["
+ "{ \"Id\": 1, \"Type\": \"socks5\", \"Host\": \"h\", \"Port\": \"1\", \"SendDomainToProxy\": false },"
+ "{ \"Id\": 2, \"Type\": \"http\", \"Host\": \"h\", \"Port\": \"2\" } ],"
+ "\"ProxyRules\": ["
+ "{ \"Name\": \"Burp\", \"ProcessName\": \"firefox\", \"Action\": \"PROXY\", \"ProxyConfigId\": 1, \"LocalhostViaProxy\": false },"
+ "{ \"ProcessName\": \"curl\", \"Action\": \"PROXY\", \"ProxyConfigId\": 2 },"
+ "{ \"ProcessName\": \"wget\", \"Action\": \"BLOCK\" },"
+ "{ \"Name\": \"own\", \"ProcessName\": \"x\", \"Action\": \"PROXY\", \"LocalhostViaProxy\": true } ] }", &p, err) == 0);
+ CHECK(!p.proxies[0].send_domain && p.proxies[1].send_domain); // true unless the file says otherwise
+ CHECK(!strcmp(p.rules[0].name, "Burp") && !p.rules[0].localhost); // the rule's own value wins over the global one
+ CHECK(!strcmp(p.rules[1].name, "") && p.rules[1].localhost); // no value of its own: the old global default
+ CHECK(!p.rules[2].localhost); // only PROXY rules can proxy localhost
+ CHECK(p.rules[3].localhost);
+ char *json = pbp_serialize(&p);
+ CHECK(json && strstr(json, "\"SendDomainToProxy\": false") && strstr(json, "\"SendDomainToProxy\": true"));
+ CHECK(json && strstr(json, "\"Name\": \"Burp\"") && strstr(json, "\"LocalhostViaProxy\": true"));
+ CHECK(json && !strstr(json, "\"LocalhostViaProxy\": true,\n \"IsTraffic")); // no top-level flag is written any more
+ CHECK(pbp_parse(json, strlen(json), &q, err, sizeof err) == 0);
+ CHECK(!q.proxies[0].send_domain && q.proxies[1].send_domain && !q.rules[0].localhost && q.rules[1].localhost && !strcmp(q.rules[0].name, "Burp"));
+ free(json);
+ pbp_free(&p);
+ pbp_free(&q);
+}
+
static void test_roundtrip(void)
{
struct pbp_profile a, b;
@@ -266,6 +295,7 @@ int main(void)
{
test_windows_sample();
test_roundtrip();
+ test_parity_fields();
test_errors();
test_leniency();
test_hosts();
diff --git a/Linux/src/ProxyBridge.c b/Linux/src/ProxyBridge.c
index 2d19db1..aa5d1db 100644
--- a/Linux/src/ProxyBridge.c
+++ b/Linux/src/ProxyBridge.c
@@ -28,7 +28,7 @@ static struct {
struct pb_proxy proxies[MAX_PROXIES]; size_t nproxies;
uint32_t next_rule_id, next_proxy_id, default_proxy;
bool running;
- atomic_bool dns_via_proxy, traffic_logging, has_domain_rules;
+ atomic_bool dns_via_proxy, traffic_logging, need_names, has_localhost;
pthread_t maint;
bool maint_started, maint_stop, maint_kick;
pthread_mutex_t maint_mu;
@@ -183,12 +183,12 @@ static void arm_cb(uint32_t ip, const char *const *names, int n, void *ctx)
static void rearm_all_locked(void)
{
pb_bpf_dom_clear();
- if (atomic_load(&G.has_domain_rules)) pb_dns_for_each(arm_cb, NULL);
+ if (atomic_load(&G.need_names)) pb_dns_for_each(arm_cb, NULL);
}
void pb_core_dns_observe(const uint8_t *msg, size_t len)
{
- if (!atomic_load(&G.has_domain_rules)) return;
+ if (!atomic_load(&G.need_names)) return;
struct pb_dns_result res;
if (pb_dns_observe(msg, len, &res) <= 0) return;
pthread_rwlock_rdlock(&G.lock);
@@ -223,19 +223,29 @@ static void rebuild_views_locked(void)
free(G.views);
G.views = calloc(G.nrules ? G.nrules : 1, sizeof *G.views);
G.nviews = G.views ? G.nrules : 0;
- bool domains = false;
+ bool names = false, localhost = false;
for (size_t i = 0; i < G.nviews; i++) {
const struct pb_rule *r = &G.rules[i];
struct pb_rule_view *v = &G.views[i];
v->rule = r;
v->action = r->action;
- domains |= r->enabled && r->ndomains > 0;
- if (r->action != RULE_ACTION_PROXY) continue;
- const struct pb_proxy *p = proxy_for_rule_locked(r);
- if (!p) v->action = RULE_ACTION_BLOCK; // no usable proxy: fail closed
- else { v->proxy_id = (uint16_t)p->id; v->udp_direct = p->type == PROXY_TYPE_HTTP; }
+ v->wants_names = r->enabled && r->ndomains > 0;
+ if (r->action == RULE_ACTION_PROXY) {
+ const struct pb_proxy *p = proxy_for_rule_locked(r);
+ if (!p) {
+ v->action = RULE_ACTION_BLOCK; // no usable proxy: fail closed
+ } else {
+ v->proxy_id = (uint16_t)p->id;
+ v->udp_direct = p->type == PROXY_TYPE_HTTP;
+ v->localhost = r->enabled && r->localhost;
+ v->wants_names |= r->enabled && p->send_domain;
+ }
+ }
+ names |= v->wants_names;
+ localhost |= v->localhost;
}
- atomic_store(&G.has_domain_rules, domains);
+ atomic_store(&G.need_names, names);
+ atomic_store(&G.has_localhost, localhost);
}
static void sync_locked(void)
@@ -248,6 +258,32 @@ static void sync_locked(void)
warn_udp_over_http_locked();
}
+static bool is_loopback(const struct pb_orig *o)
+{
+ if (o->family == AF_INET) return o->addr[12] == 127;
+ static const uint8_t lo6[16] = { [15] = 1 };
+ return memcmp(o->addr, lo6, 16) == 0;
+}
+
+int pb_core_name_for(const struct pb_orig *o, char *out, size_t n)
+{
+ if (o->family != AF_INET || !atomic_load(&G.need_names)) return -1;
+ uint32_t ip = ((uint32_t)o->addr[12] << 24) | ((uint32_t)o->addr[13] << 16) | ((uint32_t)o->addr[14] << 8) | o->addr[15];
+ char names[PB_DNS_MAX_NAMES][256];
+ int k = pb_dns_lookup(ip, names, PB_DNS_MAX_NAMES);
+ if (k <= 0) return -1;
+ const char *nm = names[k - 1]; // the lookup lists the most recent query name last
+ size_t len = strlen(nm);
+ if (len == 0 || len > 253 || len >= n) return -1;
+ for (size_t i = 0; i < len; i++) { // the name came from the network: only host name characters go into a proxy request
+ unsigned char ch = (unsigned char)nm[i];
+ if (!((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '_' || ch == '.')) return -1;
+ }
+ if (nm[0] == '.' || nm[len - 1] == '.' ) return -1;
+ memcpy(out, nm, len + 1);
+ return 0;
+}
+
void pb_core_decide(const struct pb_orig *o, struct pb_decision *out)
{
char path[4096];
@@ -256,16 +292,21 @@ void pb_core_decide(const struct pb_orig *o, struct pb_decision *out)
out->proxy_id = 0;
pthread_rwlock_rdlock(&G.lock);
- if (!pb_implicit_direct(o->family, o->addr, o->port, o->proto, atomic_load(&G.dns_via_proxy))) {
+ bool lo = atomic_load(&G.has_localhost) && is_loopback(o) && o->port != 53 &&
+ o->port != pb_relay_tcp_port() && o->port != pb_relay_udp_port();
+ if (lo || !pb_implicit_direct(o->family, o->addr, o->port, o->proto, atomic_load(&G.dns_via_proxy))) {
char names[PB_DNS_MAX_NAMES][256];
const char *ptrs[PB_DNS_MAX_NAMES] = { 0 };
int nn = 0;
- if (o->family == AF_INET && atomic_load(&G.has_domain_rules)) {
+ if (o->family == AF_INET && atomic_load(&G.need_names)) {
uint32_t ip = ((uint32_t)o->addr[12] << 24) | ((uint32_t)o->addr[13] << 16) | ((uint32_t)o->addr[14] << 8) | o->addr[15];
nn = pb_dns_lookup(ip, names, PB_DNS_MAX_NAMES);
for (int k = 0; k < nn; k++) ptrs[k] = names[k];
}
int idx = pb_rules_eval(G.rules, G.nrules, path, o->family, o->addr, o->port, o->proto, ptrs, nn);
+ if (idx >= 0 && lo && !(G.rules[idx].action == RULE_ACTION_PROXY && G.rules[idx].localhost)) {
+ idx = -1; // loopback stays direct unless the matching rule proxies it
+ }
if (idx >= 0) {
const struct pb_rule *r = &G.rules[idx];
if (r->action != RULE_ACTION_PROXY) {
@@ -418,6 +459,7 @@ uint32_t ProxyBridge_AddProxy(const char *name, ProxyType type, const char *host
struct pb_proxy *p = &G.proxies[G.nproxies++];
memset(p, 0, sizeof *p);
p->id = id = G.next_proxy_id++;
+ p->send_domain = true;
fill_proxy(p, name, type, host, port, user, pass);
sync_locked();
}
@@ -438,6 +480,15 @@ bool ProxyBridge_EditProxy(uint32_t id, const char *name, ProxyType type, const
return p != NULL;
}
+bool ProxyBridge_SetProxySendDomain(uint32_t id, bool send_domain)
+{
+ pthread_rwlock_wrlock(&G.lock);
+ struct pb_proxy *p = find_proxy_locked(id);
+ if (p) { p->send_domain = send_domain; sync_locked(); }
+ pthread_rwlock_unlock(&G.lock);
+ return p != NULL;
+}
+
bool ProxyBridge_DeleteProxy(uint32_t id)
{
bool ok = false;
@@ -542,6 +593,7 @@ bool ProxyBridge_EditRule(uint32_t id, const char *proc, const char *hosts, cons
} else {
r.id = id;
r.enabled = old->enabled;
+ r.localhost = old->localhost;
r.protocol = protocol;
r.action = action;
r.proxy_id = proxy_id;
@@ -553,6 +605,15 @@ bool ProxyBridge_EditRule(uint32_t id, const char *proc, const char *hosts, cons
return old != NULL;
}
+bool ProxyBridge_SetRuleLocalhost(uint32_t id, bool on)
+{
+ pthread_rwlock_wrlock(&G.lock);
+ struct pb_rule *r = find_rule_locked(id, NULL);
+ if (r) { r->localhost = on; sync_locked(); }
+ pthread_rwlock_unlock(&G.lock);
+ return r != NULL;
+}
+
static bool set_enabled(uint32_t id, bool on)
{
pthread_rwlock_wrlock(&G.lock);
diff --git a/Linux/src/ProxyBridge.h b/Linux/src/ProxyBridge.h
index 267bb8f..ccb88b9 100644
--- a/Linux/src/ProxyBridge.h
+++ b/Linux/src/ProxyBridge.h
@@ -40,6 +40,11 @@ PB_API uint32_t ProxyBridge_AddProxy(const char* name, ProxyType type, const cha
const char* username, const char* password, char* err, size_t err_size);
PB_API bool ProxyBridge_EditProxy(uint32_t proxy_id, const char* name, ProxyType type, const char* host, uint16_t port,
const char* username, const char* password, char* err, size_t err_size);
+/* "DNS via proxy" of one proxy (default true, as in the Windows and macOS apps): connections to an address whose host name the
+ * application resolved are sent to the proxy by name, so the proxy resolves it (SOCKS5 domain address / HTTP CONNECT host name).
+ * False sends the IP address. Names come from the application's own unencrypted DNS answers; without one the IP is sent.
+ * UDP datagrams always carry the IP. */
+PB_API bool ProxyBridge_SetProxySendDomain(uint32_t proxy_id, bool send_domain);
PB_API bool ProxyBridge_DeleteProxy(uint32_t proxy_id); /* rules that used it fall back to the default proxy */
PB_API void ProxyBridge_ClearProxies(void);
/* Which proxy a rule with proxy_id == 0 uses. 0 = the first proxy added. */
@@ -56,6 +61,10 @@ PB_API uint32_t ProxyBridge_AddRule(const char* process_name, const char* target
RuleProtocol protocol, RuleAction action, uint32_t proxy_id, char* err, size_t err_size);
PB_API bool ProxyBridge_EditRule(uint32_t rule_id, const char* process_name, const char* target_hosts, const char* target_ports,
RuleProtocol protocol, RuleAction action, uint32_t proxy_id, char* err, size_t err_size);
+/* "Also proxy localhost traffic" of one PROXY rule (default false): connections to 127.0.0.0/8 and ::1 that match the rule go to
+ * the proxy. Without it a PROXY rule leaves loopback traffic direct, as Windows does. BLOCK and DIRECT rules never touch
+ * loopback, and neither does DNS to the local resolver stub (port 53). */
+PB_API bool ProxyBridge_SetRuleLocalhost(uint32_t rule_id, bool localhost_via_proxy);
PB_API bool ProxyBridge_EnableRule(uint32_t rule_id);
PB_API bool ProxyBridge_DisableRule(uint32_t rule_id);
PB_API bool ProxyBridge_DeleteRule(uint32_t rule_id);
diff --git a/Linux/src/bpf/pb_bpf_shared.h b/Linux/src/bpf/pb_bpf_shared.h
index ef98709..8b2432d 100644
--- a/Linux/src/bpf/pb_bpf_shared.h
+++ b/Linux/src/bpf/pb_bpf_shared.h
@@ -22,6 +22,7 @@ typedef uint8_t pb_u8; typedef uint16_t pb_u16; typedef uint32_t pb_u32; typedef
#define PB_RF_HAS_V6 0x10 // IPv6 patterns present: "maybe" for IPv6 destinations
#define PB_RF_UDP_DIRECT 0x20 // PROXY rule whose proxy cannot carry UDP: UDP goes direct
#define PB_RF_DOMAINS 0x40 // answered through the dom_hit map filled by the DNS tap
+#define PB_RF_LOCALHOST 0x80 // PROXY rule that also proxies loopback destinations
#define PB_CLASS_DECIDE 0xffffffffu // pb_bclass.n: always take the slow path for this binary
@@ -32,6 +33,7 @@ struct pb_cfg {
pb_u32 dns_via_proxy;
pb_u32 dns_tap; // a domain rule exists
pb_u32 n_exempt; // entries in the exempt map
+ pb_u32 n_localhost; // rules that proxy loopback traffic; 0 keeps every loopback connection out of the rule walk
pb_u16 tcp_port, udp_port;
pb_u64 netns; // network namespace of the relay; other namespaces are ignored (0 = unknown)
};
diff --git a/Linux/src/bpf/proxybridge.bpf.c b/Linux/src/bpf/proxybridge.bpf.c
index db8a033..ea10862 100644
--- a/Linux/src/bpf/proxybridge.bpf.c
+++ b/Linux/src/bpf/proxybridge.bpf.c
@@ -92,6 +92,16 @@ static __always_inline int rule_match(const struct pb_brule *r, __u32 ri, __u8 f
return (host_res == M_MAYBE || port_res == M_MAYBE) ? M_MAYBE : M_YES;
}
+static __always_inline int is_loopback(const struct pb_orig *o)
+{
+ const __u8 *a = o->addr;
+ if (o->family == AF_INET) return a[12] == 127;
+ int loopback = a[15] == 1;
+ #pragma unroll
+ for (int i = 0; i < 15; i++) if (a[i]) loopback = 0;
+ return loopback;
+}
+
static __always_inline int implicit_direct(const struct pb_orig *o)
{
const __u8 *a = o->addr;
@@ -114,7 +124,9 @@ static __always_inline int decide(struct pb_orig *o)
if (!cfg.enabled || o->pid == cfg.self_tgid) return ACT_DIRECT;
if (cfg.n_exempt && bpf_map_lookup_elem(&exempt, &o->pid)) return ACT_DIRECT;
int tap = o->port == 53 && cfg.dns_tap;
- if (!tap && implicit_direct(o)) return ACT_DIRECT;
+ // Loopback joins the rule walk only when some rule asks for it; the resolver stub (port 53) and the relay itself never do.
+ int lo = cfg.n_localhost && is_loopback(o) && o->port != 53 && o->port != cfg.tcp_port && o->port != cfg.udp_port;
+ if (!tap && !lo && implicit_direct(o)) return ACT_DIRECT;
struct mm_struct *mm = bpf_get_current_task_btf()->mm;
if (!mm) return ACT_DIRECT;
@@ -146,6 +158,7 @@ static __always_inline int decide(struct pb_orig *o)
int m = rule_match(r, ri, o->family, ip4, o->port);
if (m == M_NO) continue;
if (m == M_MAYBE) return ACT_DECIDE;
+ if (lo && !(r->action == ACT_PROXY && (r->flags & PB_RF_LOCALHOST))) return ACT_DIRECT;
if (r->action != ACT_PROXY) return r->action;
if (o->proto == IPPROTO_UDP && (r->flags & PB_RF_UDP_DIRECT)) return ACT_DIRECT;
o->proxy_id = r->proxy_id;
diff --git a/Linux/src/pb_bpf.c b/Linux/src/pb_bpf.c
index df73bb3..18268d6 100644
--- a/Linux/src/pb_bpf.c
+++ b/Linux/src/pb_bpf.c
@@ -304,6 +304,7 @@ static void compile_rule(const struct pb_rule_view *v, struct pb_brule *b)
b->proxy_id = v->action == RULE_ACTION_PROXY ? v->proxy_id : 0;
b->proto_mask = r->protocol == RULE_PROTOCOL_TCP ? 1 : r->protocol == RULE_PROTOCOL_UDP ? 2 : 3;
if (v->action == RULE_ACTION_PROXY && v->udp_direct) b->flags |= PB_RF_UDP_DIRECT;
+ if (v->action == RULE_ACTION_PROXY && v->localhost) b->flags |= PB_RF_LOCALHOST;
if (r->any_port) b->flags |= PB_RF_ANY_PORT;
for (int i = 0; i < r->nports; i++) {
@@ -331,7 +332,7 @@ static void class_for(const struct pb_rule_view *v, const struct pb_brule *br, s
memset(out, 0, sizeof *out);
for (size_t i = 0; i < n; i++) {
if (!v[i].rule->enabled || !pb_rule_match_process(v[i].rule, path)) continue;
- if (pb_rule_has_domains(v[i].rule)) out->tap = 1;
+ if (v[i].wants_names) out->tap = 1;
if (out->n >= PB_RULES_PER_CLASS) {
memset(out->rule, 0, sizeof out->rule);
out->n = PB_CLASS_DECIDE;
@@ -400,13 +401,15 @@ int pb_bpf_sync(const struct pb_rule_view *v, size_t n)
G.br = br; G.nbr = n;
bool active = false, domains = false;
+ uint32_t localhost = 0;
for (size_t i = 0; i < n; i++) {
compile_rule(&v[i], &br[i]);
uint32_t k = (uint32_t)i;
bpf_map_update_elem(MAPFD(brules), &k, &br[i], BPF_ANY);
if (v[i].rule->enabled) {
active = true;
- domains |= pb_rule_has_domains(v[i].rule) != 0;
+ domains |= v[i].wants_names;
+ localhost += v[i].localhost;
}
}
@@ -422,6 +425,7 @@ int pb_bpf_sync(const struct pb_rule_view *v, size_t n)
free(stale);
G.skel->bss->cfg.dns_tap = domains;
+ G.skel->bss->cfg.n_localhost = localhost;
G.skel->bss->cfg.enabled = active;
pthread_mutex_unlock(&G.lock);
return 0;
diff --git a/Linux/src/pb_bpf.h b/Linux/src/pb_bpf.h
index 56abe6b..6bc582e 100644
--- a/Linux/src/pb_bpf.h
+++ b/Linux/src/pb_bpf.h
@@ -19,6 +19,8 @@ struct pb_rule_view {
int action; // PROXY with no usable proxy has already become BLOCK
uint16_t proxy_id;
bool udp_direct; // the proxy cannot carry UDP
+ bool localhost; // PROXY rule that also proxies loopback destinations
+ bool wants_names; // needs the DNS tap: a domain rule, or a proxy that is sent host names
};
typedef void (*pb_event_cb)(const struct pb_event *e);
diff --git a/Linux/src/pb_dns.c b/Linux/src/pb_dns.c
index c78050a..035d181 100644
--- a/Linux/src/pb_dns.c
+++ b/Linux/src/pb_dns.c
@@ -88,6 +88,14 @@ static void add_mapping(uint32_t ip, char names[][256], int nn, struct pb_dns_re
if (e->n == PB_DNS_MAX_NAMES) { free(e->names[0]); memmove(&e->names[0], &e->names[1], (PB_DNS_MAX_NAMES - 1) * sizeof(char *)); e->n--; }
e->names[e->n++] = c;
}
+ // names[0] is the name the application asked for: keep it last, where the lookup reports "most recent"
+ for (int j = 0; j + 1 < e->n && nn > 0; j++) {
+ if (strcmp(e->names[j], names[0]) != 0) continue;
+ char *q = e->names[j];
+ memmove(&e->names[j], &e->names[j + 1], (size_t)(e->n - j - 1) * sizeof(char *));
+ e->names[e->n - 1] = q;
+ break;
+ }
if (res) {
bool dup = false;
for (int i = 0; i < res->nips; i++) if (res->ips[i] == ip) dup = true;
diff --git a/Linux/src/pb_internal.h b/Linux/src/pb_internal.h
index 7a15989..c060410 100644
--- a/Linux/src/pb_internal.h
+++ b/Linux/src/pb_internal.h
@@ -44,6 +44,7 @@ struct pb_proxy {
uint16_t port;
char user[256]; // empty = no authentication
char pass[256];
+ bool send_domain; // send the host name the application resolved to the proxy (the proxy resolves DNS)
};
// ---- provided by the core ----
@@ -55,6 +56,9 @@ int pb_core_take_tcp_orig(uint32_t client_ip_be, uint16_t client_port, struct p
// Original destination behind a UDP flow address (the IP_PKTINFO destination of a datagram). Does not consume.
int pb_core_get_udp_flow(uint32_t flow_ip_be, struct pb_orig *out);
+// Host name the application most recently resolved to the destination of `o` (IPv4, from the DNS tap); 0 if known.
+int pb_core_name_for(const struct pb_orig *o, char *out, size_t n);
+
// Full rule evaluation for a PB_ACT_DECIDE flow.
void pb_core_decide(const struct pb_orig *o, struct pb_decision *out);
diff --git a/Linux/src/pb_relay.c b/Linux/src/pb_relay.c
index 2fc833e..3e2409f 100644
--- a/Linux/src/pb_relay.c
+++ b/Linux/src/pb_relay.c
@@ -734,14 +734,17 @@ static void tcp_job_run(struct job *j)
} else {
struct io x = { .fd = up, .dl = dl, .stopfd = R.stopfd };
int rc;
+ char hn[256];
+ bool named = px.send_domain && pb_core_name_for(o, hn, sizeof hn) == 0;
if (px.type == PROXY_TYPE_SOCKS5) {
struct s5dst d;
s5dst_from_orig(&d, o);
+ if (named) { d.atyp = 3; snprintf(d.host, sizeof d.host, "%s", hn); }
rc = socks5_request(&x, &px, 1, &d, NULL);
} else {
char ip[INET6_ADDRSTRLEN];
fmt_ip(o->family, o->addr, ip, sizeof ip);
- rc = http_connect(&x, &px, ip, o->port, left, &leftn);
+ rc = http_connect(&x, &px, named ? hn : ip, o->port, left, &leftn);
}
if (rc) {
snprintf(err, sizeof err, "proxy %s -> %s: %s", desc, dst, x.err);
diff --git a/Linux/src/pb_rules.h b/Linux/src/pb_rules.h
index a2dfc02..aeffc95 100644
--- a/Linux/src/pb_rules.h
+++ b/Linux/src/pb_rules.h
@@ -25,6 +25,7 @@ struct pb_rule {
RuleProtocol protocol;
RuleAction action;
uint32_t proxy_id; // action == PROXY: 0 = default proxy
+ bool localhost; // action == PROXY: also proxy loopback destinations that match
char process_src[512], hosts_src[PB_HOSTS_MAX], ports_src[512]; // original text, kept for the UI / export
diff --git a/Linux/src/tests/relay_test.c b/Linux/src/tests/relay_test.c
index 452d52f..4304599 100644
--- a/Linux/src/tests/relay_test.c
+++ b/Linux/src/tests/relay_test.c
@@ -121,6 +121,12 @@ static uint32_t fnv(const uint8_t *p, size_t n)
while (n--) { h ^= *p++; h *= 16777619u; }
return h;
}
+int pb_core_name_for(const struct pb_orig *o, char *out, size_t n)
+{
+ (void)o; (void)out; (void)n;
+ return -1;
+}
+
void pb_core_dns_observe(const uint8_t *m, size_t len)
{
int64_t t0 = mono_ms();
diff --git a/Linux/tests/api_live_test.c b/Linux/tests/api_live_test.c
index ae7d64b..fb980b1 100644
--- a/Linux/tests/api_live_test.c
+++ b/Linux/tests/api_live_test.c
@@ -39,6 +39,7 @@ int main(void)
check("invalid port rejected", !ProxyBridge_ValidateRule("curl", "*", "99999", err, sizeof err));
check("domain accepted", ProxyBridge_ValidateRule("curl", "*.example.org", "443", err, sizeof err));
check("AddRule with bad pattern returns 0 + message", ProxyBridge_AddRule("curl", "1.2.3", "*", RULE_PROTOCOL_TCP, RULE_ACTION_PROXY, 0, err, sizeof err) == 0 && err[0]);
+ check("SetProxySendDomain/SetRuleLocalhost refuse unknown ids", !ProxyBridge_SetProxySendDomain(9999, false) && !ProxyBridge_SetRuleLocalhost(9999, true));
check("AddProxy with empty host rejected", ProxyBridge_AddProxy("x", PROXY_TYPE_SOCKS5, "", 1080, "", "", err, sizeof err) == 0);
check("AddProxy with port 0 rejected", ProxyBridge_AddProxy("x", PROXY_TYPE_SOCKS5, "h", 0, "", "", err, sizeof err) == 0);
diff --git a/Linux/tests/e2e_domains.sh b/Linux/tests/e2e_domains.sh
index 8cf9b0c..83e2b7e 100755
--- a/Linux/tests/e2e_domains.sh
+++ b/Linux/tests/e2e_domains.sh
@@ -1,5 +1,6 @@
#!/bin/bash
# End-to-end test of domain-name rules (DNS tap). Needs root, dig, curl, python3.
+# Proxies get the resolved host name (the default "DNS via proxy"), so the fake proxy reports names, not addresses.
# sudo Linux/tests/e2e_domains.sh
set -u
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
@@ -38,14 +39,14 @@ ip2=$(dig @$DNSIP +tcp tcp.example.test +short +time=3 +tries=1 | head -1); has
nx=$(dig @$DNSIP nope.example.test +time=3 +tries=1 | grep -c NXDOMAIN); [ "$nx" -ge 1 ] && ok "NXDOMAIN is passed through" || bad "NXDOMAIN lost"
echo "== domain rules: resolve with one process, connect with another"
-out=$(curl -s -m 5 http://192.0.2.77/); has "*.example.test -> proxy a (UDP DNS learned)" "$out" "hello-from-A dst=192.0.2.77:80"
-out=$(curl -s -m 5 http://192.0.2.80/); has "*.example.test -> proxy a (TCP DNS learned)" "$out" "hello-from-A dst=192.0.2.80:80"
+out=$(curl -s -m 5 http://192.0.2.77/); has "*.example.test -> proxy a (UDP DNS learned)" "$out" "hello-from-A dst=app.example.test:80"
+out=$(curl -s -m 5 http://192.0.2.80/); has "*.example.test -> proxy a (TCP DNS learned)" "$out" "hello-from-A dst=tcp.example.test:80"
resolve blocked.example.test >/dev/null
out=$(curl -s -m 5 http://192.0.2.78/ 2>&1; echo "rc=$?"); has "exact-name BLOCK rule beats the wildcard rule" "$out" "rc=7"
resolve www.corp.test >/dev/null
-out=$(curl -s -m 5 http://192.0.2.79/); has "CNAME chain: rule on the canonical name -> proxy b" "$out" "hello-from-B dst=192.0.2.79:80"
+out=$(curl -s -m 5 http://192.0.2.79/); has "CNAME chain: rule on the canonical name -> proxy b" "$out" "hello-from-B dst=www.corp.test:80"
resolve svc.byname.test >/dev/null
-out=$(curl -s -m 5 http://192.0.2.81/); has "domain rule + proxy configured by hostname (localhost)" "$out" "hello-from-A dst=192.0.2.81:80"
+out=$(curl -s -m 5 http://192.0.2.81/); has "domain rule + proxy configured by hostname (localhost)" "$out" "hello-from-A dst=svc.byname.test:80"
echo "== things that must NOT match"
resolve plain.other.test >/dev/null
diff --git a/Linux/tests/e2e_parity.sh b/Linux/tests/e2e_parity.sh
new file mode 100755
index 0000000..95dcb92
--- /dev/null
+++ b/Linux/tests/e2e_parity.sh
@@ -0,0 +1,117 @@
+#!/bin/bash
+# End-to-end test of the Windows/macOS parity options: a proxy that resolves host names ("DNS via proxy", per proxy) and
+# "Also proxy localhost traffic" (per rule). Needs root, dig, curl, python3.
+# sudo Linux/tests/e2e_parity.sh
+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; }
+[ "$(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
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+has() { [[ "$2" == *"$3"* ]] && ok "$1" || bad "$1 (got: ${2:0:200})"; }
+hasnt() { [[ "$2" != *"$3"* ]] && ok "$1" || bad "$1 (got: ${2:0:200})"; }
+PB_PID=""
+cleanup() { [ -n "$PB_PID" ] && kill "$PB_PID" 2>/dev/null; kill $FAKE $DNSP $DNSL $WWW $UDPE 2>/dev/null; wait 2>/dev/null; ip addr del $DNSIP/32 dev lo 2>/dev/null; rm -rf "$WORK"; }
+trap cleanup EXIT
+export LD_LIBRARY_PATH="$PB_DIR"
+ip addr add $DNSIP/32 dev lo 2>/dev/null
+python3 "$HERE/fake_proxies.py" "$PLOG" > /dev/null 2>&1 & FAKE=$!
+python3 "$HERE/fake_dns.py" $DNSIP "$DLOG" > /dev/null 2>&1 & DNSP=$!
+python3 "$HERE/fake_dns.py" $LODNS "$DLOG" > /dev/null 2>&1 & DNSL=$!
+mkdir -p "$WORK/www"; echo "local-origin" > "$WORK/www/index.html"
+python3 -m http.server 18401 --bind 127.0.0.1 --directory "$WORK/www" > /dev/null 2>&1 & WWW=$!
+python3 - > /dev/null 2>&1 <<'PY' & UDPE=$!
+import socket
+s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.bind(("127.0.0.1", 18402))
+while True:
+ d, a = s.recvfrom(2048); s.sendto(b"LOCAL-ECHO " + d, a)
+PY
+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=$!
+ 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=""; }
+resolve() { dig @$DNSIP "$1" +short +time=3 +tries=1 | head -1; }
+
+echo "== per-proxy host-name sending (DNS via proxy)"
+start_pb --verbose 1 \
+ --proxy a=socks5://127.0.0.1:19080 --proxy l=socks5://127.0.0.1:19080?dns=local \
+ --proxy c=http://127.0.0.1:19082 --proxy cl=http://127.0.0.1:19082?dns=local \
+ --rule "*:192.0.2.77:*:TCP:PROXY=a" --rule "*:192.0.2.80:*:TCP:PROXY=l" \
+ --rule "*:192.0.2.81:*:TCP:PROXY=c" --rule "*:192.0.2.82:*:TCP:PROXY=cl" --rule "*:192.0.2.99:*:TCP:PROXY=a" || { bad "start"; cat "$WORK/pb.out"; }
+has "proxy option dns=local is reported" "$(cat "$WORK/pb.out")" "Proxies: 4"
+resolve app.example.test >/dev/null; resolve tcp.example.test >/dev/null; resolve svc.byname.test >/dev/null; resolve plain.other.test >/dev/null
+out=$(curl -s -m 5 http://192.0.2.77/); has "SOCKS5: the resolved name goes to the proxy (ATYP domain)" "$out" "hello-from-A dst=app.example.test:80"
+out=$(curl -s -m 5 http://192.0.2.80/); has "SOCKS5 with dns=local: the IP goes to the proxy" "$out" "hello-from-A dst=192.0.2.80:80"
+out=$(curl -s -m 5 http://192.0.2.81/); has "HTTP CONNECT: the resolved name goes to the proxy" "$out" "hello-from-C dst=svc.byname.test:80"
+out=$(curl -s -m 5 http://192.0.2.82/); has "HTTP CONNECT with dns=local: the IP goes to the proxy" "$out" "hello-from-C dst=192.0.2.82:80"
+out=$(curl -s -m 5 http://192.0.2.99/); has "no DNS answer seen for the address: the IP is sent" "$out" "hello-from-A dst=192.0.2.99:80"
+resolve app.example.test >/dev/null
+out=$(curl -s -m 5 "http://192.0.2.77:8080/"); has "port is kept with the name" "$out" "dst=app.example.test:8080"
+stop_pb
+
+echo "== a hostile DNS name never reaches a proxy request"
+cat > "$WORK/evil_dns.py" <<'PY'
+import socket, struct, sys
+ip, = sys.argv[1:2]
+s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.bind((ip, 53))
+while True:
+ q, a = s.recvfrom(512)
+ # answer: question copied, one A record for 192.0.2.60 whose owner is "ok.test\r\nX-Evil: 1" (label with control bytes)
+ name = b"ok.test\r\nX-Evil: 1"
+ lab = bytes([len(name)]) + name + b"\x00"
+ hdr = q[:2] + b"\x81\x80" + b"\x00\x01\x00\x01\x00\x00\x00\x00"
+ ques = lab + b"\x00\x01\x00\x01"
+ ans = lab + b"\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04" + bytes([192, 0, 2, 60])
+ s.sendto(hdr + ques + ans, a)
+PY
+python3 "$WORK/evil_dns.py" 127.0.0.10 > /dev/null 2>&1 & EVIL=$!
+sleep 0.5
+start_pb --verbose 1 --proxy c=http://127.0.0.1:19082 --rule "*:192.0.2.60:*:TCP:PROXY=c" || bad "start"
+dig @127.0.0.10 evil.test +short +time=2 +tries=1 > /dev/null
+out=$(curl -s -m 5 http://192.0.2.60/)
+has "HTTP CONNECT carries the IP, not the unsafe name" "$out" "hello-from-C dst=192.0.2.60:80"
+hasnt "no header injection reached the proxy" "$(cat "$PLOG")" "X-Evil"
+stop_pb; kill $EVIL 2>/dev/null
+
+echo "== per-rule localhost"
+start_pb --verbose 1 \
+ --proxy a=socks5://127.0.0.1:19080 \
+ --rule "curl:127.0.0.1:18401:TCP:PROXY=a+localhost" \
+ --rule "curl2:127.0.0.1:18401:TCP:PROXY=a" \
+ --rule "curl2:*:*:TCP:PROXY=a+localhost" \
+ --rule "curl3:*:*:TCP:BLOCK" \
+ --rule "curl4:127.0.0.*:18401:TCP:PROXY=a+localhost" \
+ --rule "curl5:127.0.0.*:18401:TCP:PROXY=a" \
+ --rule "python3*:127.0.0.1:18402:UDP:PROXY=a+localhost" \
+ --rule "dig:*:*:BOTH:PROXY=a+localhost" || { bad "start"; cat "$WORK/pb.out"; }
+has "rule line shows the option" "$(cat "$WORK/pb.out")" "(+localhost)"
+out=$(curl -s -m 5 http://127.0.0.1:18401/); has "PROXY+localhost: loopback TCP goes to the proxy (kernel path)" "$out" "hello-from-A dst=127.0.0.1:18401"
+out=$("$WORK/curl2" -s -m 5 http://127.0.0.1:18401/); has "PROXY without the option leaves loopback direct" "$out" "local-origin"
+out=$("$WORK/curl2" -s -m 5 http://192.0.2.5/); has "...and the same process is still proxied elsewhere" "$out" "hello-from-A dst=192.0.2.5:80"
+out=$("$WORK/curl3" -s -m 5 http://127.0.0.1:18401/); has "BLOCK rules do not apply to loopback" "$out" "local-origin"
+out=$("$WORK/curl3" -s -m 3 http://192.0.2.6/ 2>&1; echo "rc=$?"); has "...but still block everything else" "$out" "rc=7"
+out=$("$WORK/curl4" -s -m 5 http://127.0.0.1:18401/); has "PROXY+localhost with a pattern the kernel defers (slow path)" "$out" "hello-from-A dst=127.0.0.1:18401"
+out=$("$WORK/curl5" -s -m 5 http://127.0.0.1:18401/); has "pattern rule without the option stays direct (slow path)" "$out" "local-origin"
+out=$(python3 -c "
+import socket
+s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM); s.settimeout(4); s.sendto(b'ping',('127.0.0.1',18402))
+print(s.recvfrom(2048)[0].decode())
+" 2>&1); has "UDP to loopback goes through the proxy too" "$out" "UDP-A 127.0.0.1:18402 ping"
+out=$(dig @$LODNS app.example.test +short +time=3 +tries=1 | head -1); has "DNS to a loopback resolver is never proxied (port 53)" "$out" "192.0.2.77"
+hasnt "the fake proxy never saw the DNS query" "$(cat "$PLOG")" "127.0.0.9:53"
+stop_pb
+
+echo "== no localhost rule: loopback is untouched, as before"
+start_pb --proxy a=socks5://127.0.0.1:19080 --rule "curl:*:*:TCP:PROXY=a" || bad "start"
+out=$(curl -s -m 5 http://127.0.0.1:18401/); has "loopback stays direct without the option" "$out" "local-origin"
+stop_pb
+
+echo; echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ]
diff --git a/Linux/tests/e2e_profile.sh b/Linux/tests/e2e_profile.sh
index 4903fc7..dd09968 100755
--- a/Linux/tests/e2e_profile.sh
+++ b/Linux/tests/e2e_profile.sh
@@ -92,6 +92,31 @@ start_pb --profile "$WORK/dflt.pbprofile" --dns-via-proxy true
has "explicit --dns-via-proxy wins" "$(cat "$WORK/pb.out")" "DNS via Proxy: Enabled"
stop_pb
+echo "== per-rule LocalhostViaProxy and per-proxy SendDomainToProxy from a profile"
+cat > "$WORK/lo.pbprofile" <<'JSON'
+{ "Version": "1.0", "LocalhostViaProxy": false,
+ "ProxyConfigs": [ { "Id": 1, "Name": "p", "Type": "socks5", "Host": "127.0.0.1", "Port": "19080", "SendDomainToProxy": false } ],
+ "ProxyRules": [
+ { "Name": "with", "ProcessName": "curl", "TargetHosts": "127.0.0.1", "TargetPorts": "18403", "Protocol": "TCP", "Action": "PROXY", "ProxyConfigId": 1, "LocalhostViaProxy": true },
+ { "Name": "without", "ProcessName": "curl", "TargetHosts": "127.0.0.1", "TargetPorts": "18404", "Protocol": "TCP", "Action": "PROXY", "ProxyConfigId": 1 } ] }
+JSON
+chmod 600 "$WORK/lo.pbprofile"
+start_pb --profile "$WORK/lo.pbprofile" || { bad "start"; cat "$WORK/pb.out"; }
+has "the proxy's dns:local option is shown" "$(cat "$WORK/pb.out")" "(dns:local)"
+has "the rule's localhost option is shown" "$(cat "$WORK/pb.out")" "(+localhost)"
+out=$(curl -s -m 5 http://127.0.0.1:18403/); has "LocalhostViaProxy=true: loopback goes to the proxy" "$out" "hello-from-A dst=127.0.0.1:18403"
+out=$(curl -s -m 3 http://127.0.0.1:18404/ 2>&1; echo "rc=$?"); has "no LocalhostViaProxy: loopback stays direct (nothing listens there)" "$out" "rc=7"
+stop_pb
+cat > "$WORK/legacy.pbprofile" <<'JSON'
+{ "Version": "1.0", "LocalhostViaProxy": true,
+ "ProxyConfigs": [ { "Id": 1, "Type": "socks5", "Host": "127.0.0.1", "Port": "19080" } ],
+ "ProxyRules": [ { "ProcessName": "curl", "TargetHosts": "127.0.0.1", "TargetPorts": "18405", "Protocol": "TCP", "Action": "PROXY", "ProxyConfigId": 1 } ] }
+JSON
+chmod 600 "$WORK/legacy.pbprofile"
+start_pb --profile "$WORK/legacy.pbprofile" || bad "start"
+out=$(curl -s -m 5 http://127.0.0.1:18405/); has "an older profile's global LocalhostViaProxy becomes the rule default" "$out" "hello-from-A dst=127.0.0.1:18405"
+stop_pb
+
echo "== bad input is rejected before anything is attached"
expect_fail() { # name expected-text args...
local name="$1" want="$2"; shift 2