blob: 99b5fb13d43be4445e5a9194003a270dfeefba13 [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";
Hugo Benichi155de002021-01-19 16:45:46 +0900215
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900216 // b/178331695 Sets up a nat chain used in OUTPUT for redirecting DNS queries
217 // of system services. When a VPN is connected, a query routed through a
218 // physical network is redirected to the primary nameserver of that network.
Hugo Benichif0f55562021-04-02 15:25:02 +0900219 if (!AddChain(IpFamily::IPv4, "nat", kRedirectDnsChain))
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900220 LOG(ERROR) << "Failed to set up " << kRedirectDnsChain << " nat chain";
221
Hugo Benichi52a64992021-01-28 17:47:33 +0900222 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
223 // incorrectly cause neighbor discovery icmpv6 packets to be dropped. Add
224 // these rules to bypass connmark rule for those packets.
225 for (const auto& type : kNeighborDiscoveryTypes) {
226 if (!ModifyIptables(IpFamily::IPv6, "mangle",
227 {"-I", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
228 "-j", "ACCEPT", "-w"}))
229 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
230 << " packets in OUTPUT";
Hugo Benichi52a64992021-01-28 17:47:33 +0900231 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900232}
233
234void Datapath::Stop() {
Hugo Benichibf811c62020-09-07 17:30:45 +0900235 // Restore original local port range.
236 // TODO(garrick): The original history behind this tweak is gone. Some
237 // investigation is needed to see if it is still applicable.
238 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
239 "32768 61000") != 0)
240 LOG(ERROR) << "Failed to restore local port range";
241
242 // Disable packet forwarding
243 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
244 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
245
246 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
247 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900248
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900249 ResetIptables();
250}
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900251
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900252void Datapath::ResetIptables() {
253 // If it exists, remove jump rules from a built-in chain to a custom routing
254 // or tagging chain.
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900255 ModifyJumpRule(IpFamily::IPv4, "filter", "-D", "OUTPUT",
256 kDropGuestIpv4PrefixChain, "" /*iif*/, "" /*oif*/,
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900257 false /*log_failures*/);
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900258
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900259 // Flush chains used for routing and fwmark tagging. Also delete additional
260 // chains made by patchpanel. Chains used by permission broker (nat
261 // PREROUTING, filter INPUT) and chains used for traffic counters (mangle
262 // {rx,tx}_{<iface>, vpn}) are not flushed.
263 static struct {
264 IpFamily family;
265 std::string table;
266 std::string chain;
267 bool should_delete;
268 } resetOps[] = {
269 {IpFamily::Dual, "filter", "FORWARD", false},
270 {IpFamily::Dual, "mangle", "FORWARD", false},
271 {IpFamily::Dual, "mangle", "INPUT", false},
272 {IpFamily::Dual, "mangle", "OUTPUT", false},
273 {IpFamily::Dual, "mangle", "POSTROUTING", false},
274 {IpFamily::Dual, "mangle", "PREROUTING", false},
275 {IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain, true},
276 {IpFamily::Dual, "mangle", kApplyVpnMarkChain, true},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900277 {IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain, true},
278 {IpFamily::IPv4, "nat", kRedirectDnsChain, true},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900279 {IpFamily::IPv4, "nat", "POSTROUTING", false},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900280 {IpFamily::IPv4, "nat", "OUTPUT", false},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900281 };
282 for (const auto& op : resetOps) {
283 // Chains to delete are custom chains and will not exist the first time
284 // patchpanel starts after boot. Skip flushing and delete these chains if
285 // they do not exist to avoid logging spurious error messages.
286 if (op.should_delete && !ModifyChain(op.family, op.table, "-L", op.chain,
287 false /*log_failures*/))
288 continue;
Hugo Benichi155de002021-01-19 16:45:46 +0900289
Hugo Benichif0f55562021-04-02 15:25:02 +0900290 if (!FlushChain(op.family, op.table, op.chain))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900291 LOG(ERROR) << "Failed to flush " << op.chain << " chain in table "
292 << op.table;
Hugo Benichi2a940542020-10-26 18:50:49 +0900293
Hugo Benichif0f55562021-04-02 15:25:02 +0900294 if (op.should_delete && !RemoveChain(op.family, op.table, op.chain))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900295 LOG(ERROR) << "Failed to delete " << op.chain << " chain in table "
296 << op.table;
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900297 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900298}
299
Hugo Benichi33860d72020-07-09 16:34:01 +0900300bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
301 // Try first to delete any netns with name |netns_name| in case patchpanel
302 // did not exit cleanly.
303 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
304 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
305 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
306}
307
308bool Datapath::NetnsDeleteName(const std::string& netns_name) {
309 return process_runner_->ip_netns_delete(netns_name) == 0;
310}
311
Garrick Evans8a949dc2019-07-18 16:17:53 +0900312bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900313 uint32_t ipv4_addr,
314 uint32_t ipv4_prefix_len) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900315 if (!Ioctl(ioctl_, SIOCBRADDBR, ifname.c_str())) {
316 LOG(ERROR) << "Failed to create bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900317 return false;
318 }
319
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900320 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900321 if (process_runner_->ip(
322 "addr", "add",
323 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
324 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
325 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900326 RemoveBridge(ifname);
327 return false;
328 }
329
330 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900331 RemoveBridge(ifname);
332 return false;
333 }
334
335 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900336 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900337 RemoveBridge(ifname);
338 return false;
339 }
340
341 return true;
342}
343
344void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900345 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900346 process_runner_->ip("link", "set", {ifname, "down"});
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900347 if (!Ioctl(ioctl_, SIOCBRDELBR, ifname.c_str()))
348 LOG(ERROR) << "Failed to destroy bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900349}
350
Garrick Evans621ed262019-11-13 12:28:43 +0900351bool Datapath::AddToBridge(const std::string& br_ifname,
352 const std::string& ifname) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900353 struct ifreq ifr;
354 memset(&ifr, 0, sizeof(ifr));
355 strncpy(ifr.ifr_name, br_ifname.c_str(), sizeof(ifr.ifr_name));
356 ifr.ifr_ifindex = FindIfIndex(ifname);
357
358 if (!Ioctl(ioctl_, SIOCBRADDIF, reinterpret_cast<const char*>(&ifr))) {
359 LOG(ERROR) << "Failed to add " << ifname << " to bridge " << br_ifname;
360 return false;
361 }
362
363 return true;
Garrick Evans621ed262019-11-13 12:28:43 +0900364}
365
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900366std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900367 const MacAddress* mac_addr,
368 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900369 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900370 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
371 if (!dev.is_valid()) {
372 PLOG(ERROR) << "Failed to open " << kTunDev;
373 return "";
374 }
375
376 struct ifreq ifr;
377 memset(&ifr, 0, sizeof(ifr));
378 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
379 sizeof(ifr.ifr_name));
380 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
381
382 // If a template was given as the name, ifr_name will be updated with the
383 // actual interface name.
384 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900385 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900386 return "";
387 }
388 const char* ifname = ifr.ifr_name;
389
390 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900391 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900392 return "";
393 }
394
Garrick Evans4f9f5572019-11-26 10:25:16 +0900395 if (!user.empty()) {
396 uid_t uid = -1;
397 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
398 PLOG(ERROR) << "Unable to look up UID for " << user;
399 RemoveTAP(ifname);
400 return "";
401 }
402 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
403 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
404 << ifname;
405 RemoveTAP(ifname);
406 return "";
407 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900408 }
409
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900410 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900411 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
412 if (!sock.is_valid()) {
413 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900414 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900415 RemoveTAP(ifname);
416 return "";
417 }
418
Garrick Evans621ed262019-11-13 12:28:43 +0900419 if (ipv4_addr) {
420 struct sockaddr_in* addr =
421 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
422 addr->sin_family = AF_INET;
423 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
424 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
425 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
426 << " {" << ipv4_addr->ToCidrString() << "}";
427 RemoveTAP(ifname);
428 return "";
429 }
430
431 struct sockaddr_in* netmask =
432 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
433 netmask->sin_family = AF_INET;
434 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
435 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
436 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
437 << " {" << ipv4_addr->ToCidrString() << "}";
438 RemoveTAP(ifname);
439 return "";
440 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900441 }
442
Garrick Evans621ed262019-11-13 12:28:43 +0900443 if (mac_addr) {
444 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
445 hwaddr->sa_family = ARPHRD_ETHER;
446 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
447 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
448 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
449 << " {" << MacAddressToString(*mac_addr) << "}";
450 RemoveTAP(ifname);
451 return "";
452 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900453 }
454
455 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900456 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900457 RemoveTAP(ifname);
458 return "";
459 }
460
461 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
462 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900463 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900464 RemoveTAP(ifname);
465 return "";
466 }
467
468 return ifname;
469}
470
471void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900472 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900473}
474
Hugo Benichi33860d72020-07-09 16:34:01 +0900475bool Datapath::ConnectVethPair(pid_t netns_pid,
476 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900477 const std::string& veth_ifname,
478 const std::string& peer_ifname,
479 const MacAddress& remote_mac_addr,
480 uint32_t remote_ipv4_addr,
481 uint32_t remote_ipv4_prefix_len,
482 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900483 // Set up the virtual pair across the current namespace and |netns_name|.
484 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
485 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
486 << peer_ifname;
487 return false;
488 }
489
490 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900491 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900492 ScopedNS ns(netns_pid, ScopedNS::Type::Network);
Hugo Benichi33860d72020-07-09 16:34:01 +0900493 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900494 LOG(ERROR)
495 << "Cannot create virtual link -- invalid container namespace?";
496 return false;
497 }
498
Hugo Benichi76675592020-04-08 14:29:57 +0900499 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
500 remote_ipv4_prefix_len, true /* link up */,
501 remote_multicast_flag)) {
502 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
503 RemoveInterface(peer_ifname);
504 return false;
505 }
506 }
507
Hugo Benichi76675592020-04-08 14:29:57 +0900508 if (!ToggleInterface(veth_ifname, true /*up*/)) {
509 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
510 RemoveInterface(veth_ifname);
511 return false;
512 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900513
Hugo Benichi76675592020-04-08 14:29:57 +0900514 return true;
515}
516
Hugo Benichi33860d72020-07-09 16:34:01 +0900517bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
518 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900519 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900520 return process_runner_->ip("link", "add",
521 {veth_ifname, "type", "veth", "peer", "name",
522 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900523}
Garrick Evans54861622019-07-19 09:05:09 +0900524
Garrick Evans2470caa2020-03-04 14:15:41 +0900525bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
526 const std::string link = up ? "up" : "down";
527 return process_runner_->ip("link", "set", {ifname, link}) == 0;
528}
Garrick Evans54861622019-07-19 09:05:09 +0900529
Garrick Evans2470caa2020-03-04 14:15:41 +0900530bool Datapath::ConfigureInterface(const std::string& ifname,
531 const MacAddress& mac_addr,
532 uint32_t ipv4_addr,
533 uint32_t ipv4_prefix_len,
534 bool up,
535 bool enable_multicast) {
536 const std::string link = up ? "up" : "down";
537 const std::string multicast = enable_multicast ? "on" : "off";
538 return (process_runner_->ip(
539 "addr", "add",
540 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
541 IPv4AddressToString(
542 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
543 "dev", ifname}) == 0) &&
544 (process_runner_->ip("link", "set",
545 {
546 "dev",
547 ifname,
548 link,
549 "addr",
550 MacAddressToString(mac_addr),
551 "multicast",
552 multicast,
553 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900554}
555
556void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900557 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900558}
559
Hugo Benichi321f23b2020-09-25 15:42:05 +0900560bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
561 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900562 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900563 "filter", {"-I", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
564 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900565}
566
567bool Datapath::RemoveSourceIPv4DropRule(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", {"-D", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
571 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900572}
573
Hugo Benichifcf81022020-12-04 11:01:37 +0900574bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900575 // Veth interface configuration and client routing configuration:
576 // - attach a name to the client namespace.
577 // - create veth pair across the current namespace and the client namespace.
578 // - configure IPv4 address on remote veth inside client namespace.
579 // - configure IPv4 address on local veth inside host namespace.
580 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900581 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
582 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
583 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900584 return false;
585 }
586
Hugo Benichifcf81022020-12-04 11:01:37 +0900587 if (!ConnectVethPair(
588 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
589 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
590 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900591 LOG(ERROR) << "Failed to create veth pair for"
592 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900593 << nsinfo.pid;
594 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900595 return false;
596 }
597
Hugo Benichifcf81022020-12-04 11:01:37 +0900598 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
599 nsinfo.peer_subnet->AddressAtOffset(0),
600 nsinfo.peer_subnet->PrefixLength(),
601 true /* link up */, false /* enable_multicast */)) {
602 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
603 RemoveInterface(nsinfo.host_ifname);
604 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900605 return false;
606 }
607
608 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900609 ScopedNS ns(nsinfo.pid, ScopedNS::Type::Network);
Hugo Benichifcf81022020-12-04 11:01:37 +0900610 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
611 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
612 RemoveInterface(nsinfo.host_ifname);
613 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900614 return false;
615 }
616
Hugo Benichifcf81022020-12-04 11:01:37 +0900617 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
618 INADDR_ANY)) {
619 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
620 << " inside namespace pid " << nsinfo.pid;
621 RemoveInterface(nsinfo.host_ifname);
622 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900623 return false;
624 }
625 }
626
627 // Host namespace routing configuration
628 // - ingress: add route to client subnet via |host_ifname|.
629 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
630 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
631 // Note that by default unsolicited ingress traffic is not forwarded to the
632 // client namespace unless the client specifically set port forwarding
633 // through permission_broker DBus APIs.
634 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
635 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900636 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
637 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
638 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900639 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900640 RemoveInterface(nsinfo.host_ifname);
641 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900642 return false;
643 }
644
Hugo Benichi7c342672020-09-08 09:18:14 +0900645 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900646 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900647 LOG(ERROR) << "Failed to set SNAT for traffic"
648 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900649 << nsinfo.host_ifname;
650 RemoveInterface(nsinfo.host_ifname);
651 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
652 nsinfo.peer_subnet->BaseAddress(), netmask);
653 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
654 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900655 return false;
656 }
657
Hugo Benichi93306e52020-12-04 16:08:00 +0900658 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
659 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
660 nsinfo.route_on_vpn);
661
Hugo Benichi7c342672020-09-08 09:18:14 +0900662 return true;
663}
664
Hugo Benichifcf81022020-12-04 11:01:37 +0900665void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900666 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
667 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
668 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900669 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900670 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
671 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
672 nsinfo.peer_subnet->BaseAddress(),
673 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
674 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900675}
676
Hugo Benichi8d622b52020-08-13 15:24:12 +0900677void Datapath::StartRoutingDevice(const std::string& ext_ifname,
678 const std::string& int_ifname,
679 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900680 TrafficSource source,
681 bool route_on_vpn) {
682 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900683 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900684 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
685 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
686 << "->" << int_ifname;
687
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900688 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900689 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
690 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900691
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900692 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900693 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
694 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900695
Hugo Benichid872d3d2021-03-29 10:20:53 +0900696 std::string subchain = "PREROUTING_" + int_ifname;
697 // This can fail if patchpanel did not stopped correctly or failed to cleanup
698 // the chain when |int_ifname| was previously deleted.
699 if (!AddChain(IpFamily::Dual, "mangle", subchain))
700 LOG(ERROR) << "Failed to create mangle chain " << subchain;
701 // Make sure the chain is empty if patchpanel did not cleaned correctly that
702 // chain before.
703 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
704 LOG(ERROR) << "Could not flush " << subchain;
705 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "PREROUTING", subchain,
706 int_ifname, "" /*oif*/))
707 LOG(ERROR) << "Could not add jump rule from mangle PREROUTING to "
708 << subchain;
709 if (!ModifyFwmarkSourceTag(subchain, "-A", source))
710 LOG(ERROR) << "Failed to add fwmark tagging rule for source " << source
711 << " in " << subchain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900712
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900713 if (!ext_ifname.empty()) {
714 // If |ext_ifname| is not null, mark egress traffic with the
715 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900716 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900717 if (ifindex == 0) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900718 LOG(ERROR) << "Failed to retrieve interface index of " << ext_ifname;
Hugo Benichid872d3d2021-03-29 10:20:53 +0900719 return;
Hugo Benichi8c526e92021-03-25 14:59:59 +0900720 }
Hugo Benichid872d3d2021-03-29 10:20:53 +0900721 if (!ModifyFwmarkRoutingTag(subchain, "-A", Fwmark::FromIfIndex(ifindex)))
722 LOG(ERROR) << "Failed to add fwmark routing tag for " << ext_ifname
723 << "<-" << int_ifname << " in " << subchain;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900724 } else {
725 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
726 // PREROUTING to apply any fwmark routing tag saved for the current
727 // connection, and rely on implicit routing to the default logical network
728 // otherwise.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900729 if (!ModifyConnmarkRestore(IpFamily::Dual, subchain, "-A", "" /*iif*/,
Hugo Benichi1af52392020-11-27 18:09:32 +0900730 kFwmarkRoutingMask))
Hugo Benichid872d3d2021-03-29 10:20:53 +0900731 LOG(ERROR) << "Failed to add CONNMARK restore rule in " << subchain;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900732
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900733 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900734 // default network is eligible to be routed through a VPN if |route_on_vpn|
735 // is true.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900736 if (route_on_vpn && !ModifyFwmarkVpnJumpRule(subchain, "-A", {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900737 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900738 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900739}
740
741void Datapath::StopRoutingDevice(const std::string& ext_ifname,
742 const std::string& int_ifname,
743 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900744 TrafficSource source,
745 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900746 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900747 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900748 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
749 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900750
751 std::string subchain = "PREROUTING_" + int_ifname;
752 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "PREROUTING", subchain,
753 int_ifname, "" /*oif*/);
754 FlushChain(IpFamily::Dual, "mangle", subchain);
755 RemoveChain(IpFamily::Dual, "mangle", subchain);
Hugo Benichi8d622b52020-08-13 15:24:12 +0900756}
757
Garrick Evansf0ab7132019-06-18 14:50:42 +0900758bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
759 const std::string& ipv4_addr) {
760 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900761 if (process_runner_->iptables(
762 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
763 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900764 return false;
765
766 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900767 if (process_runner_->iptables(
768 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
769 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900770 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
771 return false;
772 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900773 if (process_runner_->iptables(
774 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
775 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900776 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
777 return false;
778 }
779
780 return true;
781}
782
783void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
784 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900785 process_runner_->iptables(
786 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
787 "--to-destination", ipv4_addr, "-w"});
788 process_runner_->iptables(
789 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
790 "--to-destination", ipv4_addr, "-w"});
791 process_runner_->iptables(
792 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
793 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900794}
795
Hugo Benichid872d3d2021-03-29 10:20:53 +0900796// TODO(b/161060333) Migrate this rule to the PREROUTING_<iface> subchains
Hugo Benichie8758b52020-04-03 14:49:01 +0900797bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
798 return process_runner_->iptables(
799 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900800 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900801}
802
803void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
804 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900805 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900806}
807
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900808bool Datapath::AddRedirectDnsRule(const std::string& ifname,
809 const std::string dns_ipv4_addr) {
810 bool success = true;
811 success &= RemoveRedirectDnsRule(ifname);
812 // Use Insert operation to ensure that the new DNS address is used first.
813 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
814 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
815 physical_dns_addresses_[ifname] = dns_ipv4_addr;
816 return success;
817}
818
819bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
820 const auto it = physical_dns_addresses_.find(ifname);
821 if (it == physical_dns_addresses_.end())
822 return true;
823
824 bool success = true;
825 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
826 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
827 physical_dns_addresses_.erase(it);
828 return success;
829}
830
831bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
832 const std::string& protocol,
833 const std::string& ifname,
834 const std::string& dns_ipv4_addr) {
835 std::vector<std::string> args = {op,
836 kRedirectDnsChain,
837 "-p",
838 protocol,
839 "--dport",
840 "53",
841 "-o",
842 ifname,
843 "-j",
844 "DNAT",
845 "--to-destination",
846 dns_ipv4_addr,
847 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900848 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900849}
850
851bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
852 std::vector<std::string> args = {
853 op,
854 "OUTPUT",
855 "-m",
856 "mark",
857 "!",
858 "--mark",
859 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
860 "-j",
861 kRedirectDnsChain,
862 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900863 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900864}
865
Garrick Evans664a82f2019-12-17 12:18:05 +0900866bool Datapath::MaskInterfaceFlags(const std::string& ifname,
867 uint16_t on,
868 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900869 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
870 if (!sock.is_valid()) {
871 PLOG(ERROR) << "Failed to create control socket";
872 return false;
873 }
874 ifreq ifr;
875 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
876 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
877 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
878 return false;
879 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900880 ifr.ifr_flags |= on;
881 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900882 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900883 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
884 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900885 return false;
886 }
887 return true;
888}
889
Garrick Evans260ff302019-07-25 11:22:50 +0900890bool Datapath::AddIPv6HostRoute(const std::string& ifname,
891 const std::string& ipv6_addr,
892 int ipv6_prefix_len) {
893 std::string ipv6_addr_cidr =
894 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
895
Garrick Evans8e8e3472020-01-23 14:03:50 +0900896 return process_runner_->ip6("route", "replace",
897 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900898}
899
900void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
901 const std::string& ipv6_addr,
902 int ipv6_prefix_len) {
903 std::string ipv6_addr_cidr =
904 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
905
Garrick Evans8e8e3472020-01-23 14:03:50 +0900906 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900907}
908
Taoyu Lia0727dc2020-09-24 19:54:59 +0900909bool Datapath::AddIPv6Address(const std::string& ifname,
910 const std::string& ipv6_addr) {
911 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900912}
913
Taoyu Lia0727dc2020-09-24 19:54:59 +0900914void Datapath::RemoveIPv6Address(const std::string& ifname,
915 const std::string& ipv6_addr) {
916 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900917}
918
Hugo Benichi76be34a2020-08-26 22:35:54 +0900919void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900920 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +0900921 if (ifindex == 0) {
922 // Can happen if the interface has already been removed (b/183679000).
923 LOG(ERROR) << "Failed to set up connection pinning on " << ext_ifname;
924 return;
925 }
926
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900927 std::string subchain = "POSTROUTING_" + ext_ifname;
928 // This can fail if patchpanel did not stopped correctly or failed to cleanup
929 // the chain when |ext_ifname| was previously deleted.
930 if (!AddChain(IpFamily::Dual, "mangle", subchain))
931 LOG(ERROR) << "Failed to create mangle chain " << subchain;
932 // Make sure the chain is empty if patchpanel did not cleaned correctly that
933 // chain before.
934 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
935 LOG(ERROR) << "Could not flush " << subchain;
936 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "POSTROUTING", subchain,
937 "" /*iif*/, ext_ifname))
938 LOG(ERROR) << "Could not add jump rule from mangle POSTROUTING to "
939 << subchain;
940
Hugo Benichi8c526e92021-03-25 14:59:59 +0900941 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
942 LOG(INFO) << "Start connection pinning on " << ext_ifname
943 << " fwmark=" << routing_mark.ToString();
Hugo Benichi1af52392020-11-27 18:09:32 +0900944 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900945 if (!ModifyConnmarkSet(IpFamily::Dual, subchain, "-A", routing_mark,
946 kFwmarkRoutingMask))
Hugo Benichi76be34a2020-08-26 22:35:54 +0900947 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900948 // Save in CONNMARK the source tag for egress traffic of this connection.
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900949 if (!ModifyConnmarkSave(IpFamily::Dual, subchain, "-A",
Hugo Benichi1af52392020-11-27 18:09:32 +0900950 kFwmarkAllSourcesMask))
951 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
952 "source tag on "
953 << ext_ifname;
954 // Restore from CONNMARK the source tag for ingress traffic of this connection
955 // (returned traffic).
956 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
957 kFwmarkAllSourcesMask))
958 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
959 "traffic received on "
960 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900961}
962
963void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900964 std::string subchain = "POSTROUTING_" + ext_ifname;
965 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "POSTROUTING", subchain,
966 "" /*iif*/, ext_ifname);
967 FlushChain(IpFamily::Dual, "mangle", subchain);
968 RemoveChain(IpFamily::Dual, "mangle", subchain);
969 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
970 kFwmarkAllSourcesMask))
971 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
972 "traffic received on "
973 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900974}
975
Hugo Benichi2a940542020-10-26 18:50:49 +0900976void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900977 int ifindex = FindIfIndex(vpn_ifname);
978 if (ifindex == 0) {
979 // Can happen if the interface has already been removed (b/183679000).
980 LOG(ERROR) << "Failed to start VPN routing on " << vpn_ifname;
981 return;
982 }
983
984 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
985 LOG(INFO) << "Start VPN routing on " << vpn_ifname
986 << " fwmark=" << routing_mark.ToString();
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900987 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-A", "POSTROUTING", "MASQUERADE",
988 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +0900989 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900990 StartConnectionPinning(vpn_ifname);
Hugo Benichi3540c7f2021-03-29 13:14:42 +0900991
992 // Any traffic that already has a routing tag applied is accepted.
993 if (!ModifyIptables(
994 IpFamily::Dual, "mangle",
995 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
996 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
997 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
998 "connections";
999 // Otherwise, any new traffic from a new connection gets marked with the
1000 // VPN routing tag.
Hugo Benichid872d3d2021-03-29 10:20:53 +09001001 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", routing_mark))
Hugo Benichi2a940542020-10-26 18:50:49 +09001002 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichi3540c7f2021-03-29 13:14:42 +09001003
1004 // When the VPN client runs on the host, also route arcbr0 to that VPN so
1005 // that ARC can access the VPN network through arc0.
Hugo Benichibfc49112020-12-14 12:54:44 +09001006 if (vpn_ifname != kArcBridge)
1007 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
1008 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001009 if (!ModifyRedirectDnsJumpRule("-A"))
1010 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001011}
1012
1013void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi3540c7f2021-03-29 13:14:42 +09001014 LOG(INFO) << "Stop VPN routing on " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +09001015 if (vpn_ifname != kArcBridge)
1016 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
1017 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi3540c7f2021-03-29 13:14:42 +09001018 if (!FlushChain(IpFamily::Dual, "mangle", kApplyVpnMarkChain))
1019 LOG(ERROR) << "Could not flush " << kApplyVpnMarkChain;
1020
Hugo Benichi2a940542020-10-26 18:50:49 +09001021 StopConnectionPinning(vpn_ifname);
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001022 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-D", "POSTROUTING", "MASQUERADE",
1023 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +09001024 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001025 if (!ModifyRedirectDnsJumpRule("-D"))
1026 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001027}
1028
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001029bool Datapath::ModifyConnmarkSet(IpFamily family,
1030 const std::string& chain,
1031 const std::string& op,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001032 Fwmark mark,
1033 Fwmark mask) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +09001034 return ModifyIptables(family, "mangle",
1035 {op, chain, "-j", "CONNMARK", "--set-mark",
1036 mark.ToString() + "/" + mask.ToString(), "-w"});
Hugo Benichi76be34a2020-08-26 22:35:54 +09001037}
1038
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001039bool Datapath::ModifyConnmarkRestore(IpFamily family,
1040 const std::string& chain,
1041 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001042 const std::string& iif,
1043 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001044 std::vector<std::string> args = {op, chain};
1045 if (!iif.empty()) {
1046 args.push_back("-i");
1047 args.push_back(iif);
1048 }
1049 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001050 mask.ToString(), "-w"});
1051 return ModifyIptables(family, "mangle", args);
1052}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001053
Hugo Benichi1af52392020-11-27 18:09:32 +09001054bool Datapath::ModifyConnmarkSave(IpFamily family,
1055 const std::string& chain,
1056 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001057 Fwmark mask) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +09001058 std::vector<std::string> args = {
1059 op, chain, "-j", "CONNMARK", "--save-mark",
1060 "--mask", mask.ToString(), "-w"};
Hugo Benichi58f264a2020-10-16 18:16:05 +09001061 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001062}
1063
Hugo Benichi2a940542020-10-26 18:50:49 +09001064bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1065 const std::string& op,
Hugo Benichid872d3d2021-03-29 10:20:53 +09001066 Fwmark routing_mark) {
1067 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*int_ifname*/,
1068 "" /*uid_name*/, 0 /*classid*/, routing_mark,
1069 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001070}
1071
Hugo Benichid872d3d2021-03-29 10:20:53 +09001072bool Datapath::ModifyFwmarkSourceTag(const std::string& chain,
1073 const std::string& op,
Hugo Benichi9be19b12020-08-14 15:33:40 +09001074 TrafficSource source) {
Hugo Benichid872d3d2021-03-29 10:20:53 +09001075 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*iif*/, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001076 0 /*classid*/, Fwmark::FromSource(source),
1077 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001078}
1079
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001080bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1081 TrafficSource source) {
1082 std::vector<std::string> args = {"-A",
1083 kApplyLocalSourceMarkChain,
1084 "-m",
1085 "mark",
1086 "--mark",
1087 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1088 "-j",
1089 "MARK",
1090 "--set-mark",
1091 Fwmark::FromSource(source).ToString() + "/" +
1092 kFwmarkAllSourcesMask.ToString(),
1093 "-w"};
1094 return ModifyIptables(IpFamily::Dual, "mangle", args);
1095}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001096
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001097bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1098 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001099 if (std::string(source.uid_name).empty() && source.classid == 0)
1100 return false;
1101
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001102 Fwmark mark = Fwmark::FromSource(source.source_type);
1103 if (source.is_on_vpn)
1104 mark = mark | kFwmarkRouteOnVpn;
1105
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001106 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1107 "" /*iif*/, source.uid_name, source.classid, mark,
1108 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001109}
1110
1111bool Datapath::ModifyFwmark(IpFamily family,
1112 const std::string& chain,
1113 const std::string& op,
1114 const std::string& iif,
1115 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001116 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001117 Fwmark mark,
1118 Fwmark mask,
1119 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001120 std::vector<std::string> args = {op, chain};
1121 if (!iif.empty()) {
1122 args.push_back("-i");
1123 args.push_back(iif);
1124 }
1125 if (!uid_name.empty()) {
1126 args.push_back("-m");
1127 args.push_back("owner");
1128 args.push_back("--uid-owner");
1129 args.push_back(uid_name);
1130 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001131 if (classid != 0) {
1132 args.push_back("-m");
1133 args.push_back("cgroup");
1134 args.push_back("--cgroup");
1135 args.push_back(base::StringPrintf("0x%08x", classid));
1136 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001137 args.push_back("-j");
1138 args.push_back("MARK");
1139 args.push_back("--set-mark");
1140 args.push_back(mark.ToString() + "/" + mask.ToString());
1141 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001142
Hugo Benichi58f264a2020-10-16 18:16:05 +09001143 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001144}
1145
Hugo Benichid82d8832020-08-14 10:05:03 +09001146bool Datapath::ModifyIpForwarding(IpFamily family,
1147 const std::string& op,
1148 const std::string& iif,
1149 const std::string& oif,
1150 bool log_failures) {
1151 if (iif.empty() && oif.empty()) {
1152 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1153 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001154 return false;
1155 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001156 return ModifyJumpRule(family, "filter", op, "FORWARD", "ACCEPT", iif, oif,
1157 log_failures);
1158}
Garrick Evans260ff302019-07-25 11:22:50 +09001159
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001160bool Datapath::ModifyJumpRule(IpFamily family,
1161 const std::string& table,
1162 const std::string& op,
1163 const std::string& chain,
1164 const std::string& target,
1165 const std::string& iif,
1166 const std::string& oif,
1167 bool log_failures) {
1168 std::vector<std::string> args = {op, chain};
Hugo Benichid82d8832020-08-14 10:05:03 +09001169 if (!iif.empty()) {
1170 args.push_back("-i");
1171 args.push_back(iif);
1172 }
1173 if (!oif.empty()) {
1174 args.push_back("-o");
1175 args.push_back(oif);
1176 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001177 args.insert(args.end(), {"-j", target, "-w"});
1178 return ModifyIptables(family, table, args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001179}
1180
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001181bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1182 const std::string& op,
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001183 Fwmark mark,
1184 Fwmark mask) {
1185 std::vector<std::string> args = {op, chain};
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001186 if (mark.Value() != 0 && mask.Value() != 0) {
1187 args.push_back("-m");
1188 args.push_back("mark");
1189 args.push_back("--mark");
1190 args.push_back(mark.ToString() + "/" + mask.ToString());
1191 }
1192 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1193 return ModifyIptables(IpFamily::Dual, "mangle", args);
1194}
1195
Hugo Benichif0f55562021-04-02 15:25:02 +09001196bool Datapath::AddChain(IpFamily family,
1197 const std::string& table,
1198 const std::string& name) {
1199 DCHECK(name.size() <= kIptablesMaxChainLength);
1200 return ModifyChain(family, table, "-N", name);
1201}
1202
1203bool Datapath::RemoveChain(IpFamily family,
1204 const std::string& table,
1205 const std::string& name) {
1206 return ModifyChain(family, table, "-X", name);
1207}
1208
1209bool Datapath::FlushChain(IpFamily family,
1210 const std::string& table,
1211 const std::string& name) {
1212 return ModifyChain(family, table, "-F", name);
1213}
1214
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001215bool Datapath::ModifyChain(IpFamily family,
1216 const std::string& table,
1217 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001218 const std::string& chain,
1219 bool log_failures) {
1220 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001221}
1222
1223bool Datapath::ModifyIptables(IpFamily family,
1224 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001225 const std::vector<std::string>& argv,
1226 bool log_failures) {
1227 switch (family) {
1228 case IPv4:
1229 case IPv6:
1230 case Dual:
1231 break;
1232 default:
1233 LOG(ERROR) << "Could not execute iptables command " << table
1234 << base::JoinString(argv, " ") << ": incorrect IP family "
1235 << family;
1236 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001237 }
1238
1239 bool success = true;
1240 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001241 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001242 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001243 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001244 return success;
1245}
1246
Hugo Benichid82d8832020-08-14 10:05:03 +09001247bool Datapath::StartIpForwarding(IpFamily family,
1248 const std::string& iif,
1249 const std::string& oif) {
1250 return ModifyIpForwarding(family, "-A", iif, oif);
1251}
1252
1253bool Datapath::StopIpForwarding(IpFamily family,
1254 const std::string& iif,
1255 const std::string& oif) {
1256 return ModifyIpForwarding(family, "-D", iif, oif);
1257}
1258
1259bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1260 const std::string& ifname2) {
1261 // Only start Ipv6 forwarding if -C returns false and it had not been
1262 // started yet.
1263 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1264 false /*log_failures*/) &&
1265 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1266 return false;
1267 }
1268
1269 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1270 false /*log_failures*/) &&
1271 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001272 RemoveIPv6Forwarding(ifname1, ifname2);
1273 return false;
1274 }
1275
1276 return true;
1277}
1278
1279void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1280 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001281 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1282 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001283}
1284
Garrick Evans3d97a392020-02-21 15:24:37 +09001285bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1286 uint32_t addr,
1287 uint32_t netmask) {
1288 struct rtentry route;
1289 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001290 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1291 SetSockaddrIn(&route.rt_dst, addr & netmask);
1292 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001293 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001294 return ModifyRtentry(SIOCADDRT, &route);
1295}
Garrick Evans3d97a392020-02-21 15:24:37 +09001296
Hugo Benichie8758b52020-04-03 14:49:01 +09001297bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1298 uint32_t addr,
1299 uint32_t netmask) {
1300 struct rtentry route;
1301 memset(&route, 0, sizeof(route));
1302 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1303 SetSockaddrIn(&route.rt_dst, addr & netmask);
1304 SetSockaddrIn(&route.rt_genmask, netmask);
1305 route.rt_flags = RTF_UP | RTF_GATEWAY;
1306 return ModifyRtentry(SIOCDELRT, &route);
1307}
1308
1309bool Datapath::AddIPv4Route(const std::string& ifname,
1310 uint32_t addr,
1311 uint32_t netmask) {
1312 struct rtentry route;
1313 memset(&route, 0, sizeof(route));
1314 SetSockaddrIn(&route.rt_dst, addr & netmask);
1315 SetSockaddrIn(&route.rt_genmask, netmask);
1316 char rt_dev[IFNAMSIZ];
1317 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1318 rt_dev[IFNAMSIZ - 1] = '\0';
1319 route.rt_dev = rt_dev;
1320 route.rt_flags = RTF_UP | RTF_GATEWAY;
1321 return ModifyRtentry(SIOCADDRT, &route);
1322}
1323
1324bool Datapath::DeleteIPv4Route(const std::string& ifname,
1325 uint32_t addr,
1326 uint32_t netmask) {
1327 struct rtentry route;
1328 memset(&route, 0, sizeof(route));
1329 SetSockaddrIn(&route.rt_dst, addr & netmask);
1330 SetSockaddrIn(&route.rt_genmask, netmask);
1331 char rt_dev[IFNAMSIZ];
1332 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1333 rt_dev[IFNAMSIZ - 1] = '\0';
1334 route.rt_dev = rt_dev;
1335 route.rt_flags = RTF_UP | RTF_GATEWAY;
1336 return ModifyRtentry(SIOCDELRT, &route);
1337}
1338
Taoyu Lia0727dc2020-09-24 19:54:59 +09001339bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001340 DCHECK(route);
1341 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001342 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001343 return false;
1344 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001345 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1346 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001347 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001348 return false;
1349 }
1350 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1351 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001352 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001353 return false;
1354 }
1355 return true;
1356}
1357
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001358bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1359 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1360 kArcAddr, kAdbServerPort, ifname,
1361 kLocalhostAddr, kAdbProxyTcpListenPort);
1362}
1363
1364void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1365 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1366 kArcAddr, kAdbServerPort, ifname,
1367 kLocalhostAddr, kAdbProxyTcpListenPort);
1368}
1369
1370bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1371 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1372 kAdbProxyTcpListenPort, ifname);
1373}
1374
1375void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1376 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1377 kAdbProxyTcpListenPort, ifname);
1378}
1379
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001380void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1381 if_nametoindex_[ifname] = ifindex;
1382}
1383
1384int Datapath::FindIfIndex(const std::string& ifname) {
1385 uint32_t ifindex = if_nametoindex(ifname.c_str());
1386 if (ifindex > 0) {
1387 if_nametoindex_[ifname] = ifindex;
1388 return ifindex;
1389 }
1390
1391 const auto it = if_nametoindex_.find(ifname);
1392 if (it != if_nametoindex_.end())
1393 return it->second;
1394
1395 return 0;
1396}
1397
Hugo Benichifcf81022020-12-04 11:01:37 +09001398std::ostream& operator<<(std::ostream& stream,
1399 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001400 stream << "{ pid: " << nsinfo.pid
1401 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001402 if (!nsinfo.outbound_ifname.empty()) {
1403 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1404 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001405 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1406 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001407 << ", peer_ifname: " << nsinfo.peer_ifname
1408 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1409 return stream;
1410}
1411
Garrick Evans3388a032020-03-24 11:25:55 +09001412} // namespace patchpanel