Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ define Package/pbr/install
$(INSTALL_DATA) ./files/usr/share/pbr/pbr.user.dnsprefetch $(1)/usr/share/pbr/pbr.user.dnsprefetch
$(INSTALL_DATA) ./files/usr/share/pbr/pbr.user.aws.uc $(1)/usr/share/pbr/pbr.user.aws.uc
$(INSTALL_DATA) ./files/usr/share/pbr/pbr.user.netflix.uc $(1)/usr/share/pbr/pbr.user.netflix.uc
$(INSTALL_DATA) ./files/usr/share/pbr/pbr.user.tunnel-dns.uc $(1)/usr/share/pbr/pbr.user.tunnel-dns.uc
$(INSTALL_DIR) $(1)/etc/uci-defaults
$(INSTALL_BIN) ./files/etc/uci-defaults/90-pbr $(1)/etc/uci-defaults/90-pbr
endef
Expand Down
107 changes: 107 additions & 0 deletions files/usr/share/pbr/pbr.user.tunnel-dns.uc
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Resolves the domains of a policy through a resolver reached via the policy's interface,
// so lookups take the same path as the traffic (and geo-located CDNs answer accordingly).
// Adds server=/<domain>/<resolver>@<device> to the dnsmasq nftset file for every
// policy whose interface is listed below; other domains resolve as before.
// The map is keyed by the pbr/UCI interface name; its device is looked up when pbr starts.
// An entry that is not an address[#port], or an interface with no device at that point,
// is skipped with a warning, so a mistake only costs that interface its pinning.
// If the tunnel goes down later, lookups for its domains fail rather than leak.
// A server= entry for the same domain in /etc/config/dhcp would be used alongside,
// so remove it; a warning is logged when one is found.
// dnsmasq pins @device with IP_UNICAST_IF, which only steers the first route lookup; an
// output policy that marks the query (e.g. a router catch-all) makes the kernel reroute it by
// table and the pin is lost, so queries already routed out their device are left unmarked.
// Ordering: pbr runs user files after processing the policies (the dnsmasq file then holds
// this run's nftset lines) and before comparing that file's hash (so a change to the lines
// appended here restarts dnsmasq). If that order changed, this would break silently.

