blob: 5f25b134feac880fb7166a4c6de425e57411c4d9 [file] [log] [blame]
Garrick Evansf0ab7132019-06-18 14:50:42 +09001// Copyright 2019 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Garrick Evans3388a032020-03-24 11:25:55 +09005#include "patchpanel/datapath.h"
Garrick Evansf0ab7132019-06-18 14:50:42 +09006
Garrick Evans3d97a392020-02-21 15:24:37 +09007#include <arpa/inet.h>
Garrick Evansc7ae82c2019-09-04 16:25:10 +09008#include <fcntl.h>
9#include <linux/if_tun.h>
10#include <linux/sockios.h>
11#include <net/if.h>
12#include <net/if_arp.h>
13#include <netinet/in.h>
14#include <string.h>
15#include <sys/ioctl.h>
16#include <sys/socket.h>
17
Hugo Benichi2a940542020-10-26 18:50:49 +090018#include <algorithm>
Hugo Benichid82d8832020-08-14 10:05:03 +090019
Qijiang Fan713061e2021-03-08 15:45:12 +090020#include <base/check.h>
Garrick Evansc7ae82c2019-09-04 16:25:10 +090021#include <base/files/scoped_file.h>
22#include <base/logging.h>
Taoyu Li79871c92020-07-02 16:09:39 +090023#include <base/posix/eintr_wrapper.h>
Garrick Evans54861622019-07-19 09:05:09 +090024#include <base/strings/string_number_conversions.h>
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +090025#include <base/strings/string_util.h>
26#include <base/strings/stringprintf.h>
Garrick Evans4f9f5572019-11-26 10:25:16 +090027#include <brillo/userdb_utils.h>
Garrick Evans54861622019-07-19 09:05:09 +090028
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090029#include "patchpanel/adb_proxy.h"
Hugo Benichibfc49112020-12-14 12:54:44 +090030#include "patchpanel/arc_service.h"
Garrick Evans3388a032020-03-24 11:25:55 +090031#include "patchpanel/net_util.h"
32#include "patchpanel/scoped_ns.h"
Garrick Evansc7ae82c2019-09-04 16:25:10 +090033
Garrick Evans3388a032020-03-24 11:25:55 +090034namespace patchpanel {
Garrick Evans54861622019-07-19 09:05:09 +090035
Garrick Evansc7ae82c2019-09-04 16:25:10 +090036namespace {
Hugo Benichi76675592020-04-08 14:29:57 +090037// TODO(hugobenichi) Consolidate this constant definition in a single place.
38constexpr pid_t kTestPID = -2;
Garrick Evansc7ae82c2019-09-04 16:25:10 +090039constexpr char kDefaultIfname[] = "vmtap%d";
40constexpr char kTunDev[] = "/dev/net/tun";
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090041constexpr char kArcAddr[] = "100.115.92.2";
42constexpr char kLocalhostAddr[] = "127.0.0.1";
43constexpr uint16_t kAdbServerPort = 5555;
Hugo Benichie8758b52020-04-03 14:49:01 +090044
Hugo Benichibf811c62020-09-07 17:30:45 +090045// Constants used for dropping locally originated traffic bound to an incorrect
46// source IPv4 address.
47constexpr char kGuestIPv4Subnet[] = "100.115.92.0/23";
48constexpr std::array<const char*, 6> kPhysicalIfnamePrefixes{
49 {"eth+", "wlan+", "mlan+", "usb+", "wwan+", "rmnet+"}};
50
Hugo Benichi3a9162b2020-09-09 15:47:40 +090051constexpr char kApplyLocalSourceMarkChain[] = "apply_local_source_mark";
Hugo Benichi3ef370b2020-11-16 19:07:17 +090052constexpr char kApplyVpnMarkChain[] = "apply_vpn_mark";
Hugo Benichi155de002021-01-19 16:45:46 +090053constexpr char kCheckRoutingMarkChain[] = "check_routing_mark";
Hugo Benichi1e0656f2021-02-15 15:43:38 +090054constexpr char kDropGuestIpv4PrefixChain[] = "drop_guest_ipv4_prefix";
55constexpr char kRedirectDnsChain[] = "redirect_dns";
Hugo Benichi2a940542020-10-26 18:50:49 +090056
Hugo Benichif0f55562021-04-02 15:25:02 +090057// Maximum length of an iptables chain name.
58constexpr int kIptablesMaxChainLength = 28;
59
Garrick Evans8a067562020-05-11 12:47:30 +090060std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
61 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090062 if (n.length() < IFNAMSIZ)
63 return n;
Garrick Evans54861622019-07-19 09:05:09 +090064
Garrick Evans2f581a02020-05-11 10:43:35 +090065 // Best effort attempt to preserve the interface number, assuming it's the
66 // last char in the name.
67 auto c = ifname[ifname.length() - 1];
68 n.resize(IFNAMSIZ - 1);
69 n[n.length() - 1] = c;
70 return n;
Garrick Evans54861622019-07-19 09:05:09 +090071}
Garrick Evansf0ab7132019-06-18 14:50:42 +090072
Hugo Benichiaba7e2e2021-02-22 14:47:11 +090073bool Ioctl(ioctl_t ioctl_h, unsigned long req, const char* arg) {
74 base::ScopedFD control_fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
75 if (!control_fd.is_valid()) {
76 PLOG(ERROR) << "Failed to create control socket for ioctl request=" << req;
77 return false;
78 }
79 if ((*ioctl_h)(control_fd.get(), req, arg) != 0) {
80 PLOG(ERROR) << "ioctl request=" << req << " failed";
81 return false;
82 }
83 return true;
84}
85
Garrick Evans8a067562020-05-11 12:47:30 +090086} // namespace
87
88std::string ArcVethHostName(const std::string& ifname) {
89 return PrefixIfname("veth", ifname);
90}
91
92std::string ArcBridgeName(const std::string& ifname) {
93 return PrefixIfname("arc_", ifname);
94}
95
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090096Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
97 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090098
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090099Datapath::Datapath(MinijailedProcessRunner* process_runner,
100 Firewall* firewall,
101 ioctl_t ioctl_hook)
102 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900103 CHECK(process_runner_);
104}
105
Garrick Evans260ff302019-07-25 11:22:50 +0900106MinijailedProcessRunner& Datapath::runner() const {
107 return *process_runner_;
108}
109
Hugo Benichibf811c62020-09-07 17:30:45 +0900110void Datapath::Start() {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900111 // Restart from a clean iptables state in case of an unordered shutdown.
112 ResetIptables();
113
Hugo Benichibf811c62020-09-07 17:30:45 +0900114 // Enable IPv4 packet forwarding
115 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
116 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
117 << " Guest connectivity will not work correctly.";
118
119 // Limit local port range: Android owns 47104-61000.
120 // TODO(garrick): The original history behind this tweak is gone. Some
121 // investigation is needed to see if it is still applicable.
122 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
123 "32768 47103") != 0)
124 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
125 << " apps may not work correctly.";
126
127 // Enable IPv6 packet forwarding
128 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
129 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
130 << " IPv6 functionality may be broken.";
131
Hugo Benichi58125d32020-09-09 11:25:45 +0900132 // Create a FORWARD ACCEPT rule for connections already established.
133 if (process_runner_->iptables(
134 "filter", {"-A", "FORWARD", "-m", "state", "--state",
135 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900136 LOG(ERROR) << "Failed to install forwarding rule for established"
137 << " connections.";
138
Hugo Benichiac799a82021-03-25 00:16:16 +0900139 // Create a FORWARD rule for accepting any ARC originated traffic regardless
140 // of the output interface. This enables for ARC certain multihoming
141 // scenarios (b/182594063).
142 if (process_runner_->iptables(
143 "filter", {"-A", "FORWARD", "-i", "arc+", "-j", "ACCEPT", "-w"}) != 0)
144 LOG(ERROR) << "Failed to install forwarding rule for ARC traffic";
145
Hugo Benichibf811c62020-09-07 17:30:45 +0900146 // chromium:898210: Drop any locally originated traffic that would exit a
147 // physical interface with a source IPv4 address from the subnet of IPs used
148 // for VMs, containers, and connected namespaces This is needed to prevent
149 // packets leaking with an incorrect src IP when a local process binds to the
150 // wrong interface.
Hugo Benichif0f55562021-04-02 15:25:02 +0900151 if (!AddChain(IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain))
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900152 LOG(ERROR) << "Failed to create " << kDropGuestIpv4PrefixChain
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900153 << " filter chain";
154 if (!ModifyIptables(IpFamily::IPv4, "filter",
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900155 {"-I", "OUTPUT", "-j", kDropGuestIpv4PrefixChain, "-w"}))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900156 LOG(ERROR) << "Failed to set up jump rule from filter OUTPUT to "
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900157 << kDropGuestIpv4PrefixChain;
Hugo Benichibf811c62020-09-07 17:30:45 +0900158 for (const auto& oif : kPhysicalIfnamePrefixes) {
159 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
160 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
161 << kGuestIPv4Subnet << " exiting " << oif;
162 }
163
Hugo Benichi561fae42021-01-22 15:28:40 +0900164 // Set static SNAT rules for any IPv4 traffic originated from a guest (ARC,
165 // Crostini, ...) or a connected namespace.
166 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
167 // need to be explicitly dropped as SNAT cannot be applied to them.
168 if (process_runner_->iptables(
169 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
170 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0)
171 LOG(ERROR) << "Failed to install SNAT mark rules.";
172 if (process_runner_->iptables(
173 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
174 "MASQUERADE", "-w"}) != 0)
175 LOG(ERROR) << "Failed to install SNAT mark rules.";
Hugo Benichibf811c62020-09-07 17:30:45 +0900176 if (!AddOutboundIPv4SNATMark("vmtap+"))
Hugo Benichi561fae42021-01-22 15:28:40 +0900177 LOG(ERROR) << "Failed to set up NAT for TAP devices.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900178
Hugo Benichi2a940542020-10-26 18:50:49 +0900179 // Applies the routing tag saved in conntrack for any established connection
180 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900181 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
182 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900183 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
Hugo Benichi155de002021-01-19 16:45:46 +0900184 // b/177787823 Also restore the routing tag after routing has taken place so
185 // that packets pre-tagged with the VPN routing tag are in sync with their
186 // associated CONNMARK routing tag. This is necessary to correctly identify
187 // packets exiting through the wrong interface.
188 if (!ModifyConnmarkRestore(IpFamily::Dual, "POSTROUTING", "-A", "" /*iif*/,
189 kFwmarkRoutingMask))
190 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK restore rule";
Hugo Benichi2a940542020-10-26 18:50:49 +0900191
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900192 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
193 // tag and tagging the local traffic that should be routed through a VPN.
Hugo Benichif0f55562021-04-02 15:25:02 +0900194 if (!AddChain(IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900195 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
196 << " mangle chain";
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900197 if (!ModifyIptables(IpFamily::Dual, "mangle",
198 {"-A", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
199 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
200 << " to mangle OUTPUT";
201 // Create rules for tagging local sources with the source tag and the vpn
202 // policy tag.
203 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900204 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900205 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
206 << " in " << kApplyLocalSourceMarkChain;
207 }
208 // Finally add a catch-all rule for tagging any remaining local sources with
209 // the SYSTEM source tag
210 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
211 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
212
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900213 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
214 // traffic that should be routed through a VPN.
Hugo Benichif0f55562021-04-02 15:25:02 +0900215 if (!AddChain(IpFamily::Dual, "mangle", kApplyVpnMarkChain))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900216 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900217 // All local outgoing traffic eligible to VPN routing should traverse the VPN
218 // marking chain.
219 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", "" /*iif*/, kFwmarkRouteOnVpn,
220 kFwmarkVpnMask))
221 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
222 // Any traffic that already has a routing tag applied is accepted.
223 if (!ModifyIptables(
224 IpFamily::Dual, "mangle",
225 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
226 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
227 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
228 "connections";
Hugo Benichi155de002021-01-19 16:45:46 +0900229
230 // Sets up a mangle chain used in POSTROUTING for checking consistency between
231 // the routing tag and the output interface.
Hugo Benichif0f55562021-04-02 15:25:02 +0900232 if (!AddChain(IpFamily::Dual, "mangle", kCheckRoutingMarkChain))
Hugo Benichi155de002021-01-19 16:45:46 +0900233 LOG(ERROR) << "Failed to set up " << kCheckRoutingMarkChain
234 << " mangle chain";
Hugo Benichi155de002021-01-19 16:45:46 +0900235 // b/177787823 If it already exists, the routing tag of any traffic exiting an
236 // interface (physical or VPN) must match the routing tag of that interface.
237 if (!ModifyIptables(IpFamily::Dual, "mangle",
238 {"-A", "POSTROUTING", "-m", "mark", "!", "--mark",
239 "0x0/" + kFwmarkRoutingMask.ToString(), "-j",
240 kCheckRoutingMarkChain, "-w"}))
241 LOG(ERROR) << "Failed to add POSTROUTING jump rule to "
242 << kCheckRoutingMarkChain;
Hugo Benichi52a64992021-01-28 17:47:33 +0900243
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900244 // b/178331695 Sets up a nat chain used in OUTPUT for redirecting DNS queries
245 // of system services. When a VPN is connected, a query routed through a
246 // physical network is redirected to the primary nameserver of that network.
Hugo Benichif0f55562021-04-02 15:25:02 +0900247 if (!AddChain(IpFamily::IPv4, "nat", kRedirectDnsChain))
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900248 LOG(ERROR) << "Failed to set up " << kRedirectDnsChain << " nat chain";
249
Hugo Benichi52a64992021-01-28 17:47:33 +0900250 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
251 // incorrectly cause neighbor discovery icmpv6 packets to be dropped. Add
252 // these rules to bypass connmark rule for those packets.
253 for (const auto& type : kNeighborDiscoveryTypes) {
254 if (!ModifyIptables(IpFamily::IPv6, "mangle",
255 {"-I", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
256 "-j", "ACCEPT", "-w"}))
257 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
258 << " packets in OUTPUT";
259 if (!ModifyIptables(IpFamily::IPv6, "mangle",
260 {"-I", kCheckRoutingMarkChain, "-p", "icmpv6",
261 "--icmpv6-type", type, "-j", "RETURN", "-w"}))
262 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
263 << " packets in " << kCheckRoutingMarkChain;
264 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900265}
266
267void Datapath::Stop() {
Hugo Benichibf811c62020-09-07 17:30:45 +0900268 // Restore original local port range.
269 // TODO(garrick): The original history behind this tweak is gone. Some
270 // investigation is needed to see if it is still applicable.
271 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
272 "32768 61000") != 0)
273 LOG(ERROR) << "Failed to restore local port range";
274
275 // Disable packet forwarding
276 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
277 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
278
279 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
280 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900281
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900282 ResetIptables();
283}
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900284
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900285void Datapath::ResetIptables() {
286 // If it exists, remove jump rules from a built-in chain to a custom routing
287 // or tagging chain.
288 ModifyIptables(IpFamily::IPv4, "filter",
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900289 {"-D", "OUTPUT", "-j", kDropGuestIpv4PrefixChain, "-w"},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900290 false /*log_failures*/);
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900291
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900292 // Flush chains used for routing and fwmark tagging. Also delete additional
293 // chains made by patchpanel. Chains used by permission broker (nat
294 // PREROUTING, filter INPUT) and chains used for traffic counters (mangle
295 // {rx,tx}_{<iface>, vpn}) are not flushed.
296 static struct {
297 IpFamily family;
298 std::string table;
299 std::string chain;
300 bool should_delete;
301 } resetOps[] = {
302 {IpFamily::Dual, "filter", "FORWARD", false},
303 {IpFamily::Dual, "mangle", "FORWARD", false},
304 {IpFamily::Dual, "mangle", "INPUT", false},
305 {IpFamily::Dual, "mangle", "OUTPUT", false},
306 {IpFamily::Dual, "mangle", "POSTROUTING", false},
307 {IpFamily::Dual, "mangle", "PREROUTING", false},
308 {IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain, true},
309 {IpFamily::Dual, "mangle", kApplyVpnMarkChain, true},
310 {IpFamily::Dual, "mangle", kCheckRoutingMarkChain, true},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900311 {IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain, true},
312 {IpFamily::IPv4, "nat", kRedirectDnsChain, true},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900313 {IpFamily::IPv4, "nat", "POSTROUTING", false},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900314 {IpFamily::IPv4, "nat", "OUTPUT", false},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900315 };
316 for (const auto& op : resetOps) {
317 // Chains to delete are custom chains and will not exist the first time
318 // patchpanel starts after boot. Skip flushing and delete these chains if
319 // they do not exist to avoid logging spurious error messages.
320 if (op.should_delete && !ModifyChain(op.family, op.table, "-L", op.chain,
321 false /*log_failures*/))
322 continue;
Hugo Benichi155de002021-01-19 16:45:46 +0900323
Hugo Benichif0f55562021-04-02 15:25:02 +0900324 if (!FlushChain(op.family, op.table, op.chain))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900325 LOG(ERROR) << "Failed to flush " << op.chain << " chain in table "
326 << op.table;
Hugo Benichi2a940542020-10-26 18:50:49 +0900327
Hugo Benichif0f55562021-04-02 15:25:02 +0900328 if (op.should_delete && !RemoveChain(op.family, op.table, op.chain))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900329 LOG(ERROR) << "Failed to delete " << op.chain << " chain in table "
330 << op.table;
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900331 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900332}
333
Hugo Benichi33860d72020-07-09 16:34:01 +0900334bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
335 // Try first to delete any netns with name |netns_name| in case patchpanel
336 // did not exit cleanly.
337 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
338 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
339 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
340}
341
342bool Datapath::NetnsDeleteName(const std::string& netns_name) {
343 return process_runner_->ip_netns_delete(netns_name) == 0;
344}
345
Garrick Evans8a949dc2019-07-18 16:17:53 +0900346bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900347 uint32_t ipv4_addr,
348 uint32_t ipv4_prefix_len) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900349 if (!Ioctl(ioctl_, SIOCBRADDBR, ifname.c_str())) {
350 LOG(ERROR) << "Failed to create bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900351 return false;
352 }
353
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900354 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900355 if (process_runner_->ip(
356 "addr", "add",
357 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
358 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
359 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900360 RemoveBridge(ifname);
361 return false;
362 }
363
364 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900365 RemoveBridge(ifname);
366 return false;
367 }
368
369 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900370 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900371 RemoveBridge(ifname);
372 return false;
373 }
374
375 return true;
376}
377
378void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900379 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900380 process_runner_->ip("link", "set", {ifname, "down"});
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900381 if (!Ioctl(ioctl_, SIOCBRDELBR, ifname.c_str()))
382 LOG(ERROR) << "Failed to destroy bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900383}
384
Garrick Evans621ed262019-11-13 12:28:43 +0900385bool Datapath::AddToBridge(const std::string& br_ifname,
386 const std::string& ifname) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900387 struct ifreq ifr;
388 memset(&ifr, 0, sizeof(ifr));
389 strncpy(ifr.ifr_name, br_ifname.c_str(), sizeof(ifr.ifr_name));
390 ifr.ifr_ifindex = FindIfIndex(ifname);
391
392 if (!Ioctl(ioctl_, SIOCBRADDIF, reinterpret_cast<const char*>(&ifr))) {
393 LOG(ERROR) << "Failed to add " << ifname << " to bridge " << br_ifname;
394 return false;
395 }
396
397 return true;
Garrick Evans621ed262019-11-13 12:28:43 +0900398}
399
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900400std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900401 const MacAddress* mac_addr,
402 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900403 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900404 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
405 if (!dev.is_valid()) {
406 PLOG(ERROR) << "Failed to open " << kTunDev;
407 return "";
408 }
409
410 struct ifreq ifr;
411 memset(&ifr, 0, sizeof(ifr));
412 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
413 sizeof(ifr.ifr_name));
414 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
415
416 // If a template was given as the name, ifr_name will be updated with the
417 // actual interface name.
418 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900419 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900420 return "";
421 }
422 const char* ifname = ifr.ifr_name;
423
424 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900425 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900426 return "";
427 }
428
Garrick Evans4f9f5572019-11-26 10:25:16 +0900429 if (!user.empty()) {
430 uid_t uid = -1;
431 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
432 PLOG(ERROR) << "Unable to look up UID for " << user;
433 RemoveTAP(ifname);
434 return "";
435 }
436 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
437 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
438 << ifname;
439 RemoveTAP(ifname);
440 return "";
441 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900442 }
443
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900444 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900445 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
446 if (!sock.is_valid()) {
447 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900448 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900449 RemoveTAP(ifname);
450 return "";
451 }
452
Garrick Evans621ed262019-11-13 12:28:43 +0900453 if (ipv4_addr) {
454 struct sockaddr_in* addr =
455 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
456 addr->sin_family = AF_INET;
457 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
458 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
459 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
460 << " {" << ipv4_addr->ToCidrString() << "}";
461 RemoveTAP(ifname);
462 return "";
463 }
464
465 struct sockaddr_in* netmask =
466 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
467 netmask->sin_family = AF_INET;
468 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
469 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
470 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
471 << " {" << ipv4_addr->ToCidrString() << "}";
472 RemoveTAP(ifname);
473 return "";
474 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900475 }
476
Garrick Evans621ed262019-11-13 12:28:43 +0900477 if (mac_addr) {
478 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
479 hwaddr->sa_family = ARPHRD_ETHER;
480 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
481 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
482 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
483 << " {" << MacAddressToString(*mac_addr) << "}";
484 RemoveTAP(ifname);
485 return "";
486 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900487 }
488
489 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900490 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900491 RemoveTAP(ifname);
492 return "";
493 }
494
495 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
496 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900497 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900498 RemoveTAP(ifname);
499 return "";
500 }
501
502 return ifname;
503}
504
505void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900506 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900507}
508
Hugo Benichi33860d72020-07-09 16:34:01 +0900509bool Datapath::ConnectVethPair(pid_t netns_pid,
510 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900511 const std::string& veth_ifname,
512 const std::string& peer_ifname,
513 const MacAddress& remote_mac_addr,
514 uint32_t remote_ipv4_addr,
515 uint32_t remote_ipv4_prefix_len,
516 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900517 // Set up the virtual pair across the current namespace and |netns_name|.
518 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
519 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
520 << peer_ifname;
521 return false;
522 }
523
524 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900525 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900526 ScopedNS ns(netns_pid, ScopedNS::Type::Network);
Hugo Benichi33860d72020-07-09 16:34:01 +0900527 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900528 LOG(ERROR)
529 << "Cannot create virtual link -- invalid container namespace?";
530 return false;
531 }
532
Hugo Benichi76675592020-04-08 14:29:57 +0900533 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
534 remote_ipv4_prefix_len, true /* link up */,
535 remote_multicast_flag)) {
536 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
537 RemoveInterface(peer_ifname);
538 return false;
539 }
540 }
541
Hugo Benichi76675592020-04-08 14:29:57 +0900542 if (!ToggleInterface(veth_ifname, true /*up*/)) {
543 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
544 RemoveInterface(veth_ifname);
545 return false;
546 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900547
Hugo Benichi76675592020-04-08 14:29:57 +0900548 return true;
549}
550
Hugo Benichi33860d72020-07-09 16:34:01 +0900551bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
552 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900553 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900554 return process_runner_->ip("link", "add",
555 {veth_ifname, "type", "veth", "peer", "name",
556 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900557}
Garrick Evans54861622019-07-19 09:05:09 +0900558
Garrick Evans2470caa2020-03-04 14:15:41 +0900559bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
560 const std::string link = up ? "up" : "down";
561 return process_runner_->ip("link", "set", {ifname, link}) == 0;
562}
Garrick Evans54861622019-07-19 09:05:09 +0900563
Garrick Evans2470caa2020-03-04 14:15:41 +0900564bool Datapath::ConfigureInterface(const std::string& ifname,
565 const MacAddress& mac_addr,
566 uint32_t ipv4_addr,
567 uint32_t ipv4_prefix_len,
568 bool up,
569 bool enable_multicast) {
570 const std::string link = up ? "up" : "down";
571 const std::string multicast = enable_multicast ? "on" : "off";
572 return (process_runner_->ip(
573 "addr", "add",
574 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
575 IPv4AddressToString(
576 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
577 "dev", ifname}) == 0) &&
578 (process_runner_->ip("link", "set",
579 {
580 "dev",
581 ifname,
582 link,
583 "addr",
584 MacAddressToString(mac_addr),
585 "multicast",
586 multicast,
587 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900588}
589
590void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900591 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900592}
593
Hugo Benichi321f23b2020-09-25 15:42:05 +0900594bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
595 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900596 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900597 "filter", {"-I", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
598 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900599}
600
601bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
602 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900603 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900604 "filter", {"-D", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
605 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900606}
607
Hugo Benichifcf81022020-12-04 11:01:37 +0900608bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900609 // Veth interface configuration and client routing configuration:
610 // - attach a name to the client namespace.
611 // - create veth pair across the current namespace and the client namespace.
612 // - configure IPv4 address on remote veth inside client namespace.
613 // - configure IPv4 address on local veth inside host namespace.
614 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900615 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
616 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
617 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900618 return false;
619 }
620
Hugo Benichifcf81022020-12-04 11:01:37 +0900621 if (!ConnectVethPair(
622 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
623 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
624 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900625 LOG(ERROR) << "Failed to create veth pair for"
626 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900627 << nsinfo.pid;
628 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900629 return false;
630 }
631
Hugo Benichifcf81022020-12-04 11:01:37 +0900632 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
633 nsinfo.peer_subnet->AddressAtOffset(0),
634 nsinfo.peer_subnet->PrefixLength(),
635 true /* link up */, false /* enable_multicast */)) {
636 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
637 RemoveInterface(nsinfo.host_ifname);
638 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900639 return false;
640 }
641
642 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900643 ScopedNS ns(nsinfo.pid, ScopedNS::Type::Network);
Hugo Benichifcf81022020-12-04 11:01:37 +0900644 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
645 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
646 RemoveInterface(nsinfo.host_ifname);
647 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900648 return false;
649 }
650
Hugo Benichifcf81022020-12-04 11:01:37 +0900651 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
652 INADDR_ANY)) {
653 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
654 << " inside namespace pid " << nsinfo.pid;
655 RemoveInterface(nsinfo.host_ifname);
656 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900657 return false;
658 }
659 }
660
661 // Host namespace routing configuration
662 // - ingress: add route to client subnet via |host_ifname|.
663 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
664 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
665 // Note that by default unsolicited ingress traffic is not forwarded to the
666 // client namespace unless the client specifically set port forwarding
667 // through permission_broker DBus APIs.
668 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
669 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900670 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
671 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
672 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900673 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900674 RemoveInterface(nsinfo.host_ifname);
675 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900676 return false;
677 }
678
Hugo Benichi7c342672020-09-08 09:18:14 +0900679 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900680 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900681 LOG(ERROR) << "Failed to set SNAT for traffic"
682 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900683 << nsinfo.host_ifname;
684 RemoveInterface(nsinfo.host_ifname);
685 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
686 nsinfo.peer_subnet->BaseAddress(), netmask);
687 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
688 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900689 return false;
690 }
691
Hugo Benichi93306e52020-12-04 16:08:00 +0900692 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
693 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
694 nsinfo.route_on_vpn);
695
Hugo Benichi7c342672020-09-08 09:18:14 +0900696 return true;
697}
698
Hugo Benichifcf81022020-12-04 11:01:37 +0900699void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900700 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
701 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
702 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900703 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900704 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
705 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
706 nsinfo.peer_subnet->BaseAddress(),
707 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
708 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900709}
710
Hugo Benichi8d622b52020-08-13 15:24:12 +0900711void Datapath::StartRoutingDevice(const std::string& ext_ifname,
712 const std::string& int_ifname,
713 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900714 TrafficSource source,
715 bool route_on_vpn) {
716 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900717 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900718 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
719 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
720 << "->" << int_ifname;
721
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900722 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900723 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
724 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900725
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900726 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900727 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
728 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900729
Hugo Benichi2a940542020-10-26 18:50:49 +0900730 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
731 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
732 << source << " for " << int_ifname;
733
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900734 if (!ext_ifname.empty()) {
735 // If |ext_ifname| is not null, mark egress traffic with the
736 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900737 int ifindex = FindIfIndex(ext_ifname);
738 if (ifindex != 0) {
739 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
740 if (!ModifyFwmarkRoutingTag("PREROUTING", "-A", routing_mark, int_ifname))
741 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
742 << ext_ifname << "<-" << int_ifname;
743 } else {
744 // Do not abort: if the PREROUTING tagging mark cannot be
745 // set then |int_ifname| will instead be routed to the default logical
746 // network without connection pinning, aka legacy routing.
747 LOG(ERROR) << "Failed to retrieve interface index of " << ext_ifname;
748 }
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900749 } else {
750 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
751 // PREROUTING to apply any fwmark routing tag saved for the current
752 // connection, and rely on implicit routing to the default logical network
753 // otherwise.
Hugo Benichi1af52392020-11-27 18:09:32 +0900754 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname,
755 kFwmarkRoutingMask))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900756 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
757 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900758
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900759 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900760 // default network is eligible to be routed through a VPN if |route_on_vpn|
761 // is true.
762 if (route_on_vpn &&
763 !ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900764 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900765 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900766}
767
768void Datapath::StopRoutingDevice(const std::string& ext_ifname,
769 const std::string& int_ifname,
770 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900771 TrafficSource source,
772 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900773 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900774 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900775 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
776 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900777 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900778 if (!ext_ifname.empty()) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900779 Fwmark routing_mark = CachedRoutingFwmark(ext_ifname);
780 ModifyFwmarkRoutingTag("PREROUTING", "-D", routing_mark, int_ifname);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900781 } else {
Hugo Benichi1af52392020-11-27 18:09:32 +0900782 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname,
783 kFwmarkRoutingMask);
Hugo Benichi93306e52020-12-04 16:08:00 +0900784 if (route_on_vpn)
785 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900786 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900787}
788
Garrick Evansf0ab7132019-06-18 14:50:42 +0900789bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
790 const std::string& ipv4_addr) {
791 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900792 if (process_runner_->iptables(
793 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
794 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900795 return false;
796
797 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900798 if (process_runner_->iptables(
799 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
800 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900801 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
802 return false;
803 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900804 if (process_runner_->iptables(
805 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
806 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900807 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
808 return false;
809 }
810
811 return true;
812}
813
814void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
815 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900816 process_runner_->iptables(
817 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
818 "--to-destination", ipv4_addr, "-w"});
819 process_runner_->iptables(
820 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
821 "--to-destination", ipv4_addr, "-w"});
822 process_runner_->iptables(
823 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
824 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900825}
826
Hugo Benichie8758b52020-04-03 14:49:01 +0900827bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
828 return process_runner_->iptables(
829 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900830 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900831}
832
833void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
834 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900835 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900836}
837
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900838bool Datapath::AddRedirectDnsRule(const std::string& ifname,
839 const std::string dns_ipv4_addr) {
840 bool success = true;
841 success &= RemoveRedirectDnsRule(ifname);
842 // Use Insert operation to ensure that the new DNS address is used first.
843 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
844 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
845 physical_dns_addresses_[ifname] = dns_ipv4_addr;
846 return success;
847}
848
849bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
850 const auto it = physical_dns_addresses_.find(ifname);
851 if (it == physical_dns_addresses_.end())
852 return true;
853
854 bool success = true;
855 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
856 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
857 physical_dns_addresses_.erase(it);
858 return success;
859}
860
861bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
862 const std::string& protocol,
863 const std::string& ifname,
864 const std::string& dns_ipv4_addr) {
865 std::vector<std::string> args = {op,
866 kRedirectDnsChain,
867 "-p",
868 protocol,
869 "--dport",
870 "53",
871 "-o",
872 ifname,
873 "-j",
874 "DNAT",
875 "--to-destination",
876 dns_ipv4_addr,
877 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900878 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900879}
880
881bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
882 std::vector<std::string> args = {
883 op,
884 "OUTPUT",
885 "-m",
886 "mark",
887 "!",
888 "--mark",
889 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
890 "-j",
891 kRedirectDnsChain,
892 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900893 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900894}
895
Garrick Evans664a82f2019-12-17 12:18:05 +0900896bool Datapath::MaskInterfaceFlags(const std::string& ifname,
897 uint16_t on,
898 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900899 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
900 if (!sock.is_valid()) {
901 PLOG(ERROR) << "Failed to create control socket";
902 return false;
903 }
904 ifreq ifr;
905 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
906 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
907 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
908 return false;
909 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900910 ifr.ifr_flags |= on;
911 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900912 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900913 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
914 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900915 return false;
916 }
917 return true;
918}
919
Garrick Evans260ff302019-07-25 11:22:50 +0900920bool Datapath::AddIPv6HostRoute(const std::string& ifname,
921 const std::string& ipv6_addr,
922 int ipv6_prefix_len) {
923 std::string ipv6_addr_cidr =
924 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
925
Garrick Evans8e8e3472020-01-23 14:03:50 +0900926 return process_runner_->ip6("route", "replace",
927 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900928}
929
930void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
931 const std::string& ipv6_addr,
932 int ipv6_prefix_len) {
933 std::string ipv6_addr_cidr =
934 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
935
Garrick Evans8e8e3472020-01-23 14:03:50 +0900936 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900937}
938
Taoyu Lia0727dc2020-09-24 19:54:59 +0900939bool Datapath::AddIPv6Address(const std::string& ifname,
940 const std::string& ipv6_addr) {
941 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900942}
943
Taoyu Lia0727dc2020-09-24 19:54:59 +0900944void Datapath::RemoveIPv6Address(const std::string& ifname,
945 const std::string& ipv6_addr) {
946 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900947}
948
Hugo Benichi76be34a2020-08-26 22:35:54 +0900949void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900950 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +0900951 if (ifindex == 0) {
952 // Can happen if the interface has already been removed (b/183679000).
953 LOG(ERROR) << "Failed to set up connection pinning on " << ext_ifname;
954 return;
955 }
956
957 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
958 LOG(INFO) << "Start connection pinning on " << ext_ifname
959 << " fwmark=" << routing_mark.ToString();
960 if (!ModifyIptables(
961 IpFamily::Dual, "mangle",
962 {"-A", kCheckRoutingMarkChain, "-o", ext_ifname, "-m", "mark", "!",
963 "--mark",
Hugo Benichi0a110402021-03-25 11:32:52 +0900964 routing_mark.ToString() + "/" + kFwmarkRoutingMask.ToString(),
965 "-w"}))
Hugo Benichi155de002021-01-19 16:45:46 +0900966 LOG(ERROR) << "Could not set fwmark routing filter rule for " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900967 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900968 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname,
969 routing_mark))
Hugo Benichi76be34a2020-08-26 22:35:54 +0900970 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900971 // Save in CONNMARK the source tag for egress traffic of this connection.
972 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
973 kFwmarkAllSourcesMask))
974 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
975 "source tag on "
976 << ext_ifname;
977 // Restore from CONNMARK the source tag for ingress traffic of this connection
978 // (returned traffic).
979 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
980 kFwmarkAllSourcesMask))
981 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
982 "traffic received on "
983 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900984}
985
986void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900987 Fwmark routing_mark = CachedRoutingFwmark(ext_ifname);
988 LOG(INFO) << "Stop connection pinning on " << ext_ifname
989 << " fwmark=" << routing_mark.ToString();
990 if (!ModifyIptables(
991 IpFamily::Dual, "mangle",
992 {"-D", kCheckRoutingMarkChain, "-o", ext_ifname, "-m", "mark", "!",
993 "--mark",
Hugo Benichi0a110402021-03-25 11:32:52 +0900994 routing_mark.ToString() + "/" + kFwmarkRoutingMask.ToString(),
995 "-w"}))
Hugo Benichi155de002021-01-19 16:45:46 +0900996 LOG(ERROR) << "Could not remove fwmark routing filter rule for "
997 << ext_ifname;
Hugo Benichi8c526e92021-03-25 14:59:59 +0900998 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname,
999 routing_mark))
Hugo Benichi76be34a2020-08-26 22:35:54 +09001000 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +09001001 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
1002 kFwmarkAllSourcesMask))
1003 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
1004 "fwmark source tag on "
1005 << ext_ifname;
1006 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
1007 kFwmarkAllSourcesMask))
1008 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
1009 "traffic received on "
1010 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +09001011}
1012
Hugo Benichi2a940542020-10-26 18:50:49 +09001013void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +09001014 int ifindex = FindIfIndex(vpn_ifname);
1015 if (ifindex == 0) {
1016 // Can happen if the interface has already been removed (b/183679000).
1017 LOG(ERROR) << "Failed to start VPN routing on " << vpn_ifname;
1018 return;
1019 }
1020
1021 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
1022 LOG(INFO) << "Start VPN routing on " << vpn_ifname
1023 << " fwmark=" << routing_mark.ToString();
Hugo Benichi891275e2020-12-16 10:35:34 +09001024 if (process_runner_->iptables("nat", {"-A", "POSTROUTING", "-o", vpn_ifname,
1025 "-j", "MASQUERADE", "-w"}) != 0)
1026 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +09001027 StartConnectionPinning(vpn_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +09001028 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", routing_mark, ""))
Hugo Benichi2a940542020-10-26 18:50:49 +09001029 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +09001030 if (vpn_ifname != kArcBridge)
1031 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
1032 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001033 if (!ModifyRedirectDnsJumpRule("-A"))
1034 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001035}
1036
1037void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +09001038 Fwmark routing_mark = CachedRoutingFwmark(vpn_ifname);
1039 LOG(INFO) << "Stop VPN routing on " << vpn_ifname
1040 << " fwmark=" << routing_mark.ToString();
Hugo Benichibfc49112020-12-14 12:54:44 +09001041 if (vpn_ifname != kArcBridge)
1042 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
1043 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi8c526e92021-03-25 14:59:59 +09001044 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", routing_mark, ""))
Hugo Benichi2a940542020-10-26 18:50:49 +09001045 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
1046 StopConnectionPinning(vpn_ifname);
Hugo Benichi891275e2020-12-16 10:35:34 +09001047 if (process_runner_->iptables("nat", {"-D", "POSTROUTING", "-o", vpn_ifname,
1048 "-j", "MASQUERADE", "-w"}) != 0)
1049 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001050 if (!ModifyRedirectDnsJumpRule("-D"))
1051 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001052}
1053
Hugo Benichi76be34a2020-08-26 22:35:54 +09001054bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
1055 const std::string& op,
Hugo Benichi8c526e92021-03-25 14:59:59 +09001056 const std::string& oif,
1057 Fwmark routing_mark) {
1058 return ModifyConnmarkSet(family, "POSTROUTING", op, oif, routing_mark,
1059 kFwmarkRoutingMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001060}
1061
1062bool Datapath::ModifyConnmarkSet(IpFamily family,
1063 const std::string& chain,
1064 const std::string& op,
1065 const std::string& oif,
1066 Fwmark mark,
1067 Fwmark mask) {
1068 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
1069 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
1070 return false;
1071 }
1072
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001073 std::vector<std::string> args = {op, chain};
1074 if (!oif.empty()) {
1075 args.push_back("-o");
1076 args.push_back(oif);
1077 }
1078 args.push_back("-j");
1079 args.push_back("CONNMARK");
1080 args.push_back("--set-mark");
1081 args.push_back(mark.ToString() + "/" + mask.ToString());
1082 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +09001083
Hugo Benichi58f264a2020-10-16 18:16:05 +09001084 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +09001085}
1086
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001087bool Datapath::ModifyConnmarkRestore(IpFamily family,
1088 const std::string& chain,
1089 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001090 const std::string& iif,
1091 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001092 std::vector<std::string> args = {op, chain};
1093 if (!iif.empty()) {
1094 args.push_back("-i");
1095 args.push_back(iif);
1096 }
1097 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001098 mask.ToString(), "-w"});
1099 return ModifyIptables(family, "mangle", args);
1100}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001101
Hugo Benichi1af52392020-11-27 18:09:32 +09001102bool Datapath::ModifyConnmarkSave(IpFamily family,
1103 const std::string& chain,
1104 const std::string& op,
1105 const std::string& oif,
1106 Fwmark mask) {
1107 std::vector<std::string> args = {op, chain};
1108 if (!oif.empty()) {
1109 args.push_back("-o");
1110 args.push_back(oif);
1111 }
1112 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
1113 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +09001114 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001115}
1116
Hugo Benichi2a940542020-10-26 18:50:49 +09001117bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1118 const std::string& op,
Hugo Benichi8c526e92021-03-25 14:59:59 +09001119 Fwmark routing_mark,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001120 const std::string& int_ifname) {
Hugo Benichi2a940542020-10-26 18:50:49 +09001121 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi8c526e92021-03-25 14:59:59 +09001122 0 /*classid*/, routing_mark, kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001123}
1124
Hugo Benichi9be19b12020-08-14 15:33:40 +09001125bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
1126 const std::string& iif,
1127 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001128 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001129 0 /*classid*/, Fwmark::FromSource(source),
1130 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001131}
1132
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001133bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1134 TrafficSource source) {
1135 std::vector<std::string> args = {"-A",
1136 kApplyLocalSourceMarkChain,
1137 "-m",
1138 "mark",
1139 "--mark",
1140 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1141 "-j",
1142 "MARK",
1143 "--set-mark",
1144 Fwmark::FromSource(source).ToString() + "/" +
1145 kFwmarkAllSourcesMask.ToString(),
1146 "-w"};
1147 return ModifyIptables(IpFamily::Dual, "mangle", args);
1148}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001149
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001150bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1151 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001152 if (std::string(source.uid_name).empty() && source.classid == 0)
1153 return false;
1154
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001155 Fwmark mark = Fwmark::FromSource(source.source_type);
1156 if (source.is_on_vpn)
1157 mark = mark | kFwmarkRouteOnVpn;
1158
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001159 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1160 "" /*iif*/, source.uid_name, source.classid, mark,
1161 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001162}
1163
1164bool Datapath::ModifyFwmark(IpFamily family,
1165 const std::string& chain,
1166 const std::string& op,
1167 const std::string& iif,
1168 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001169 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001170 Fwmark mark,
1171 Fwmark mask,
1172 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001173 std::vector<std::string> args = {op, chain};
1174 if (!iif.empty()) {
1175 args.push_back("-i");
1176 args.push_back(iif);
1177 }
1178 if (!uid_name.empty()) {
1179 args.push_back("-m");
1180 args.push_back("owner");
1181 args.push_back("--uid-owner");
1182 args.push_back(uid_name);
1183 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001184 if (classid != 0) {
1185 args.push_back("-m");
1186 args.push_back("cgroup");
1187 args.push_back("--cgroup");
1188 args.push_back(base::StringPrintf("0x%08x", classid));
1189 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001190 args.push_back("-j");
1191 args.push_back("MARK");
1192 args.push_back("--set-mark");
1193 args.push_back(mark.ToString() + "/" + mask.ToString());
1194 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001195
Hugo Benichi58f264a2020-10-16 18:16:05 +09001196 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001197}
1198
Hugo Benichid82d8832020-08-14 10:05:03 +09001199bool Datapath::ModifyIpForwarding(IpFamily family,
1200 const std::string& op,
1201 const std::string& iif,
1202 const std::string& oif,
1203 bool log_failures) {
1204 if (iif.empty() && oif.empty()) {
1205 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1206 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001207 return false;
1208 }
1209
Hugo Benichid82d8832020-08-14 10:05:03 +09001210 std::vector<std::string> args = {op, "FORWARD"};
1211 if (!iif.empty()) {
1212 args.push_back("-i");
1213 args.push_back(iif);
1214 }
1215 if (!oif.empty()) {
1216 args.push_back("-o");
1217 args.push_back(oif);
1218 }
1219 args.push_back("-j");
1220 args.push_back("ACCEPT");
1221 args.push_back("-w");
1222
Hugo Benichi58f264a2020-10-16 18:16:05 +09001223 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001224}
1225
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001226bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1227 const std::string& op,
1228 const std::string& iif,
1229 Fwmark mark,
1230 Fwmark mask) {
1231 std::vector<std::string> args = {op, chain};
1232 if (!iif.empty()) {
1233 args.push_back("-i");
1234 args.push_back(iif);
1235 }
1236 if (mark.Value() != 0 && mask.Value() != 0) {
1237 args.push_back("-m");
1238 args.push_back("mark");
1239 args.push_back("--mark");
1240 args.push_back(mark.ToString() + "/" + mask.ToString());
1241 }
1242 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1243 return ModifyIptables(IpFamily::Dual, "mangle", args);
1244}
1245
Hugo Benichif0f55562021-04-02 15:25:02 +09001246bool Datapath::AddChain(IpFamily family,
1247 const std::string& table,
1248 const std::string& name) {
1249 DCHECK(name.size() <= kIptablesMaxChainLength);
1250 return ModifyChain(family, table, "-N", name);
1251}
1252
1253bool Datapath::RemoveChain(IpFamily family,
1254 const std::string& table,
1255 const std::string& name) {
1256 return ModifyChain(family, table, "-X", name);
1257}
1258
1259bool Datapath::FlushChain(IpFamily family,
1260 const std::string& table,
1261 const std::string& name) {
1262 return ModifyChain(family, table, "-F", name);
1263}
1264
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001265bool Datapath::ModifyChain(IpFamily family,
1266 const std::string& table,
1267 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001268 const std::string& chain,
1269 bool log_failures) {
1270 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001271}
1272
1273bool Datapath::ModifyIptables(IpFamily family,
1274 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001275 const std::vector<std::string>& argv,
1276 bool log_failures) {
1277 switch (family) {
1278 case IPv4:
1279 case IPv6:
1280 case Dual:
1281 break;
1282 default:
1283 LOG(ERROR) << "Could not execute iptables command " << table
1284 << base::JoinString(argv, " ") << ": incorrect IP family "
1285 << family;
1286 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001287 }
1288
1289 bool success = true;
1290 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001291 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001292 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001293 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001294 return success;
1295}
1296
Hugo Benichid82d8832020-08-14 10:05:03 +09001297bool Datapath::StartIpForwarding(IpFamily family,
1298 const std::string& iif,
1299 const std::string& oif) {
1300 return ModifyIpForwarding(family, "-A", iif, oif);
1301}
1302
1303bool Datapath::StopIpForwarding(IpFamily family,
1304 const std::string& iif,
1305 const std::string& oif) {
1306 return ModifyIpForwarding(family, "-D", iif, oif);
1307}
1308
1309bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1310 const std::string& ifname2) {
1311 // Only start Ipv6 forwarding if -C returns false and it had not been
1312 // started yet.
1313 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1314 false /*log_failures*/) &&
1315 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1316 return false;
1317 }
1318
1319 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1320 false /*log_failures*/) &&
1321 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001322 RemoveIPv6Forwarding(ifname1, ifname2);
1323 return false;
1324 }
1325
1326 return true;
1327}
1328
1329void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1330 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001331 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1332 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001333}
1334
Garrick Evans3d97a392020-02-21 15:24:37 +09001335bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1336 uint32_t addr,
1337 uint32_t netmask) {
1338 struct rtentry route;
1339 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001340 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1341 SetSockaddrIn(&route.rt_dst, addr & netmask);
1342 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001343 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001344 return ModifyRtentry(SIOCADDRT, &route);
1345}
Garrick Evans3d97a392020-02-21 15:24:37 +09001346
Hugo Benichie8758b52020-04-03 14:49:01 +09001347bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1348 uint32_t addr,
1349 uint32_t netmask) {
1350 struct rtentry route;
1351 memset(&route, 0, sizeof(route));
1352 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1353 SetSockaddrIn(&route.rt_dst, addr & netmask);
1354 SetSockaddrIn(&route.rt_genmask, netmask);
1355 route.rt_flags = RTF_UP | RTF_GATEWAY;
1356 return ModifyRtentry(SIOCDELRT, &route);
1357}
1358
1359bool Datapath::AddIPv4Route(const std::string& ifname,
1360 uint32_t addr,
1361 uint32_t netmask) {
1362 struct rtentry route;
1363 memset(&route, 0, sizeof(route));
1364 SetSockaddrIn(&route.rt_dst, addr & netmask);
1365 SetSockaddrIn(&route.rt_genmask, netmask);
1366 char rt_dev[IFNAMSIZ];
1367 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1368 rt_dev[IFNAMSIZ - 1] = '\0';
1369 route.rt_dev = rt_dev;
1370 route.rt_flags = RTF_UP | RTF_GATEWAY;
1371 return ModifyRtentry(SIOCADDRT, &route);
1372}
1373
1374bool Datapath::DeleteIPv4Route(const std::string& ifname,
1375 uint32_t addr,
1376 uint32_t netmask) {
1377 struct rtentry route;
1378 memset(&route, 0, sizeof(route));
1379 SetSockaddrIn(&route.rt_dst, addr & netmask);
1380 SetSockaddrIn(&route.rt_genmask, netmask);
1381 char rt_dev[IFNAMSIZ];
1382 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1383 rt_dev[IFNAMSIZ - 1] = '\0';
1384 route.rt_dev = rt_dev;
1385 route.rt_flags = RTF_UP | RTF_GATEWAY;
1386 return ModifyRtentry(SIOCDELRT, &route);
1387}
1388
Taoyu Lia0727dc2020-09-24 19:54:59 +09001389bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001390 DCHECK(route);
1391 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001392 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001393 return false;
1394 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001395 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1396 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001397 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001398 return false;
1399 }
1400 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1401 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001402 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001403 return false;
1404 }
1405 return true;
1406}
1407
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001408bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1409 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1410 kArcAddr, kAdbServerPort, ifname,
1411 kLocalhostAddr, kAdbProxyTcpListenPort);
1412}
1413
1414void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1415 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1416 kArcAddr, kAdbServerPort, ifname,
1417 kLocalhostAddr, kAdbProxyTcpListenPort);
1418}
1419
1420bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1421 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1422 kAdbProxyTcpListenPort, ifname);
1423}
1424
1425void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1426 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1427 kAdbProxyTcpListenPort, ifname);
1428}
1429
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001430void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1431 if_nametoindex_[ifname] = ifindex;
1432}
1433
1434int Datapath::FindIfIndex(const std::string& ifname) {
1435 uint32_t ifindex = if_nametoindex(ifname.c_str());
1436 if (ifindex > 0) {
1437 if_nametoindex_[ifname] = ifindex;
1438 return ifindex;
1439 }
1440
1441 const auto it = if_nametoindex_.find(ifname);
1442 if (it != if_nametoindex_.end())
1443 return it->second;
1444
1445 return 0;
1446}
1447
Hugo Benichi8c526e92021-03-25 14:59:59 +09001448Fwmark Datapath::CachedRoutingFwmark(const std::string& ifname) {
1449 const auto it = if_nametoindex_.find(ifname);
1450 if (it != if_nametoindex_.end())
1451 return Fwmark::FromIfIndex(it->second);
1452
1453 LOG(WARNING) << "No interface index known for " << ifname;
1454 return Fwmark();
1455}
1456
Hugo Benichifcf81022020-12-04 11:01:37 +09001457std::ostream& operator<<(std::ostream& stream,
1458 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001459 stream << "{ pid: " << nsinfo.pid
1460 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001461 if (!nsinfo.outbound_ifname.empty()) {
1462 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1463 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001464 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1465 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001466 << ", peer_ifname: " << nsinfo.peer_ifname
1467 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1468 return stream;
1469}
1470
Garrick Evans3388a032020-03-24 11:25:55 +09001471} // namespace patchpanel