blob: a02109c9017a03cc60dc115a6e276c40e9984289 [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 Benichi1e0656f2021-02-15 15:43:38 +090053constexpr char kDropGuestIpv4PrefixChain[] = "drop_guest_ipv4_prefix";
54constexpr char kRedirectDnsChain[] = "redirect_dns";
Hugo Benichi2a940542020-10-26 18:50:49 +090055
Hugo Benichif0f55562021-04-02 15:25:02 +090056// Maximum length of an iptables chain name.
57constexpr int kIptablesMaxChainLength = 28;
58
Garrick Evans8a067562020-05-11 12:47:30 +090059std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
60 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090061 if (n.length() < IFNAMSIZ)
62 return n;
Garrick Evans54861622019-07-19 09:05:09 +090063
Garrick Evans2f581a02020-05-11 10:43:35 +090064 // Best effort attempt to preserve the interface number, assuming it's the
65 // last char in the name.
66 auto c = ifname[ifname.length() - 1];
67 n.resize(IFNAMSIZ - 1);
68 n[n.length() - 1] = c;
69 return n;
Garrick Evans54861622019-07-19 09:05:09 +090070}
Garrick Evansf0ab7132019-06-18 14:50:42 +090071
Hugo Benichiaba7e2e2021-02-22 14:47:11 +090072bool Ioctl(ioctl_t ioctl_h, unsigned long req, const char* arg) {
73 base::ScopedFD control_fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
74 if (!control_fd.is_valid()) {
75 PLOG(ERROR) << "Failed to create control socket for ioctl request=" << req;
76 return false;
77 }
78 if ((*ioctl_h)(control_fd.get(), req, arg) != 0) {
79 PLOG(ERROR) << "ioctl request=" << req << " failed";
80 return false;
81 }
82 return true;
83}
84
Garrick Evans8a067562020-05-11 12:47:30 +090085} // namespace
86
87std::string ArcVethHostName(const std::string& ifname) {
88 return PrefixIfname("veth", ifname);
89}
90
91std::string ArcBridgeName(const std::string& ifname) {
92 return PrefixIfname("arc_", ifname);
93}
94
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090095Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
96 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090097
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090098Datapath::Datapath(MinijailedProcessRunner* process_runner,
99 Firewall* firewall,
100 ioctl_t ioctl_hook)
101 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900102 CHECK(process_runner_);
103}
104
Garrick Evans260ff302019-07-25 11:22:50 +0900105MinijailedProcessRunner& Datapath::runner() const {
106 return *process_runner_;
107}
108
Hugo Benichibf811c62020-09-07 17:30:45 +0900109void Datapath::Start() {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900110 // Restart from a clean iptables state in case of an unordered shutdown.
111 ResetIptables();
112
Hugo Benichibf811c62020-09-07 17:30:45 +0900113 // Enable IPv4 packet forwarding
114 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
115 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
116 << " Guest connectivity will not work correctly.";
117
118 // Limit local port range: Android owns 47104-61000.
119 // TODO(garrick): The original history behind this tweak is gone. Some
120 // investigation is needed to see if it is still applicable.
121 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
122 "32768 47103") != 0)
123 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
124 << " apps may not work correctly.";
125
126 // Enable IPv6 packet forwarding
127 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
128 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
129 << " IPv6 functionality may be broken.";
130
Hugo Benichi58125d32020-09-09 11:25:45 +0900131 // Create a FORWARD ACCEPT rule for connections already established.
132 if (process_runner_->iptables(
133 "filter", {"-A", "FORWARD", "-m", "state", "--state",
134 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900135 LOG(ERROR) << "Failed to install forwarding rule for established"
136 << " connections.";
137
Hugo Benichiac799a82021-03-25 00:16:16 +0900138 // Create a FORWARD rule for accepting any ARC originated traffic regardless
139 // of the output interface. This enables for ARC certain multihoming
140 // scenarios (b/182594063).
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900141 if (!ModifyJumpRule(IpFamily::IPv4, "filter", "-A", "FORWARD", "ACCEPT",
142 "arc+", "" /*oif*/))
Hugo Benichiac799a82021-03-25 00:16:16 +0900143 LOG(ERROR) << "Failed to install forwarding rule for ARC traffic";
144
Hugo Benichibf811c62020-09-07 17:30:45 +0900145 // chromium:898210: Drop any locally originated traffic that would exit a
146 // physical interface with a source IPv4 address from the subnet of IPs used
147 // for VMs, containers, and connected namespaces This is needed to prevent
148 // packets leaking with an incorrect src IP when a local process binds to the
149 // wrong interface.
Hugo Benichif0f55562021-04-02 15:25:02 +0900150 if (!AddChain(IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain))
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900151 LOG(ERROR) << "Failed to create " << kDropGuestIpv4PrefixChain
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900152 << " filter chain";
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900153 if (!ModifyJumpRule(IpFamily::IPv4, "filter", "-I", "OUTPUT",
154 kDropGuestIpv4PrefixChain, "" /*iif*/, "" /*oif*/))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900155 LOG(ERROR) << "Failed to set up jump rule from filter OUTPUT to "
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900156 << kDropGuestIpv4PrefixChain;
Hugo Benichibf811c62020-09-07 17:30:45 +0900157 for (const auto& oif : kPhysicalIfnamePrefixes) {
158 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
159 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
160 << kGuestIPv4Subnet << " exiting " << oif;
161 }
162
Hugo Benichi561fae42021-01-22 15:28:40 +0900163 // Set static SNAT rules for any IPv4 traffic originated from a guest (ARC,
164 // Crostini, ...) or a connected namespace.
165 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
166 // need to be explicitly dropped as SNAT cannot be applied to them.
167 if (process_runner_->iptables(
168 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
169 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0)
170 LOG(ERROR) << "Failed to install SNAT mark rules.";
171 if (process_runner_->iptables(
172 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
173 "MASQUERADE", "-w"}) != 0)
174 LOG(ERROR) << "Failed to install SNAT mark rules.";
Hugo Benichibf811c62020-09-07 17:30:45 +0900175 if (!AddOutboundIPv4SNATMark("vmtap+"))
Hugo Benichi561fae42021-01-22 15:28:40 +0900176 LOG(ERROR) << "Failed to set up NAT for TAP devices.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900177
Hugo Benichi2a940542020-10-26 18:50:49 +0900178 // Applies the routing tag saved in conntrack for any established connection
179 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900180 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
181 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900182 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
183
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900184 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
185 // tag and tagging the local traffic that should be routed through a VPN.
Hugo Benichif0f55562021-04-02 15:25:02 +0900186 if (!AddChain(IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900187 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
188 << " mangle chain";
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900189 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "OUTPUT",
190 kApplyLocalSourceMarkChain, "" /*iif*/, "" /*oif*/))
191
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900192 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
193 << " to mangle OUTPUT";
194 // Create rules for tagging local sources with the source tag and the vpn
195 // policy tag.
196 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900197 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900198 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
199 << " in " << kApplyLocalSourceMarkChain;
200 }
201 // Finally add a catch-all rule for tagging any remaining local sources with
202 // the SYSTEM source tag
203 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
204 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
205
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900206 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
207 // traffic that should be routed through a VPN.
Hugo Benichif0f55562021-04-02 15:25:02 +0900208 if (!AddChain(IpFamily::Dual, "mangle", kApplyVpnMarkChain))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900209 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900210 // All local outgoing traffic eligible to VPN routing should traverse the VPN
211 // marking chain.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900212 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", kFwmarkRouteOnVpn,
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900213 kFwmarkVpnMask))
214 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
215 // Any traffic that already has a routing tag applied is accepted.
216 if (!ModifyIptables(
217 IpFamily::Dual, "mangle",
218 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
219 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
220 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
221 "connections";
Hugo Benichi155de002021-01-19 16:45:46 +0900222
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900223 // b/178331695 Sets up a nat chain used in OUTPUT for redirecting DNS queries
224 // of system services. When a VPN is connected, a query routed through a
225 // physical network is redirected to the primary nameserver of that network.
Hugo Benichif0f55562021-04-02 15:25:02 +0900226 if (!AddChain(IpFamily::IPv4, "nat", kRedirectDnsChain))
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900227 LOG(ERROR) << "Failed to set up " << kRedirectDnsChain << " nat chain";
228
Hugo Benichi52a64992021-01-28 17:47:33 +0900229 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
230 // incorrectly cause neighbor discovery icmpv6 packets to be dropped. Add
231 // these rules to bypass connmark rule for those packets.
232 for (const auto& type : kNeighborDiscoveryTypes) {
233 if (!ModifyIptables(IpFamily::IPv6, "mangle",
234 {"-I", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
235 "-j", "ACCEPT", "-w"}))
236 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
237 << " packets in OUTPUT";
Hugo Benichi52a64992021-01-28 17:47:33 +0900238 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900239}
240
241void Datapath::Stop() {
Hugo Benichibf811c62020-09-07 17:30:45 +0900242 // Restore original local port range.
243 // TODO(garrick): The original history behind this tweak is gone. Some
244 // investigation is needed to see if it is still applicable.
245 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
246 "32768 61000") != 0)
247 LOG(ERROR) << "Failed to restore local port range";
248
249 // Disable packet forwarding
250 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
251 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
252
253 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
254 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900255
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900256 ResetIptables();
257}
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900258
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900259void Datapath::ResetIptables() {
260 // If it exists, remove jump rules from a built-in chain to a custom routing
261 // or tagging chain.
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900262 ModifyJumpRule(IpFamily::IPv4, "filter", "-D", "OUTPUT",
263 kDropGuestIpv4PrefixChain, "" /*iif*/, "" /*oif*/,
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900264 false /*log_failures*/);
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900265
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900266 // Flush chains used for routing and fwmark tagging. Also delete additional
267 // chains made by patchpanel. Chains used by permission broker (nat
268 // PREROUTING, filter INPUT) and chains used for traffic counters (mangle
269 // {rx,tx}_{<iface>, vpn}) are not flushed.
270 static struct {
271 IpFamily family;
272 std::string table;
273 std::string chain;
274 bool should_delete;
275 } resetOps[] = {
276 {IpFamily::Dual, "filter", "FORWARD", false},
277 {IpFamily::Dual, "mangle", "FORWARD", false},
278 {IpFamily::Dual, "mangle", "INPUT", false},
279 {IpFamily::Dual, "mangle", "OUTPUT", false},
280 {IpFamily::Dual, "mangle", "POSTROUTING", false},
281 {IpFamily::Dual, "mangle", "PREROUTING", false},
282 {IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain, true},
283 {IpFamily::Dual, "mangle", kApplyVpnMarkChain, true},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900284 {IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain, true},
285 {IpFamily::IPv4, "nat", kRedirectDnsChain, true},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900286 {IpFamily::IPv4, "nat", "POSTROUTING", false},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900287 {IpFamily::IPv4, "nat", "OUTPUT", false},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900288 };
289 for (const auto& op : resetOps) {
290 // Chains to delete are custom chains and will not exist the first time
291 // patchpanel starts after boot. Skip flushing and delete these chains if
292 // they do not exist to avoid logging spurious error messages.
293 if (op.should_delete && !ModifyChain(op.family, op.table, "-L", op.chain,
294 false /*log_failures*/))
295 continue;
Hugo Benichi155de002021-01-19 16:45:46 +0900296
Hugo Benichif0f55562021-04-02 15:25:02 +0900297 if (!FlushChain(op.family, op.table, op.chain))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900298 LOG(ERROR) << "Failed to flush " << op.chain << " chain in table "
299 << op.table;
Hugo Benichi2a940542020-10-26 18:50:49 +0900300
Hugo Benichif0f55562021-04-02 15:25:02 +0900301 if (op.should_delete && !RemoveChain(op.family, op.table, op.chain))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900302 LOG(ERROR) << "Failed to delete " << op.chain << " chain in table "
303 << op.table;
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900304 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900305}
306
Hugo Benichi33860d72020-07-09 16:34:01 +0900307bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
308 // Try first to delete any netns with name |netns_name| in case patchpanel
309 // did not exit cleanly.
310 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
311 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
312 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
313}
314
315bool Datapath::NetnsDeleteName(const std::string& netns_name) {
316 return process_runner_->ip_netns_delete(netns_name) == 0;
317}
318
Garrick Evans8a949dc2019-07-18 16:17:53 +0900319bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900320 uint32_t ipv4_addr,
321 uint32_t ipv4_prefix_len) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900322 if (!Ioctl(ioctl_, SIOCBRADDBR, ifname.c_str())) {
323 LOG(ERROR) << "Failed to create bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900324 return false;
325 }
326
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900327 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900328 if (process_runner_->ip(
329 "addr", "add",
330 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
331 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
332 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900333 RemoveBridge(ifname);
334 return false;
335 }
336
337 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900338 RemoveBridge(ifname);
339 return false;
340 }
341
342 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900343 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900344 RemoveBridge(ifname);
345 return false;
346 }
347
348 return true;
349}
350
351void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900352 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900353 process_runner_->ip("link", "set", {ifname, "down"});
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900354 if (!Ioctl(ioctl_, SIOCBRDELBR, ifname.c_str()))
355 LOG(ERROR) << "Failed to destroy bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900356}
357
Garrick Evans621ed262019-11-13 12:28:43 +0900358bool Datapath::AddToBridge(const std::string& br_ifname,
359 const std::string& ifname) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900360 struct ifreq ifr;
361 memset(&ifr, 0, sizeof(ifr));
362 strncpy(ifr.ifr_name, br_ifname.c_str(), sizeof(ifr.ifr_name));
363 ifr.ifr_ifindex = FindIfIndex(ifname);
364
365 if (!Ioctl(ioctl_, SIOCBRADDIF, reinterpret_cast<const char*>(&ifr))) {
366 LOG(ERROR) << "Failed to add " << ifname << " to bridge " << br_ifname;
367 return false;
368 }
369
370 return true;
Garrick Evans621ed262019-11-13 12:28:43 +0900371}
372
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900373std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900374 const MacAddress* mac_addr,
375 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900376 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900377 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
378 if (!dev.is_valid()) {
379 PLOG(ERROR) << "Failed to open " << kTunDev;
380 return "";
381 }
382
383 struct ifreq ifr;
384 memset(&ifr, 0, sizeof(ifr));
385 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
386 sizeof(ifr.ifr_name));
387 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
388
389 // If a template was given as the name, ifr_name will be updated with the
390 // actual interface name.
391 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900392 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900393 return "";
394 }
395 const char* ifname = ifr.ifr_name;
396
397 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900398 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900399 return "";
400 }
401
Garrick Evans4f9f5572019-11-26 10:25:16 +0900402 if (!user.empty()) {
403 uid_t uid = -1;
404 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
405 PLOG(ERROR) << "Unable to look up UID for " << user;
406 RemoveTAP(ifname);
407 return "";
408 }
409 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
410 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
411 << ifname;
412 RemoveTAP(ifname);
413 return "";
414 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900415 }
416
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900417 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900418 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
419 if (!sock.is_valid()) {
420 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900421 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900422 RemoveTAP(ifname);
423 return "";
424 }
425
Garrick Evans621ed262019-11-13 12:28:43 +0900426 if (ipv4_addr) {
427 struct sockaddr_in* addr =
428 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
429 addr->sin_family = AF_INET;
430 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
431 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
432 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
433 << " {" << ipv4_addr->ToCidrString() << "}";
434 RemoveTAP(ifname);
435 return "";
436 }
437
438 struct sockaddr_in* netmask =
439 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
440 netmask->sin_family = AF_INET;
441 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
442 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
443 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
444 << " {" << ipv4_addr->ToCidrString() << "}";
445 RemoveTAP(ifname);
446 return "";
447 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900448 }
449
Garrick Evans621ed262019-11-13 12:28:43 +0900450 if (mac_addr) {
451 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
452 hwaddr->sa_family = ARPHRD_ETHER;
453 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
454 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
455 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
456 << " {" << MacAddressToString(*mac_addr) << "}";
457 RemoveTAP(ifname);
458 return "";
459 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900460 }
461
462 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900463 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900464 RemoveTAP(ifname);
465 return "";
466 }
467
468 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
469 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900470 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900471 RemoveTAP(ifname);
472 return "";
473 }
474
475 return ifname;
476}
477
478void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900479 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900480}
481
Hugo Benichi33860d72020-07-09 16:34:01 +0900482bool Datapath::ConnectVethPair(pid_t netns_pid,
483 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900484 const std::string& veth_ifname,
485 const std::string& peer_ifname,
486 const MacAddress& remote_mac_addr,
487 uint32_t remote_ipv4_addr,
488 uint32_t remote_ipv4_prefix_len,
489 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900490 // Set up the virtual pair across the current namespace and |netns_name|.
491 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
492 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
493 << peer_ifname;
494 return false;
495 }
496
497 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900498 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900499 ScopedNS ns(netns_pid, ScopedNS::Type::Network);
Hugo Benichi33860d72020-07-09 16:34:01 +0900500 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900501 LOG(ERROR)
502 << "Cannot create virtual link -- invalid container namespace?";
503 return false;
504 }
505
Hugo Benichi76675592020-04-08 14:29:57 +0900506 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
507 remote_ipv4_prefix_len, true /* link up */,
508 remote_multicast_flag)) {
509 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
510 RemoveInterface(peer_ifname);
511 return false;
512 }
513 }
514
Hugo Benichi76675592020-04-08 14:29:57 +0900515 if (!ToggleInterface(veth_ifname, true /*up*/)) {
516 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
517 RemoveInterface(veth_ifname);
518 return false;
519 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900520
Hugo Benichi76675592020-04-08 14:29:57 +0900521 return true;
522}
523
Hugo Benichi33860d72020-07-09 16:34:01 +0900524bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
525 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900526 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900527 return process_runner_->ip("link", "add",
528 {veth_ifname, "type", "veth", "peer", "name",
529 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900530}
Garrick Evans54861622019-07-19 09:05:09 +0900531
Garrick Evans2470caa2020-03-04 14:15:41 +0900532bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
533 const std::string link = up ? "up" : "down";
534 return process_runner_->ip("link", "set", {ifname, link}) == 0;
535}
Garrick Evans54861622019-07-19 09:05:09 +0900536
Garrick Evans2470caa2020-03-04 14:15:41 +0900537bool Datapath::ConfigureInterface(const std::string& ifname,
538 const MacAddress& mac_addr,
539 uint32_t ipv4_addr,
540 uint32_t ipv4_prefix_len,
541 bool up,
542 bool enable_multicast) {
543 const std::string link = up ? "up" : "down";
544 const std::string multicast = enable_multicast ? "on" : "off";
545 return (process_runner_->ip(
546 "addr", "add",
547 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
548 IPv4AddressToString(
549 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
550 "dev", ifname}) == 0) &&
551 (process_runner_->ip("link", "set",
552 {
553 "dev",
554 ifname,
555 link,
556 "addr",
557 MacAddressToString(mac_addr),
558 "multicast",
559 multicast,
560 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900561}
562
563void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900564 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900565}
566
Hugo Benichi321f23b2020-09-25 15:42:05 +0900567bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
568 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900569 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900570 "filter", {"-I", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
571 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900572}
573
574bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
575 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900576 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900577 "filter", {"-D", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
578 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900579}
580
Hugo Benichifcf81022020-12-04 11:01:37 +0900581bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900582 // Veth interface configuration and client routing configuration:
583 // - attach a name to the client namespace.
584 // - create veth pair across the current namespace and the client namespace.
585 // - configure IPv4 address on remote veth inside client namespace.
586 // - configure IPv4 address on local veth inside host namespace.
587 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900588 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
589 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
590 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900591 return false;
592 }
593
Hugo Benichifcf81022020-12-04 11:01:37 +0900594 if (!ConnectVethPair(
595 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
596 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
597 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900598 LOG(ERROR) << "Failed to create veth pair for"
599 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900600 << nsinfo.pid;
601 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900602 return false;
603 }
604
Hugo Benichifcf81022020-12-04 11:01:37 +0900605 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
606 nsinfo.peer_subnet->AddressAtOffset(0),
607 nsinfo.peer_subnet->PrefixLength(),
608 true /* link up */, false /* enable_multicast */)) {
609 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
610 RemoveInterface(nsinfo.host_ifname);
611 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900612 return false;
613 }
614
615 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900616 ScopedNS ns(nsinfo.pid, ScopedNS::Type::Network);
Hugo Benichifcf81022020-12-04 11:01:37 +0900617 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
618 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
619 RemoveInterface(nsinfo.host_ifname);
620 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900621 return false;
622 }
623
Hugo Benichifcf81022020-12-04 11:01:37 +0900624 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
625 INADDR_ANY)) {
626 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
627 << " inside namespace pid " << nsinfo.pid;
628 RemoveInterface(nsinfo.host_ifname);
629 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900630 return false;
631 }
632 }
633
634 // Host namespace routing configuration
635 // - ingress: add route to client subnet via |host_ifname|.
636 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
637 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
638 // Note that by default unsolicited ingress traffic is not forwarded to the
639 // client namespace unless the client specifically set port forwarding
640 // through permission_broker DBus APIs.
641 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
642 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900643 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
644 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
645 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900646 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900647 RemoveInterface(nsinfo.host_ifname);
648 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900649 return false;
650 }
651
Hugo Benichi7c342672020-09-08 09:18:14 +0900652 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900653 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900654 LOG(ERROR) << "Failed to set SNAT for traffic"
655 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900656 << nsinfo.host_ifname;
657 RemoveInterface(nsinfo.host_ifname);
658 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
659 nsinfo.peer_subnet->BaseAddress(), netmask);
660 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
661 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900662 return false;
663 }
664
Hugo Benichi93306e52020-12-04 16:08:00 +0900665 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
666 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
667 nsinfo.route_on_vpn);
668
Hugo Benichi7c342672020-09-08 09:18:14 +0900669 return true;
670}
671
Hugo Benichifcf81022020-12-04 11:01:37 +0900672void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900673 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
674 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
675 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900676 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900677 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
678 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
679 nsinfo.peer_subnet->BaseAddress(),
680 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
681 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900682}
683
Hugo Benichi8d622b52020-08-13 15:24:12 +0900684void Datapath::StartRoutingDevice(const std::string& ext_ifname,
685 const std::string& int_ifname,
686 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900687 TrafficSource source,
688 bool route_on_vpn) {
689 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900690 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900691 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
692 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
693 << "->" << int_ifname;
694
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900695 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900696 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
697 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900698
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900699 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900700 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
701 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900702
Hugo Benichid872d3d2021-03-29 10:20:53 +0900703 std::string subchain = "PREROUTING_" + int_ifname;
704 // This can fail if patchpanel did not stopped correctly or failed to cleanup
705 // the chain when |int_ifname| was previously deleted.
706 if (!AddChain(IpFamily::Dual, "mangle", subchain))
707 LOG(ERROR) << "Failed to create mangle chain " << subchain;
708 // Make sure the chain is empty if patchpanel did not cleaned correctly that
709 // chain before.
710 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
711 LOG(ERROR) << "Could not flush " << subchain;
712 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "PREROUTING", subchain,
713 int_ifname, "" /*oif*/))
714 LOG(ERROR) << "Could not add jump rule from mangle PREROUTING to "
715 << subchain;
716 if (!ModifyFwmarkSourceTag(subchain, "-A", source))
717 LOG(ERROR) << "Failed to add fwmark tagging rule for source " << source
718 << " in " << subchain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900719
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900720 if (!ext_ifname.empty()) {
721 // If |ext_ifname| is not null, mark egress traffic with the
722 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900723 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900724 if (ifindex == 0) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900725 LOG(ERROR) << "Failed to retrieve interface index of " << ext_ifname;
Hugo Benichid872d3d2021-03-29 10:20:53 +0900726 return;
Hugo Benichi8c526e92021-03-25 14:59:59 +0900727 }
Hugo Benichid872d3d2021-03-29 10:20:53 +0900728 if (!ModifyFwmarkRoutingTag(subchain, "-A", Fwmark::FromIfIndex(ifindex)))
729 LOG(ERROR) << "Failed to add fwmark routing tag for " << ext_ifname
730 << "<-" << int_ifname << " in " << subchain;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900731 } else {
732 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
733 // PREROUTING to apply any fwmark routing tag saved for the current
734 // connection, and rely on implicit routing to the default logical network
735 // otherwise.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900736 if (!ModifyConnmarkRestore(IpFamily::Dual, subchain, "-A", "" /*iif*/,
Hugo Benichi1af52392020-11-27 18:09:32 +0900737 kFwmarkRoutingMask))
Hugo Benichid872d3d2021-03-29 10:20:53 +0900738 LOG(ERROR) << "Failed to add CONNMARK restore rule in " << subchain;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900739
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900740 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900741 // default network is eligible to be routed through a VPN if |route_on_vpn|
742 // is true.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900743 if (route_on_vpn && !ModifyFwmarkVpnJumpRule(subchain, "-A", {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900744 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900745 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900746}
747
748void Datapath::StopRoutingDevice(const std::string& ext_ifname,
749 const std::string& int_ifname,
750 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900751 TrafficSource source,
752 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900753 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900754 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900755 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
756 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900757
758 std::string subchain = "PREROUTING_" + int_ifname;
759 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "PREROUTING", subchain,
760 int_ifname, "" /*oif*/);
761 FlushChain(IpFamily::Dual, "mangle", subchain);
762 RemoveChain(IpFamily::Dual, "mangle", subchain);
Hugo Benichi8d622b52020-08-13 15:24:12 +0900763}
764
Garrick Evansf0ab7132019-06-18 14:50:42 +0900765bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
766 const std::string& ipv4_addr) {
767 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900768 if (process_runner_->iptables(
769 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
770 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900771 return false;
772
773 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900774 if (process_runner_->iptables(
775 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
776 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900777 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
778 return false;
779 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900780 if (process_runner_->iptables(
781 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
782 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900783 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
784 return false;
785 }
786
787 return true;
788}
789
790void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
791 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900792 process_runner_->iptables(
793 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
794 "--to-destination", ipv4_addr, "-w"});
795 process_runner_->iptables(
796 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
797 "--to-destination", ipv4_addr, "-w"});
798 process_runner_->iptables(
799 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
800 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900801}
802
Hugo Benichid872d3d2021-03-29 10:20:53 +0900803// TODO(b/161060333) Migrate this rule to the PREROUTING_<iface> subchains
Hugo Benichie8758b52020-04-03 14:49:01 +0900804bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
805 return process_runner_->iptables(
806 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900807 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900808}
809
810void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
811 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900812 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900813}
814
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900815bool Datapath::AddRedirectDnsRule(const std::string& ifname,
816 const std::string dns_ipv4_addr) {
817 bool success = true;
818 success &= RemoveRedirectDnsRule(ifname);
819 // Use Insert operation to ensure that the new DNS address is used first.
820 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
821 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
822 physical_dns_addresses_[ifname] = dns_ipv4_addr;
823 return success;
824}
825
826bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
827 const auto it = physical_dns_addresses_.find(ifname);
828 if (it == physical_dns_addresses_.end())
829 return true;
830
831 bool success = true;
832 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
833 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
834 physical_dns_addresses_.erase(it);
835 return success;
836}
837
838bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
839 const std::string& protocol,
840 const std::string& ifname,
841 const std::string& dns_ipv4_addr) {
842 std::vector<std::string> args = {op,
843 kRedirectDnsChain,
844 "-p",
845 protocol,
846 "--dport",
847 "53",
848 "-o",
849 ifname,
850 "-j",
851 "DNAT",
852 "--to-destination",
853 dns_ipv4_addr,
854 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900855 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900856}
857
858bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
859 std::vector<std::string> args = {
860 op,
861 "OUTPUT",
862 "-m",
863 "mark",
864 "!",
865 "--mark",
866 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
867 "-j",
868 kRedirectDnsChain,
869 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900870 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900871}
872
Garrick Evans664a82f2019-12-17 12:18:05 +0900873bool Datapath::MaskInterfaceFlags(const std::string& ifname,
874 uint16_t on,
875 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900876 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
877 if (!sock.is_valid()) {
878 PLOG(ERROR) << "Failed to create control socket";
879 return false;
880 }
881 ifreq ifr;
882 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
883 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
884 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
885 return false;
886 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900887 ifr.ifr_flags |= on;
888 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900889 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900890 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
891 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900892 return false;
893 }
894 return true;
895}
896
Garrick Evans260ff302019-07-25 11:22:50 +0900897bool Datapath::AddIPv6HostRoute(const std::string& ifname,
898 const std::string& ipv6_addr,
899 int ipv6_prefix_len) {
900 std::string ipv6_addr_cidr =
901 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
902
Garrick Evans8e8e3472020-01-23 14:03:50 +0900903 return process_runner_->ip6("route", "replace",
904 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900905}
906
907void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
908 const std::string& ipv6_addr,
909 int ipv6_prefix_len) {
910 std::string ipv6_addr_cidr =
911 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
912
Garrick Evans8e8e3472020-01-23 14:03:50 +0900913 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900914}
915
Taoyu Lia0727dc2020-09-24 19:54:59 +0900916bool Datapath::AddIPv6Address(const std::string& ifname,
917 const std::string& ipv6_addr) {
918 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900919}
920
Taoyu Lia0727dc2020-09-24 19:54:59 +0900921void Datapath::RemoveIPv6Address(const std::string& ifname,
922 const std::string& ipv6_addr) {
923 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900924}
925
Hugo Benichi76be34a2020-08-26 22:35:54 +0900926void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900927 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +0900928 if (ifindex == 0) {
929 // Can happen if the interface has already been removed (b/183679000).
930 LOG(ERROR) << "Failed to set up connection pinning on " << ext_ifname;
931 return;
932 }
933
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900934 std::string subchain = "POSTROUTING_" + ext_ifname;
935 // This can fail if patchpanel did not stopped correctly or failed to cleanup
936 // the chain when |ext_ifname| was previously deleted.
937 if (!AddChain(IpFamily::Dual, "mangle", subchain))
938 LOG(ERROR) << "Failed to create mangle chain " << subchain;
939 // Make sure the chain is empty if patchpanel did not cleaned correctly that
940 // chain before.
941 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
942 LOG(ERROR) << "Could not flush " << subchain;
943 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "POSTROUTING", subchain,
944 "" /*iif*/, ext_ifname))
945 LOG(ERROR) << "Could not add jump rule from mangle POSTROUTING to "
946 << subchain;
947
Hugo Benichi8c526e92021-03-25 14:59:59 +0900948 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
949 LOG(INFO) << "Start connection pinning on " << ext_ifname
950 << " fwmark=" << routing_mark.ToString();
Hugo Benichi1af52392020-11-27 18:09:32 +0900951 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900952 if (!ModifyConnmarkSet(IpFamily::Dual, subchain, "-A", routing_mark,
953 kFwmarkRoutingMask))
Hugo Benichi76be34a2020-08-26 22:35:54 +0900954 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900955 // Save in CONNMARK the source tag for egress traffic of this connection.
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900956 if (!ModifyConnmarkSave(IpFamily::Dual, subchain, "-A",
Hugo Benichi1af52392020-11-27 18:09:32 +0900957 kFwmarkAllSourcesMask))
958 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
959 "source tag on "
960 << ext_ifname;
961 // Restore from CONNMARK the source tag for ingress traffic of this connection
962 // (returned traffic).
963 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
964 kFwmarkAllSourcesMask))
965 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
966 "traffic received on "
967 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900968}
969
970void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900971 std::string subchain = "POSTROUTING_" + ext_ifname;
972 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "POSTROUTING", subchain,
973 "" /*iif*/, ext_ifname);
974 FlushChain(IpFamily::Dual, "mangle", subchain);
975 RemoveChain(IpFamily::Dual, "mangle", subchain);
976 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
977 kFwmarkAllSourcesMask))
978 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
979 "traffic received on "
980 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900981}
982
Hugo Benichi2a940542020-10-26 18:50:49 +0900983void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900984 int ifindex = FindIfIndex(vpn_ifname);
985 if (ifindex == 0) {
986 // Can happen if the interface has already been removed (b/183679000).
987 LOG(ERROR) << "Failed to start VPN routing on " << vpn_ifname;
988 return;
989 }
990
991 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
992 LOG(INFO) << "Start VPN routing on " << vpn_ifname
993 << " fwmark=" << routing_mark.ToString();
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900994 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-A", "POSTROUTING", "MASQUERADE",
995 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +0900996 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900997 StartConnectionPinning(vpn_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900998 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", routing_mark))
Hugo Benichi2a940542020-10-26 18:50:49 +0900999 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +09001000 if (vpn_ifname != kArcBridge)
1001 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
1002 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001003 if (!ModifyRedirectDnsJumpRule("-A"))
1004 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001005}
1006
1007void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +09001008 Fwmark routing_mark = CachedRoutingFwmark(vpn_ifname);
1009 LOG(INFO) << "Stop VPN routing on " << vpn_ifname
1010 << " fwmark=" << routing_mark.ToString();
Hugo Benichibfc49112020-12-14 12:54:44 +09001011 if (vpn_ifname != kArcBridge)
1012 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
1013 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichid872d3d2021-03-29 10:20:53 +09001014 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", routing_mark))
Hugo Benichi2a940542020-10-26 18:50:49 +09001015 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
1016 StopConnectionPinning(vpn_ifname);
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001017 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-D", "POSTROUTING", "MASQUERADE",
1018 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +09001019 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001020 if (!ModifyRedirectDnsJumpRule("-D"))
1021 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001022}
1023
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001024bool Datapath::ModifyConnmarkSet(IpFamily family,
1025 const std::string& chain,
1026 const std::string& op,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001027 Fwmark mark,
1028 Fwmark mask) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +09001029 return ModifyIptables(family, "mangle",
1030 {op, chain, "-j", "CONNMARK", "--set-mark",
1031 mark.ToString() + "/" + mask.ToString(), "-w"});
Hugo Benichi76be34a2020-08-26 22:35:54 +09001032}
1033
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001034bool Datapath::ModifyConnmarkRestore(IpFamily family,
1035 const std::string& chain,
1036 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001037 const std::string& iif,
1038 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001039 std::vector<std::string> args = {op, chain};
1040 if (!iif.empty()) {
1041 args.push_back("-i");
1042 args.push_back(iif);
1043 }
1044 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001045 mask.ToString(), "-w"});
1046 return ModifyIptables(family, "mangle", args);
1047}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001048
Hugo Benichi1af52392020-11-27 18:09:32 +09001049bool Datapath::ModifyConnmarkSave(IpFamily family,
1050 const std::string& chain,
1051 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001052 Fwmark mask) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +09001053 std::vector<std::string> args = {
1054 op, chain, "-j", "CONNMARK", "--save-mark",
1055 "--mask", mask.ToString(), "-w"};
Hugo Benichi58f264a2020-10-16 18:16:05 +09001056 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001057}
1058
Hugo Benichi2a940542020-10-26 18:50:49 +09001059bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1060 const std::string& op,
Hugo Benichid872d3d2021-03-29 10:20:53 +09001061 Fwmark routing_mark) {
1062 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*int_ifname*/,
1063 "" /*uid_name*/, 0 /*classid*/, routing_mark,
1064 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001065}
1066
Hugo Benichid872d3d2021-03-29 10:20:53 +09001067bool Datapath::ModifyFwmarkSourceTag(const std::string& chain,
1068 const std::string& op,
Hugo Benichi9be19b12020-08-14 15:33:40 +09001069 TrafficSource source) {
Hugo Benichid872d3d2021-03-29 10:20:53 +09001070 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*iif*/, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001071 0 /*classid*/, Fwmark::FromSource(source),
1072 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001073}
1074
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001075bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1076 TrafficSource source) {
1077 std::vector<std::string> args = {"-A",
1078 kApplyLocalSourceMarkChain,
1079 "-m",
1080 "mark",
1081 "--mark",
1082 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1083 "-j",
1084 "MARK",
1085 "--set-mark",
1086 Fwmark::FromSource(source).ToString() + "/" +
1087 kFwmarkAllSourcesMask.ToString(),
1088 "-w"};
1089 return ModifyIptables(IpFamily::Dual, "mangle", args);
1090}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001091
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001092bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1093 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001094 if (std::string(source.uid_name).empty() && source.classid == 0)
1095 return false;
1096
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001097 Fwmark mark = Fwmark::FromSource(source.source_type);
1098 if (source.is_on_vpn)
1099 mark = mark | kFwmarkRouteOnVpn;
1100
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001101 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1102 "" /*iif*/, source.uid_name, source.classid, mark,
1103 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001104}
1105
1106bool Datapath::ModifyFwmark(IpFamily family,
1107 const std::string& chain,
1108 const std::string& op,
1109 const std::string& iif,
1110 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001111 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001112 Fwmark mark,
1113 Fwmark mask,
1114 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001115 std::vector<std::string> args = {op, chain};
1116 if (!iif.empty()) {
1117 args.push_back("-i");
1118 args.push_back(iif);
1119 }
1120 if (!uid_name.empty()) {
1121 args.push_back("-m");
1122 args.push_back("owner");
1123 args.push_back("--uid-owner");
1124 args.push_back(uid_name);
1125 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001126 if (classid != 0) {
1127 args.push_back("-m");
1128 args.push_back("cgroup");
1129 args.push_back("--cgroup");
1130 args.push_back(base::StringPrintf("0x%08x", classid));
1131 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001132 args.push_back("-j");
1133 args.push_back("MARK");
1134 args.push_back("--set-mark");
1135 args.push_back(mark.ToString() + "/" + mask.ToString());
1136 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001137
Hugo Benichi58f264a2020-10-16 18:16:05 +09001138 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001139}
1140
Hugo Benichid82d8832020-08-14 10:05:03 +09001141bool Datapath::ModifyIpForwarding(IpFamily family,
1142 const std::string& op,
1143 const std::string& iif,
1144 const std::string& oif,
1145 bool log_failures) {
1146 if (iif.empty() && oif.empty()) {
1147 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1148 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001149 return false;
1150 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001151 return ModifyJumpRule(family, "filter", op, "FORWARD", "ACCEPT", iif, oif,
1152 log_failures);
1153}
Garrick Evans260ff302019-07-25 11:22:50 +09001154
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001155bool Datapath::ModifyJumpRule(IpFamily family,
1156 const std::string& table,
1157 const std::string& op,
1158 const std::string& chain,
1159 const std::string& target,
1160 const std::string& iif,
1161 const std::string& oif,
1162 bool log_failures) {
1163 std::vector<std::string> args = {op, chain};
Hugo Benichid82d8832020-08-14 10:05:03 +09001164 if (!iif.empty()) {
1165 args.push_back("-i");
1166 args.push_back(iif);
1167 }
1168 if (!oif.empty()) {
1169 args.push_back("-o");
1170 args.push_back(oif);
1171 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001172 args.insert(args.end(), {"-j", target, "-w"});
1173 return ModifyIptables(family, table, args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001174}
1175
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001176bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1177 const std::string& op,
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001178 Fwmark mark,
1179 Fwmark mask) {
1180 std::vector<std::string> args = {op, chain};
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001181 if (mark.Value() != 0 && mask.Value() != 0) {
1182 args.push_back("-m");
1183 args.push_back("mark");
1184 args.push_back("--mark");
1185 args.push_back(mark.ToString() + "/" + mask.ToString());
1186 }
1187 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1188 return ModifyIptables(IpFamily::Dual, "mangle", args);
1189}
1190
Hugo Benichif0f55562021-04-02 15:25:02 +09001191bool Datapath::AddChain(IpFamily family,
1192 const std::string& table,
1193 const std::string& name) {
1194 DCHECK(name.size() <= kIptablesMaxChainLength);
1195 return ModifyChain(family, table, "-N", name);
1196}
1197
1198bool Datapath::RemoveChain(IpFamily family,
1199 const std::string& table,
1200 const std::string& name) {
1201 return ModifyChain(family, table, "-X", name);
1202}
1203
1204bool Datapath::FlushChain(IpFamily family,
1205 const std::string& table,
1206 const std::string& name) {
1207 return ModifyChain(family, table, "-F", name);
1208}
1209
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001210bool Datapath::ModifyChain(IpFamily family,
1211 const std::string& table,
1212 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001213 const std::string& chain,
1214 bool log_failures) {
1215 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001216}
1217
1218bool Datapath::ModifyIptables(IpFamily family,
1219 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001220 const std::vector<std::string>& argv,
1221 bool log_failures) {
1222 switch (family) {
1223 case IPv4:
1224 case IPv6:
1225 case Dual:
1226 break;
1227 default:
1228 LOG(ERROR) << "Could not execute iptables command " << table
1229 << base::JoinString(argv, " ") << ": incorrect IP family "
1230 << family;
1231 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001232 }
1233
1234 bool success = true;
1235 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001236 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001237 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001238 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001239 return success;
1240}
1241
Hugo Benichid82d8832020-08-14 10:05:03 +09001242bool Datapath::StartIpForwarding(IpFamily family,
1243 const std::string& iif,
1244 const std::string& oif) {
1245 return ModifyIpForwarding(family, "-A", iif, oif);
1246}
1247
1248bool Datapath::StopIpForwarding(IpFamily family,
1249 const std::string& iif,
1250 const std::string& oif) {
1251 return ModifyIpForwarding(family, "-D", iif, oif);
1252}
1253
1254bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1255 const std::string& ifname2) {
1256 // Only start Ipv6 forwarding if -C returns false and it had not been
1257 // started yet.
1258 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1259 false /*log_failures*/) &&
1260 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1261 return false;
1262 }
1263
1264 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1265 false /*log_failures*/) &&
1266 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001267 RemoveIPv6Forwarding(ifname1, ifname2);
1268 return false;
1269 }
1270
1271 return true;
1272}
1273
1274void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1275 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001276 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1277 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001278}
1279
Garrick Evans3d97a392020-02-21 15:24:37 +09001280bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1281 uint32_t addr,
1282 uint32_t netmask) {
1283 struct rtentry route;
1284 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001285 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1286 SetSockaddrIn(&route.rt_dst, addr & netmask);
1287 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001288 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001289 return ModifyRtentry(SIOCADDRT, &route);
1290}
Garrick Evans3d97a392020-02-21 15:24:37 +09001291
Hugo Benichie8758b52020-04-03 14:49:01 +09001292bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1293 uint32_t addr,
1294 uint32_t netmask) {
1295 struct rtentry route;
1296 memset(&route, 0, sizeof(route));
1297 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1298 SetSockaddrIn(&route.rt_dst, addr & netmask);
1299 SetSockaddrIn(&route.rt_genmask, netmask);
1300 route.rt_flags = RTF_UP | RTF_GATEWAY;
1301 return ModifyRtentry(SIOCDELRT, &route);
1302}
1303
1304bool Datapath::AddIPv4Route(const std::string& ifname,
1305 uint32_t addr,
1306 uint32_t netmask) {
1307 struct rtentry route;
1308 memset(&route, 0, sizeof(route));
1309 SetSockaddrIn(&route.rt_dst, addr & netmask);
1310 SetSockaddrIn(&route.rt_genmask, netmask);
1311 char rt_dev[IFNAMSIZ];
1312 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1313 rt_dev[IFNAMSIZ - 1] = '\0';
1314 route.rt_dev = rt_dev;
1315 route.rt_flags = RTF_UP | RTF_GATEWAY;
1316 return ModifyRtentry(SIOCADDRT, &route);
1317}
1318
1319bool Datapath::DeleteIPv4Route(const std::string& ifname,
1320 uint32_t addr,
1321 uint32_t netmask) {
1322 struct rtentry route;
1323 memset(&route, 0, sizeof(route));
1324 SetSockaddrIn(&route.rt_dst, addr & netmask);
1325 SetSockaddrIn(&route.rt_genmask, netmask);
1326 char rt_dev[IFNAMSIZ];
1327 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1328 rt_dev[IFNAMSIZ - 1] = '\0';
1329 route.rt_dev = rt_dev;
1330 route.rt_flags = RTF_UP | RTF_GATEWAY;
1331 return ModifyRtentry(SIOCDELRT, &route);
1332}
1333
Taoyu Lia0727dc2020-09-24 19:54:59 +09001334bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001335 DCHECK(route);
1336 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001337 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001338 return false;
1339 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001340 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1341 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001342 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001343 return false;
1344 }
1345 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1346 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001347 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001348 return false;
1349 }
1350 return true;
1351}
1352
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001353bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1354 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1355 kArcAddr, kAdbServerPort, ifname,
1356 kLocalhostAddr, kAdbProxyTcpListenPort);
1357}
1358
1359void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1360 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1361 kArcAddr, kAdbServerPort, ifname,
1362 kLocalhostAddr, kAdbProxyTcpListenPort);
1363}
1364
1365bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1366 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1367 kAdbProxyTcpListenPort, ifname);
1368}
1369
1370void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1371 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1372 kAdbProxyTcpListenPort, ifname);
1373}
1374
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001375void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1376 if_nametoindex_[ifname] = ifindex;
1377}
1378
1379int Datapath::FindIfIndex(const std::string& ifname) {
1380 uint32_t ifindex = if_nametoindex(ifname.c_str());
1381 if (ifindex > 0) {
1382 if_nametoindex_[ifname] = ifindex;
1383 return ifindex;
1384 }
1385
1386 const auto it = if_nametoindex_.find(ifname);
1387 if (it != if_nametoindex_.end())
1388 return it->second;
1389
1390 return 0;
1391}
1392
Hugo Benichi8c526e92021-03-25 14:59:59 +09001393Fwmark Datapath::CachedRoutingFwmark(const std::string& ifname) {
1394 const auto it = if_nametoindex_.find(ifname);
1395 if (it != if_nametoindex_.end())
1396 return Fwmark::FromIfIndex(it->second);
1397
1398 LOG(WARNING) << "No interface index known for " << ifname;
1399 return Fwmark();
1400}
1401
Hugo Benichifcf81022020-12-04 11:01:37 +09001402std::ostream& operator<<(std::ostream& stream,
1403 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001404 stream << "{ pid: " << nsinfo.pid
1405 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001406 if (!nsinfo.outbound_ifname.empty()) {
1407 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1408 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001409 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1410 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001411 << ", peer_ifname: " << nsinfo.peer_ifname
1412 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1413 return stream;
1414}
1415
Garrick Evans3388a032020-03-24 11:25:55 +09001416} // namespace patchpanel