return function(api) {
if (!api.compat || api.compat < 29) return;

// interface: address[#port] of a resolver reachable through it, e.g. a VPN provider's in-tunnel DNS
let resolvers = {
// wg0: '10.0.0.1',
};
let dnsmasq_file = '/var/run/pbr.dnsmasq';

if (!length(keys(resolvers))) return;
let uci = require('uci').cursor();
if (uci.get('pbr', 'config', 'resolver_set') != 'dnsmasq.nftset') return;

let _warn = function(msg) {
system([ 'logger', '-t', 'pbr', 'tunnel-dns: ' + msg ]);
};
let _is_domain = function(d) {
return match(d, /^[a-z0-9_-]+(\.[a-z0-9_-]+)+$/i) && !match(d, /^[0-9.]+$/);
};

// A bad address would reject pbr's whole ruleset or stop dnsmasq starting, and a
// UCI name in place of the device would never match, so check both first.
let ubus = require('ubus').connect();
let targets = {};
for (let iface, r in resolvers) {
let m = match(r, /^([^#]+)(#([0-9]+))?$/);
let addr = m ? iptoarr(m[1]) : null;
let port = m ? +(m[3] || '53') : 0;
if (!addr || port < 1 || port > 65535) {
_warn(iface + ": '" + r + "' is not an address[#port]; skipped");
continue;
}
let dev = ubus?.call('network.interface.' + iface, 'status')?.l3_device;
if (!dev) {
_warn(iface + ': no device (interface down or unknown); skipped');
continue;
}
targets[iface] = { addr: arrtoip(addr), port, family: (length(addr) == 16) ? '6' : '4', dev };
}
ubus?.disconnect();
if (!length(keys(targets))) return;

let pinned = {};
uci.foreach('dhcp', 'dnsmasq', function(s) {
for (let v in ((type(s.server) == 'array') ? s.server : [ s.server ])) {
// /a.example/b.example/<server> names several domains
let m = match(v || '', /^\/(.*)\//);
for (let d in (m ? split(m[1], '/') : []))
if (d) pinned[d] = true;
}
});

// First policy to claim a domain wins, as it does for the traffic.
let seen = {};
let lines = [];
let used = {};
uci.foreach('pbr', 'policy', function(s) {
if (s.enabled == '0') return;
// The name ends up in a comment; a newline in it would start a new dnsmasq line.
let name = replace(s.name || '', /[[:cntrl:]]+/g, ' ');
let dest = (type(s.dest_addr) == 'array') ? join(' ', s.dest_addr) : (s.dest_addr || '');
for (let d in split(trim(dest), /\s+/)) {
if (!_is_domain(d) || seen[d]) continue;
seen[d] = true;
let t = targets[s.interface];
if (!t) continue;
push(lines, 'server=/' + d + '/' + t.addr + ((t.port != 53) ? '#' + t.port : '') +
'@' + t.dev + ' # ' + name);
used[s.interface] = t;
if (pinned[d])
_warn(d + ' also has a dhcp server entry; remove it, or answers will mix');
}
});

if (!length(lines)) return;

let pairs = { '4': [], '6': [] };
for (let i, t in used)
push(pairs[t.family], '"' + t.dev + '" . ' + t.addr + ' . ' + t.port);
for (let fam in [ '4', '6' ]) {
if (!length(pairs[fam])) continue;
let rule = 'insert rule ' + api.table + ' pbr_output meta l4proto { tcp, udp } oifname . ' +
(fam == '4' ? 'ip' : 'ip6') + ' daddr . th dport { ' + join(', ', pairs[fam]) + ' } return';
(fam == '4') ? api.nft4(rule) : api.nft6(rule);
}
let f = require('fs').open(dnsmasq_file, 'a');
if (!f) return;
f.write(join('\n', lines) + '\n');
f.close();
};
108 changes: 108 additions & 0 deletions tests/06_user_files/05_tunnel_dns
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
Testing pbr.user.tunnel-dns.uc: map entries that are not an address[#port] and interfaces without a device are skipped with a warning, and the dnsmasq server= lines and the pbr_output exemption use the interface's device, not its UCI name. A policy name cannot add lines of its own, and every domain of a multi-domain dhcp server= entry is checked.

-- Testcase --
// The shipped file is read with the real fs; the module cache is then dropped so that
// the include's own require('fs') gets the mock again and never touches the host.
let src = global.mocklib.require('fs').readfile('files/usr/share/pbr/pbr.user.tunnel-dns.uc');
delete global.modules.fs;
let placeholder = "\t\t// wg0: '10.0.0.1',\n";
let entries = "\t\tvpn: '10.8.0.1#5353',\n" +
"\t\tvpnserver: 'fd00::53',\n" +
"\t\twan: 'resolver.example',\n" +
"\t\tlan: '10.0.0.300',\n" +
"\t\twan6: '10.0.0.1#70000',\n" +
"\t\twg0: '10.9.0.1',\n";
let checks = [];
push(checks, ['map_placeholder_found', index(src, placeholder) >= 0]);

let rules = [];
let api = {
compat: 38,
table: 'inet fw4',
nft4: (r) => push(rules, r),
nft6: (r) => push(rules, r),
};
global._orig_loadstring(replace(src, placeholder, entries))()(api);

let dnsmasq = global.mocklib.read_captured('/var/run/pbr.dnsmasq') || '';
let lines = filter(split(dnsmasq, '\n'), (l) => l != '');
let has_line = (l) => index(lines, l) >= 0;
let warnings = map(filter(global.mocklib.argvs(), (a) => type(a) == 'array' && a[0] == 'logger'), (a) => a[3]);
let has_warning = (w) => index(warnings, 'tunnel-dns: ' + w) >= 0;
let rule4 = filter(rules, (r) => index(r, ' ip daddr ') >= 0)[0] || '';
let rule6 = filter(rules, (r) => index(r, ' ip6 daddr ') >= 0)[0] || '';

// Lines name the device (vpn is tun0, vpnserver is wg1), with a port only when not 53.
push(checks, ['vpn_line_uses_device', has_line('server=/example.com/10.8.0.1#5353@tun0 # VPN dom')]);
push(checks, ['ipv6_resolver_line', has_line('server=/example.edu/fd00::53@wg1 # V6 dom')]);
push(checks, ['no_uci_name_in_lines', index(dnsmasq, '@vpn') < 0]);
push(checks, ['first_policy_wins', length(filter(lines, (l) => index(l, 'server=/example.com/') == 0)) == 1]);
push(checks, ['ip_literal_not_a_domain', index(dnsmasq, '192.0.2.1') < 0]);
push(checks, ['disabled_policy_ignored', index(dnsmasq, 'disabled.example') < 0]);

// Skipped entries: no lines, one warning each, and nothing else breaks.
push(checks, ['hostname_skipped', index(dnsmasq, 'example.net') < 0 && has_warning("wan: 'resolver.example' is not an address[#port]; skipped")]);
push(checks, ['bad_address_skipped', has_warning("lan: '10.0.0.300' is not an address[#port]; skipped")]);
push(checks, ['bad_port_skipped', has_warning("wan6: '10.0.0.1#70000' is not an address[#port]; skipped")]);
push(checks, ['no_device_skipped', index(dnsmasq, 'example.info') < 0 && has_warning('wg0: no device (interface down or unknown); skipped')]);
push(checks, ['valid_entries_not_warned', length(filter(warnings, (w) => match(w, /^tunnel-dns: vpn(server)?:/))) == 0]);
// example.org is the second domain of a multi-domain dhcp entry.
push(checks, ['dhcp_server_entry_warned', has_line('server=/example.org/10.8.0.1#5353@tun0 # VPN dom') && has_warning('example.org also has a dhcp server entry; remove it, or answers will mix')]);

// A control character in a policy name must not start a line of its own.
push(checks, ['name_newline_stays_in_comment', has_line('server=/example.biz/10.8.0.1#5353@tun0 # Inject server=/injected.test/9.9.9.9')]);
push(checks, ['no_injected_line', length(filter(lines, (l) => index(l, 'server=/') != 0)) == 0 && index(dnsmasq, '\nserver=/injected.test/') < 0]);

// The pbr_output exemption matches the device too, per family.
push(checks, ['nft4_uses_device', index(rule4, 'oifname . ip daddr . th dport { "tun0" . 10.8.0.1 . 5353 }') >= 0]);
push(checks, ['nft6_uses_device', index(rule6, 'oifname . ip6 daddr . th dport { "wg1" . fd00::53 . 53 }') >= 0]);
push(checks, ['two_rules_only', length(rules) == 2]);

let pass = 0, fail = 0;
for (let c in checks) {
if (c[1]) {
pass++;
} else {
fail++;
printf("FAIL: %s\n", c[0]);
}
}
printf("tunnel_dns: %d/%d passed\n", pass, pass + fail);
-- End --

-- File uci/pbr.json --
{
"pbr": [
{
".name": "config",
"enabled": "1",
"resolver_set": "dnsmasq.nftset"
}
],
"policy": [
{ ".name": "p1", "name": "VPN dom", "interface": "vpn", "dest_addr": "example.com example.org 192.0.2.1" },
{ ".name": "p2", "name": "Later", "interface": "vpn", "dest_addr": "example.com" },
{ ".name": "p3", "name": "V6 dom", "interface": "vpnserver", "dest_addr": "example.edu" },
{ ".name": "p4", "name": "WAN dom", "interface": "wan", "dest_addr": "example.net" },
{ ".name": "p5", "name": "WG dom", "interface": "wg0", "dest_addr": "example.info" },
{ ".name": "p6", "name": "Off", "interface": "vpn", "enabled": "0", "dest_addr": "disabled.example" },
{ ".name": "p7", "name": "Inject\nserver=/injected.test/9.9.9.9", "interface": "vpn", "dest_addr": "example.biz" }
]
}
-- End --

-- File uci/dhcp.json --
{
"dnsmasq": [
{ ".name": "cfg01411c", "server": [ "/unrelated.example/example.org/192.0.2.53" ] }
]
}
-- End --

-- File ubus/network.interface.vpnserver~status.json --
{ "up": true, "l3_device": "wg1", "device": "wg1" }
-- End --

-- Expect stdout --
tunnel_dns: 18/18 passed
-- End --
4 changes: 4 additions & 0 deletions tests/lib/mocklib/uci.uc
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,10 @@ return {
foreach: function(config, stype, cb) {
let rv = false;

/* Like libuci: load the package on first use */
if (!exists(this._configs, config))
this.load(config);

if (exists(this._configs, config)) {
let cfg = this._configs[config],
sids = sort(keys(cfg), (a, b) => cfg[a]['.index'] - cfg[b]['.index']);
Expand Down
Loading