blob: 43046f180c5b7ea588de4ef1224e132a0d77d607 [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
Garrick Evansc7ae82c2019-09-04 16:25:10 +090020#include <base/files/scoped_file.h>
21#include <base/logging.h>
Taoyu Li79871c92020-07-02 16:09:39 +090022#include <base/posix/eintr_wrapper.h>
Garrick Evans54861622019-07-19 09:05:09 +090023#include <base/strings/string_number_conversions.h>
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +090024#include <base/strings/string_util.h>
25#include <base/strings/stringprintf.h>
Garrick Evans4f9f5572019-11-26 10:25:16 +090026#include <brillo/userdb_utils.h>
Garrick Evans54861622019-07-19 09:05:09 +090027
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090028#include "patchpanel/adb_proxy.h"
Hugo Benichibfc49112020-12-14 12:54:44 +090029#include "patchpanel/arc_service.h"
Garrick Evans3388a032020-03-24 11:25:55 +090030#include "patchpanel/net_util.h"
31#include "patchpanel/scoped_ns.h"
Garrick Evansc7ae82c2019-09-04 16:25:10 +090032
Garrick Evans3388a032020-03-24 11:25:55 +090033namespace patchpanel {
Garrick Evans54861622019-07-19 09:05:09 +090034
Garrick Evansc7ae82c2019-09-04 16:25:10 +090035namespace {
Hugo Benichi76675592020-04-08 14:29:57 +090036// TODO(hugobenichi) Consolidate this constant definition in a single place.
37constexpr pid_t kTestPID = -2;
Garrick Evansc7ae82c2019-09-04 16:25:10 +090038constexpr char kDefaultIfname[] = "vmtap%d";
39constexpr char kTunDev[] = "/dev/net/tun";
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090040constexpr char kArcAddr[] = "100.115.92.2";
41constexpr char kLocalhostAddr[] = "127.0.0.1";
42constexpr uint16_t kAdbServerPort = 5555;
Hugo Benichie8758b52020-04-03 14:49:01 +090043
Hugo Benichibf811c62020-09-07 17:30:45 +090044// Constants used for dropping locally originated traffic bound to an incorrect
45// source IPv4 address.
46constexpr char kGuestIPv4Subnet[] = "100.115.92.0/23";
47constexpr std::array<const char*, 6> kPhysicalIfnamePrefixes{
48 {"eth+", "wlan+", "mlan+", "usb+", "wwan+", "rmnet+"}};
49
Hugo Benichi3a9162b2020-09-09 15:47:40 +090050constexpr char kApplyLocalSourceMarkChain[] = "apply_local_source_mark";
Hugo Benichi3ef370b2020-11-16 19:07:17 +090051constexpr char kApplyVpnMarkChain[] = "apply_vpn_mark";
Hugo Benichi155de002021-01-19 16:45:46 +090052constexpr char kCheckRoutingMarkChain[] = "check_routing_mark";
Hugo Benichi3ef370b2020-11-16 19:07:17 +090053
Hugo Benichi2a940542020-10-26 18:50:49 +090054// Constant fwmark mask for matching local socket traffic that should be routed
55// through a VPN connection. The traffic must not be part of an existing
56// connection and must match exactly the VPN routing intent policy bit.
57const Fwmark kFwmarkVpnMatchingMask = kFwmarkRoutingMask | kFwmarkVpnMask;
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
Garrick Evans8a067562020-05-11 12:47:30 +090072} // namespace
73
74std::string ArcVethHostName(const std::string& ifname) {
75 return PrefixIfname("veth", ifname);
76}
77
78std::string ArcBridgeName(const std::string& ifname) {
79 return PrefixIfname("arc_", ifname);
80}
81
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090082Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
83 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090084
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090085Datapath::Datapath(MinijailedProcessRunner* process_runner,
86 Firewall* firewall,
87 ioctl_t ioctl_hook)
88 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +090089 CHECK(process_runner_);
90}
91
Garrick Evans260ff302019-07-25 11:22:50 +090092MinijailedProcessRunner& Datapath::runner() const {
93 return *process_runner_;
94}
95
Hugo Benichibf811c62020-09-07 17:30:45 +090096void Datapath::Start() {
97 // Enable IPv4 packet forwarding
98 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
99 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
100 << " Guest connectivity will not work correctly.";
101
102 // Limit local port range: Android owns 47104-61000.
103 // TODO(garrick): The original history behind this tweak is gone. Some
104 // investigation is needed to see if it is still applicable.
105 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
106 "32768 47103") != 0)
107 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
108 << " apps may not work correctly.";
109
110 // Enable IPv6 packet forwarding
111 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
112 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
113 << " IPv6 functionality may be broken.";
114
115 if (!AddSNATMarkRules())
116 LOG(ERROR) << "Failed to install SNAT mark rules."
117 << " Guest connectivity may be broken.";
118
Hugo Benichi58125d32020-09-09 11:25:45 +0900119 // Create a FORWARD ACCEPT rule for connections already established.
120 if (process_runner_->iptables(
121 "filter", {"-A", "FORWARD", "-m", "state", "--state",
122 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900123 LOG(ERROR) << "Failed to install forwarding rule for established"
124 << " connections.";
125
126 // chromium:898210: Drop any locally originated traffic that would exit a
127 // physical interface with a source IPv4 address from the subnet of IPs used
128 // for VMs, containers, and connected namespaces This is needed to prevent
129 // packets leaking with an incorrect src IP when a local process binds to the
130 // wrong interface.
131 for (const auto& oif : kPhysicalIfnamePrefixes) {
132 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
133 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
134 << kGuestIPv4Subnet << " exiting " << oif;
135 }
136
137 if (!AddOutboundIPv4SNATMark("vmtap+"))
138 LOG(ERROR) << "Failed to set up NAT for TAP devices."
139 << " Guest connectivity may be broken.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900140
Taoyu Li78f0c9a2020-12-25 22:58:26 +0900141 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
142 // wrongly cause neighbor discovery icmpv6 packets to be dropped. Add these
143 // rules to bypass connmark rule for those packets.
144 for (const auto& type : kNeighborDiscoveryTypes) {
145 if (!ModifyIptables(IpFamily::IPv6, "mangle",
146 {"-A", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
147 "-j", "ACCEPT", "-w"}))
148 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
149 << " packets";
150 }
151
Hugo Benichi2a940542020-10-26 18:50:49 +0900152 // Applies the routing tag saved in conntrack for any established connection
153 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900154 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
155 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900156 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
Hugo Benichi155de002021-01-19 16:45:46 +0900157 // b/177787823 Also restore the routing tag after routing has taken place so
158 // that packets pre-tagged with the VPN routing tag are in sync with their
159 // associated CONNMARK routing tag. This is necessary to correctly identify
160 // packets exiting through the wrong interface.
161 if (!ModifyConnmarkRestore(IpFamily::Dual, "POSTROUTING", "-A", "" /*iif*/,
162 kFwmarkRoutingMask))
163 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK restore rule";
Hugo Benichi2a940542020-10-26 18:50:49 +0900164
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900165 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
166 // tag and tagging the local traffic that should be routed through a VPN.
167 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyLocalSourceMarkChain))
168 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
169 << " mangle chain";
170 // Ensure that the chain is empty if patchpanel is restarting after a crash.
171 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyLocalSourceMarkChain))
172 LOG(ERROR) << "Failed to flush " << kApplyLocalSourceMarkChain
173 << " mangle chain";
174 if (!ModifyIptables(IpFamily::Dual, "mangle",
175 {"-A", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
176 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
177 << " to mangle OUTPUT";
178 // Create rules for tagging local sources with the source tag and the vpn
179 // policy tag.
180 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900181 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900182 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
183 << " in " << kApplyLocalSourceMarkChain;
184 }
185 // Finally add a catch-all rule for tagging any remaining local sources with
186 // the SYSTEM source tag
187 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
188 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
189
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900190 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
191 // traffic that should be routed through a VPN.
192 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyVpnMarkChain))
193 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
194 // Ensure that the chain is empty if patchpanel is restarting after a crash.
195 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyVpnMarkChain))
196 LOG(ERROR) << "Failed to flush " << kApplyVpnMarkChain << " mangle chain";
197 // All local outgoing traffic eligible to VPN routing should traverse the VPN
198 // marking chain.
199 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", "" /*iif*/, kFwmarkRouteOnVpn,
200 kFwmarkVpnMask))
201 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
202 // Any traffic that already has a routing tag applied is accepted.
203 if (!ModifyIptables(
204 IpFamily::Dual, "mangle",
205 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
206 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
207 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
208 "connections";
Hugo Benichi155de002021-01-19 16:45:46 +0900209
210 // Sets up a mangle chain used in POSTROUTING for checking consistency between
211 // the routing tag and the output interface.
212 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kCheckRoutingMarkChain))
213 LOG(ERROR) << "Failed to set up " << kCheckRoutingMarkChain
214 << " mangle chain";
215 // Ensure that the chain is empty if patchpanel is restarting after a crash.
216 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kCheckRoutingMarkChain))
217 LOG(ERROR) << "Failed to flush " << kCheckRoutingMarkChain
218 << " mangle chain";
219
220 // b/177787823 If it already exists, the routing tag of any traffic exiting an
221 // interface (physical or VPN) must match the routing tag of that interface.
222 if (!ModifyIptables(IpFamily::Dual, "mangle",
223 {"-A", "POSTROUTING", "-m", "mark", "!", "--mark",
224 "0x0/" + kFwmarkRoutingMask.ToString(), "-j",
225 kCheckRoutingMarkChain, "-w"}))
226 LOG(ERROR) << "Failed to add POSTROUTING jump rule to "
227 << kCheckRoutingMarkChain;
Hugo Benichibf811c62020-09-07 17:30:45 +0900228}
229
230void Datapath::Stop() {
231 RemoveOutboundIPv4SNATMark("vmtap+");
Hugo Benichi58125d32020-09-09 11:25:45 +0900232 process_runner_->iptables("filter",
233 {"-D", "FORWARD", "-m", "state", "--state",
234 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"});
Hugo Benichibf811c62020-09-07 17:30:45 +0900235 RemoveSNATMarkRules();
236 for (const auto& oif : kPhysicalIfnamePrefixes)
237 RemoveSourceIPv4DropRule(oif, kGuestIPv4Subnet);
238
239 // Restore original local port range.
240 // TODO(garrick): The original history behind this tweak is gone. Some
241 // investigation is needed to see if it is still applicable.
242 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
243 "32768 61000") != 0)
244 LOG(ERROR) << "Failed to restore local port range";
245
246 // Disable packet forwarding
247 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
248 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
249
250 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
251 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900252
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900253 // Detach the VPN marking mangle chain
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900254 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-D", "" /*iif*/, kFwmarkRouteOnVpn,
255 kFwmarkVpnMask))
256 LOG(ERROR)
257 << "Failed to remove from mangle OUTPUT chain jump rule to VPN chain";
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900258
259 // Detach apply_local_source_mark from mangle PREROUTING
260 if (!ModifyIptables(IpFamily::Dual, "mangle",
261 {"-D", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
262 LOG(ERROR) << "Failed to detach " << kApplyLocalSourceMarkChain
263 << " from mangle OUTPUT";
264
Hugo Benichi2a940542020-10-26 18:50:49 +0900265 // Stops applying routing tags saved in conntrack for sockets created in the
266 // host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900267 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-D", "" /*iif*/,
268 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900269 LOG(ERROR) << "Failed to remove OUTPUT CONNMARK restore rule";
Hugo Benichi155de002021-01-19 16:45:46 +0900270 if (!ModifyConnmarkRestore(IpFamily::Dual, "POSTROUTING", "-D", "",
271 kFwmarkRoutingMask))
272 LOG(ERROR) << "Failed to remove POSTROUTING CONNMARK restore rule";
273
274 // Delete the POSTROUTING jump rule to check_routing_mark chain holding
275 // routing tag filter rules.
276 if (!ModifyIptables(IpFamily::Dual, "mangle",
277 {"-D", "POSTROUTING", "-m", "mark", "!", "--mark",
278 "0x0/" + kFwmarkRoutingMask.ToString(), "-j",
279 kCheckRoutingMarkChain, "-w"}))
280 LOG(ERROR) << "Failed to remove POSTROUTING jump rule to "
281 << kCheckRoutingMarkChain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900282
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900283 // Delete the mangle chains
Hugo Benichi155de002021-01-19 16:45:46 +0900284 for (const auto* chain : {kApplyLocalSourceMarkChain, kApplyVpnMarkChain,
285 kCheckRoutingMarkChain}) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900286 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", chain))
287 LOG(ERROR) << "Failed to flush " << chain << " mangle chain";
288
289 if (!ModifyChain(IpFamily::Dual, "mangle", "-X", chain))
290 LOG(ERROR) << "Failed to delete " << chain << " mangle chain";
291 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900292}
293
Hugo Benichi33860d72020-07-09 16:34:01 +0900294bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
295 // Try first to delete any netns with name |netns_name| in case patchpanel
296 // did not exit cleanly.
297 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
298 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
299 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
300}
301
302bool Datapath::NetnsDeleteName(const std::string& netns_name) {
303 return process_runner_->ip_netns_delete(netns_name) == 0;
304}
305
Garrick Evans8a949dc2019-07-18 16:17:53 +0900306bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900307 uint32_t ipv4_addr,
308 uint32_t ipv4_prefix_len) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900309 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900310 if (process_runner_->brctl("addbr", {ifname}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900311 return false;
312 }
313
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900314 if (process_runner_->ip(
315 "addr", "add",
316 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
317 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
318 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900319 RemoveBridge(ifname);
320 return false;
321 }
322
323 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900324 RemoveBridge(ifname);
325 return false;
326 }
327
328 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900329 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900330 RemoveBridge(ifname);
331 return false;
332 }
333
334 return true;
335}
336
337void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900338 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900339 process_runner_->ip("link", "set", {ifname, "down"});
Garrick Evans8e8e3472020-01-23 14:03:50 +0900340 process_runner_->brctl("delbr", {ifname});
Garrick Evans8a949dc2019-07-18 16:17:53 +0900341}
342
Garrick Evans621ed262019-11-13 12:28:43 +0900343bool Datapath::AddToBridge(const std::string& br_ifname,
344 const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900345 return (process_runner_->brctl("addif", {br_ifname, ifname}) == 0);
Garrick Evans621ed262019-11-13 12:28:43 +0900346}
347
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900348std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900349 const MacAddress* mac_addr,
350 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900351 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900352 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
353 if (!dev.is_valid()) {
354 PLOG(ERROR) << "Failed to open " << kTunDev;
355 return "";
356 }
357
358 struct ifreq ifr;
359 memset(&ifr, 0, sizeof(ifr));
360 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
361 sizeof(ifr.ifr_name));
362 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
363
364 // If a template was given as the name, ifr_name will be updated with the
365 // actual interface name.
366 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900367 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900368 return "";
369 }
370 const char* ifname = ifr.ifr_name;
371
372 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900373 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900374 return "";
375 }
376
Garrick Evans4f9f5572019-11-26 10:25:16 +0900377 if (!user.empty()) {
378 uid_t uid = -1;
379 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
380 PLOG(ERROR) << "Unable to look up UID for " << user;
381 RemoveTAP(ifname);
382 return "";
383 }
384 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
385 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
386 << ifname;
387 RemoveTAP(ifname);
388 return "";
389 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900390 }
391
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900392 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900393 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
394 if (!sock.is_valid()) {
395 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900396 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900397 RemoveTAP(ifname);
398 return "";
399 }
400
Garrick Evans621ed262019-11-13 12:28:43 +0900401 if (ipv4_addr) {
402 struct sockaddr_in* addr =
403 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
404 addr->sin_family = AF_INET;
405 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
406 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
407 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
408 << " {" << ipv4_addr->ToCidrString() << "}";
409 RemoveTAP(ifname);
410 return "";
411 }
412
413 struct sockaddr_in* netmask =
414 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
415 netmask->sin_family = AF_INET;
416 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
417 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
418 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
419 << " {" << ipv4_addr->ToCidrString() << "}";
420 RemoveTAP(ifname);
421 return "";
422 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900423 }
424
Garrick Evans621ed262019-11-13 12:28:43 +0900425 if (mac_addr) {
426 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
427 hwaddr->sa_family = ARPHRD_ETHER;
428 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
429 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
430 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
431 << " {" << MacAddressToString(*mac_addr) << "}";
432 RemoveTAP(ifname);
433 return "";
434 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900435 }
436
437 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900438 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900439 RemoveTAP(ifname);
440 return "";
441 }
442
443 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
444 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900445 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900446 RemoveTAP(ifname);
447 return "";
448 }
449
450 return ifname;
451}
452
453void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900454 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900455}
456
Hugo Benichi33860d72020-07-09 16:34:01 +0900457bool Datapath::ConnectVethPair(pid_t netns_pid,
458 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900459 const std::string& veth_ifname,
460 const std::string& peer_ifname,
461 const MacAddress& remote_mac_addr,
462 uint32_t remote_ipv4_addr,
463 uint32_t remote_ipv4_prefix_len,
464 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900465 // Set up the virtual pair across the current namespace and |netns_name|.
466 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
467 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
468 << peer_ifname;
469 return false;
470 }
471
472 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900473 {
Hugo Benichi33860d72020-07-09 16:34:01 +0900474 ScopedNS ns(netns_pid);
475 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900476 LOG(ERROR)
477 << "Cannot create virtual link -- invalid container namespace?";
478 return false;
479 }
480
Hugo Benichi76675592020-04-08 14:29:57 +0900481 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
482 remote_ipv4_prefix_len, true /* link up */,
483 remote_multicast_flag)) {
484 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
485 RemoveInterface(peer_ifname);
486 return false;
487 }
488 }
489
Hugo Benichi76675592020-04-08 14:29:57 +0900490 if (!ToggleInterface(veth_ifname, true /*up*/)) {
491 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
492 RemoveInterface(veth_ifname);
493 return false;
494 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900495
Hugo Benichi76675592020-04-08 14:29:57 +0900496 return true;
497}
498
Hugo Benichi33860d72020-07-09 16:34:01 +0900499bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
500 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900501 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900502 return process_runner_->ip("link", "add",
503 {veth_ifname, "type", "veth", "peer", "name",
504 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900505}
Garrick Evans54861622019-07-19 09:05:09 +0900506
Garrick Evans2470caa2020-03-04 14:15:41 +0900507bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
508 const std::string link = up ? "up" : "down";
509 return process_runner_->ip("link", "set", {ifname, link}) == 0;
510}
Garrick Evans54861622019-07-19 09:05:09 +0900511
Garrick Evans2470caa2020-03-04 14:15:41 +0900512bool Datapath::ConfigureInterface(const std::string& ifname,
513 const MacAddress& mac_addr,
514 uint32_t ipv4_addr,
515 uint32_t ipv4_prefix_len,
516 bool up,
517 bool enable_multicast) {
518 const std::string link = up ? "up" : "down";
519 const std::string multicast = enable_multicast ? "on" : "off";
520 return (process_runner_->ip(
521 "addr", "add",
522 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
523 IPv4AddressToString(
524 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
525 "dev", ifname}) == 0) &&
526 (process_runner_->ip("link", "set",
527 {
528 "dev",
529 ifname,
530 link,
531 "addr",
532 MacAddressToString(mac_addr),
533 "multicast",
534 multicast,
535 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900536}
537
538void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900539 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900540}
541
Hugo Benichi321f23b2020-09-25 15:42:05 +0900542bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
543 const std::string& src_ip) {
544 return process_runner_->iptables("filter", {"-I", "OUTPUT", "-o", oif, "-s",
545 src_ip, "-j", "DROP", "-w"}) == 0;
546}
547
548bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
549 const std::string& src_ip) {
550 return process_runner_->iptables("filter", {"-D", "OUTPUT", "-o", oif, "-s",
551 src_ip, "-j", "DROP", "-w"}) == 0;
552}
553
Hugo Benichifcf81022020-12-04 11:01:37 +0900554bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900555 // Veth interface configuration and client routing configuration:
556 // - attach a name to the client namespace.
557 // - create veth pair across the current namespace and the client namespace.
558 // - configure IPv4 address on remote veth inside client namespace.
559 // - configure IPv4 address on local veth inside host namespace.
560 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900561 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
562 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
563 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900564 return false;
565 }
566
Hugo Benichifcf81022020-12-04 11:01:37 +0900567 if (!ConnectVethPair(
568 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
569 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
570 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900571 LOG(ERROR) << "Failed to create veth pair for"
572 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900573 << nsinfo.pid;
574 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900575 return false;
576 }
577
Hugo Benichifcf81022020-12-04 11:01:37 +0900578 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
579 nsinfo.peer_subnet->AddressAtOffset(0),
580 nsinfo.peer_subnet->PrefixLength(),
581 true /* link up */, false /* enable_multicast */)) {
582 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
583 RemoveInterface(nsinfo.host_ifname);
584 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900585 return false;
586 }
587
588 {
Hugo Benichifcf81022020-12-04 11:01:37 +0900589 ScopedNS ns(nsinfo.pid);
590 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
591 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
592 RemoveInterface(nsinfo.host_ifname);
593 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900594 return false;
595 }
596
Hugo Benichifcf81022020-12-04 11:01:37 +0900597 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
598 INADDR_ANY)) {
599 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
600 << " inside namespace pid " << nsinfo.pid;
601 RemoveInterface(nsinfo.host_ifname);
602 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900603 return false;
604 }
605 }
606
607 // Host namespace routing configuration
608 // - ingress: add route to client subnet via |host_ifname|.
609 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
610 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
611 // Note that by default unsolicited ingress traffic is not forwarded to the
612 // client namespace unless the client specifically set port forwarding
613 // through permission_broker DBus APIs.
614 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
615 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900616 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
617 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
618 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900619 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900620 RemoveInterface(nsinfo.host_ifname);
621 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900622 return false;
623 }
624
Hugo Benichi7c342672020-09-08 09:18:14 +0900625 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900626 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900627 LOG(ERROR) << "Failed to set SNAT for traffic"
628 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900629 << nsinfo.host_ifname;
630 RemoveInterface(nsinfo.host_ifname);
631 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
632 nsinfo.peer_subnet->BaseAddress(), netmask);
633 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
634 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900635 return false;
636 }
637
Hugo Benichi93306e52020-12-04 16:08:00 +0900638 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
639 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
640 nsinfo.route_on_vpn);
641
Hugo Benichi7c342672020-09-08 09:18:14 +0900642 return true;
643}
644
Hugo Benichifcf81022020-12-04 11:01:37 +0900645void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900646 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
647 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
648 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900649 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900650 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
651 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
652 nsinfo.peer_subnet->BaseAddress(),
653 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
654 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900655}
656
Hugo Benichi8d622b52020-08-13 15:24:12 +0900657void Datapath::StartRoutingDevice(const std::string& ext_ifname,
658 const std::string& int_ifname,
659 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900660 TrafficSource source,
661 bool route_on_vpn) {
662 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900663 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900664 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
665 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
666 << "->" << int_ifname;
667
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900668 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900669 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
670 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900671
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900672 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900673 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
674 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900675
Hugo Benichi2a940542020-10-26 18:50:49 +0900676 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
677 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
678 << source << " for " << int_ifname;
679
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900680 if (!ext_ifname.empty()) {
681 // If |ext_ifname| is not null, mark egress traffic with the
682 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi2a940542020-10-26 18:50:49 +0900683 if (!ModifyFwmarkRoutingTag("PREROUTING", "-A", ext_ifname, int_ifname))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900684 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
685 << ext_ifname << "<-" << int_ifname;
686 } else {
687 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
688 // PREROUTING to apply any fwmark routing tag saved for the current
689 // connection, and rely on implicit routing to the default logical network
690 // otherwise.
Hugo Benichi1af52392020-11-27 18:09:32 +0900691 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname,
692 kFwmarkRoutingMask))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900693 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
694 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900695
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900696 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900697 // default network is eligible to be routed through a VPN if |route_on_vpn|
698 // is true.
699 if (route_on_vpn &&
700 !ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900701 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900702 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900703}
704
705void Datapath::StopRoutingDevice(const std::string& ext_ifname,
706 const std::string& int_ifname,
707 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900708 TrafficSource source,
709 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900710 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900711 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900712 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
713 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900714 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900715 if (!ext_ifname.empty()) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900716 ModifyFwmarkRoutingTag("PREROUTING", "-D", ext_ifname, int_ifname);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900717 } else {
Hugo Benichi1af52392020-11-27 18:09:32 +0900718 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname,
719 kFwmarkRoutingMask);
Hugo Benichi93306e52020-12-04 16:08:00 +0900720 if (route_on_vpn)
721 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900722 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900723}
724
Garrick Evansf0ab7132019-06-18 14:50:42 +0900725bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
726 const std::string& ipv4_addr) {
727 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900728 if (process_runner_->iptables(
729 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
730 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900731 return false;
732
733 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900734 if (process_runner_->iptables(
735 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
736 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900737 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
738 return false;
739 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900740 if (process_runner_->iptables(
741 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
742 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900743 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
744 return false;
745 }
746
747 return true;
748}
749
750void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
751 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900752 process_runner_->iptables(
753 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
754 "--to-destination", ipv4_addr, "-w"});
755 process_runner_->iptables(
756 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
757 "--to-destination", ipv4_addr, "-w"});
758 process_runner_->iptables(
759 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
760 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900761}
762
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900763// TODO(b/161507671) Stop relying on the traffic fwmark 1/1 once forwarded
764// egress traffic is routed through the fwmark routing tag.
Garrick Evansd291af62020-05-25 10:39:06 +0900765bool Datapath::AddSNATMarkRules() {
Taoyu Li79871c92020-07-02 16:09:39 +0900766 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
767 // need to be explicitly dropped.
768 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900769 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
Taoyu Li79871c92020-07-02 16:09:39 +0900770 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0) {
771 return false;
772 }
Garrick Evansd291af62020-05-25 10:39:06 +0900773 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900774 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900775 "ACCEPT", "-w"}) != 0) {
776 return false;
777 }
778 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900779 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900780 "MASQUERADE", "-w"}) != 0) {
781 RemoveSNATMarkRules();
782 return false;
783 }
784 return true;
785}
786
787void Datapath::RemoveSNATMarkRules() {
788 process_runner_->iptables("nat", {"-D", "POSTROUTING", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900789 "1/1", "-j", "MASQUERADE", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900790 process_runner_->iptables("filter", {"-D", "FORWARD", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900791 "1/1", "-j", "ACCEPT", "-w"});
Taoyu Li79871c92020-07-02 16:09:39 +0900792 process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900793 "filter", {"-D", "FORWARD", "-m", "mark", "--mark", "1/1", "-m", "state",
Taoyu Li79871c92020-07-02 16:09:39 +0900794 "--state", "INVALID", "-j", "DROP", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900795}
796
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
Garrick Evans664a82f2019-12-17 12:18:05 +0900808bool Datapath::MaskInterfaceFlags(const std::string& ifname,
809 uint16_t on,
810 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900811 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
812 if (!sock.is_valid()) {
813 PLOG(ERROR) << "Failed to create control socket";
814 return false;
815 }
816 ifreq ifr;
817 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
818 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
819 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
820 return false;
821 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900822 ifr.ifr_flags |= on;
823 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900824 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900825 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
826 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900827 return false;
828 }
829 return true;
830}
831
Garrick Evans260ff302019-07-25 11:22:50 +0900832bool Datapath::AddIPv6HostRoute(const std::string& ifname,
833 const std::string& ipv6_addr,
834 int ipv6_prefix_len) {
835 std::string ipv6_addr_cidr =
836 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
837
Garrick Evans8e8e3472020-01-23 14:03:50 +0900838 return process_runner_->ip6("route", "replace",
839 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900840}
841
842void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
843 const std::string& ipv6_addr,
844 int ipv6_prefix_len) {
845 std::string ipv6_addr_cidr =
846 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
847
Garrick Evans8e8e3472020-01-23 14:03:50 +0900848 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900849}
850
Taoyu Lia0727dc2020-09-24 19:54:59 +0900851bool Datapath::AddIPv6Address(const std::string& ifname,
852 const std::string& ipv6_addr) {
853 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900854}
855
Taoyu Lia0727dc2020-09-24 19:54:59 +0900856void Datapath::RemoveIPv6Address(const std::string& ifname,
857 const std::string& ipv6_addr) {
858 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900859}
860
Hugo Benichi76be34a2020-08-26 22:35:54 +0900861void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900862 int ifindex = FindIfIndex(ext_ifname);
863 if (ifindex != 0 && !ModifyIptables(IpFamily::Dual, "mangle",
864 {"-A", kCheckRoutingMarkChain, "-o",
865 ext_ifname, "-m", "mark", "!", "--mark",
866 Fwmark::FromIfIndex(ifindex).ToString() +
867 "/" + kFwmarkRoutingMask.ToString(),
868 "-j", "DROP", "-w"}))
869 LOG(ERROR) << "Could not set fwmark routing filter rule for " << ext_ifname;
870
Hugo Benichi1af52392020-11-27 18:09:32 +0900871 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi76be34a2020-08-26 22:35:54 +0900872 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
873 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900874 // Save in CONNMARK the source tag for egress traffic of this connection.
875 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
876 kFwmarkAllSourcesMask))
877 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
878 "source tag on "
879 << ext_ifname;
880 // Restore from CONNMARK the source tag for ingress traffic of this connection
881 // (returned traffic).
882 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
883 kFwmarkAllSourcesMask))
884 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
885 "traffic received on "
886 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900887}
888
889void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900890 int ifindex = FindIfIndex(ext_ifname);
891 if (ifindex != 0 && !ModifyIptables(IpFamily::Dual, "mangle",
892 {"-D", kCheckRoutingMarkChain, "-o",
893 ext_ifname, "-m", "mark", "!", "--mark",
894 Fwmark::FromIfIndex(ifindex).ToString() +
895 "/" + kFwmarkRoutingMask.ToString(),
896 "-j", "DROP", "-w"}))
897 LOG(ERROR) << "Could not remove fwmark routing filter rule for "
898 << ext_ifname;
899
Hugo Benichi76be34a2020-08-26 22:35:54 +0900900 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
901 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900902 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
903 kFwmarkAllSourcesMask))
904 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
905 "fwmark source tag on "
906 << ext_ifname;
907 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
908 kFwmarkAllSourcesMask))
909 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
910 "traffic received on "
911 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900912}
913
Hugo Benichi2a940542020-10-26 18:50:49 +0900914void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi891275e2020-12-16 10:35:34 +0900915 if (process_runner_->iptables("nat", {"-A", "POSTROUTING", "-o", vpn_ifname,
916 "-j", "MASQUERADE", "-w"}) != 0)
917 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900918 StartConnectionPinning(vpn_ifname);
919 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", vpn_ifname, ""))
920 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +0900921 if (vpn_ifname != kArcBridge)
922 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
923 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi2a940542020-10-26 18:50:49 +0900924}
925
926void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900927 if (vpn_ifname != kArcBridge)
928 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
929 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi2a940542020-10-26 18:50:49 +0900930 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", vpn_ifname, ""))
931 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
932 StopConnectionPinning(vpn_ifname);
Hugo Benichi891275e2020-12-16 10:35:34 +0900933 if (process_runner_->iptables("nat", {"-D", "POSTROUTING", "-o", vpn_ifname,
934 "-j", "MASQUERADE", "-w"}) != 0)
935 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900936}
937
Hugo Benichi76be34a2020-08-26 22:35:54 +0900938bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
939 const std::string& op,
940 const std::string& oif) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900941 int ifindex = FindIfIndex(oif);
942 if (ifindex == 0) {
943 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
944 return false;
945 }
946
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900947 return ModifyConnmarkSet(family, "POSTROUTING", op, oif,
948 Fwmark::FromIfIndex(ifindex), kFwmarkRoutingMask);
949}
950
951bool Datapath::ModifyConnmarkSet(IpFamily family,
952 const std::string& chain,
953 const std::string& op,
954 const std::string& oif,
955 Fwmark mark,
956 Fwmark mask) {
957 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
958 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
959 return false;
960 }
961
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900962 std::vector<std::string> args = {op, chain};
963 if (!oif.empty()) {
964 args.push_back("-o");
965 args.push_back(oif);
966 }
967 args.push_back("-j");
968 args.push_back("CONNMARK");
969 args.push_back("--set-mark");
970 args.push_back(mark.ToString() + "/" + mask.ToString());
971 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +0900972
Hugo Benichi58f264a2020-10-16 18:16:05 +0900973 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +0900974}
975
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900976bool Datapath::ModifyConnmarkRestore(IpFamily family,
977 const std::string& chain,
978 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +0900979 const std::string& iif,
980 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900981 std::vector<std::string> args = {op, chain};
982 if (!iif.empty()) {
983 args.push_back("-i");
984 args.push_back(iif);
985 }
986 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +0900987 mask.ToString(), "-w"});
988 return ModifyIptables(family, "mangle", args);
989}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900990
Hugo Benichi1af52392020-11-27 18:09:32 +0900991bool Datapath::ModifyConnmarkSave(IpFamily family,
992 const std::string& chain,
993 const std::string& op,
994 const std::string& oif,
995 Fwmark mask) {
996 std::vector<std::string> args = {op, chain};
997 if (!oif.empty()) {
998 args.push_back("-o");
999 args.push_back(oif);
1000 }
1001 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
1002 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +09001003 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001004}
1005
Hugo Benichi2a940542020-10-26 18:50:49 +09001006bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1007 const std::string& op,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001008 const std::string& ext_ifname,
1009 const std::string& int_ifname) {
1010 int ifindex = FindIfIndex(ext_ifname);
1011 if (ifindex == 0) {
1012 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
1013 return false;
1014 }
1015
Hugo Benichi2a940542020-10-26 18:50:49 +09001016 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001017 0 /*classid*/, Fwmark::FromIfIndex(ifindex),
1018 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001019}
1020
Hugo Benichi9be19b12020-08-14 15:33:40 +09001021bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
1022 const std::string& iif,
1023 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001024 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001025 0 /*classid*/, Fwmark::FromSource(source),
1026 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001027}
1028
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001029bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1030 TrafficSource source) {
1031 std::vector<std::string> args = {"-A",
1032 kApplyLocalSourceMarkChain,
1033 "-m",
1034 "mark",
1035 "--mark",
1036 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1037 "-j",
1038 "MARK",
1039 "--set-mark",
1040 Fwmark::FromSource(source).ToString() + "/" +
1041 kFwmarkAllSourcesMask.ToString(),
1042 "-w"};
1043 return ModifyIptables(IpFamily::Dual, "mangle", args);
1044}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001045
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001046bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1047 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001048 if (std::string(source.uid_name).empty() && source.classid == 0)
1049 return false;
1050
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001051 Fwmark mark = Fwmark::FromSource(source.source_type);
1052 if (source.is_on_vpn)
1053 mark = mark | kFwmarkRouteOnVpn;
1054
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001055 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1056 "" /*iif*/, source.uid_name, source.classid, mark,
1057 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001058}
1059
1060bool Datapath::ModifyFwmark(IpFamily family,
1061 const std::string& chain,
1062 const std::string& op,
1063 const std::string& iif,
1064 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001065 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001066 Fwmark mark,
1067 Fwmark mask,
1068 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001069 std::vector<std::string> args = {op, chain};
1070 if (!iif.empty()) {
1071 args.push_back("-i");
1072 args.push_back(iif);
1073 }
1074 if (!uid_name.empty()) {
1075 args.push_back("-m");
1076 args.push_back("owner");
1077 args.push_back("--uid-owner");
1078 args.push_back(uid_name);
1079 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001080 if (classid != 0) {
1081 args.push_back("-m");
1082 args.push_back("cgroup");
1083 args.push_back("--cgroup");
1084 args.push_back(base::StringPrintf("0x%08x", classid));
1085 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001086 args.push_back("-j");
1087 args.push_back("MARK");
1088 args.push_back("--set-mark");
1089 args.push_back(mark.ToString() + "/" + mask.ToString());
1090 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001091
Hugo Benichi58f264a2020-10-16 18:16:05 +09001092 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001093}
1094
Hugo Benichid82d8832020-08-14 10:05:03 +09001095bool Datapath::ModifyIpForwarding(IpFamily family,
1096 const std::string& op,
1097 const std::string& iif,
1098 const std::string& oif,
1099 bool log_failures) {
1100 if (iif.empty() && oif.empty()) {
1101 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1102 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001103 return false;
1104 }
1105
Hugo Benichid82d8832020-08-14 10:05:03 +09001106 std::vector<std::string> args = {op, "FORWARD"};
1107 if (!iif.empty()) {
1108 args.push_back("-i");
1109 args.push_back(iif);
1110 }
1111 if (!oif.empty()) {
1112 args.push_back("-o");
1113 args.push_back(oif);
1114 }
1115 args.push_back("-j");
1116 args.push_back("ACCEPT");
1117 args.push_back("-w");
1118
Hugo Benichi58f264a2020-10-16 18:16:05 +09001119 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001120}
1121
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001122bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1123 const std::string& op,
1124 const std::string& iif,
1125 Fwmark mark,
1126 Fwmark mask) {
1127 std::vector<std::string> args = {op, chain};
1128 if (!iif.empty()) {
1129 args.push_back("-i");
1130 args.push_back(iif);
1131 }
1132 if (mark.Value() != 0 && mask.Value() != 0) {
1133 args.push_back("-m");
1134 args.push_back("mark");
1135 args.push_back("--mark");
1136 args.push_back(mark.ToString() + "/" + mask.ToString());
1137 }
1138 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1139 return ModifyIptables(IpFamily::Dual, "mangle", args);
1140}
1141
1142bool Datapath::ModifyChain(IpFamily family,
1143 const std::string& table,
1144 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001145 const std::string& chain,
1146 bool log_failures) {
1147 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001148}
1149
1150bool Datapath::ModifyIptables(IpFamily family,
1151 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001152 const std::vector<std::string>& argv,
1153 bool log_failures) {
1154 switch (family) {
1155 case IPv4:
1156 case IPv6:
1157 case Dual:
1158 break;
1159 default:
1160 LOG(ERROR) << "Could not execute iptables command " << table
1161 << base::JoinString(argv, " ") << ": incorrect IP family "
1162 << family;
1163 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001164 }
1165
1166 bool success = true;
1167 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001168 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001169 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001170 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001171 return success;
1172}
1173
Hugo Benichid82d8832020-08-14 10:05:03 +09001174bool Datapath::StartIpForwarding(IpFamily family,
1175 const std::string& iif,
1176 const std::string& oif) {
1177 return ModifyIpForwarding(family, "-A", iif, oif);
1178}
1179
1180bool Datapath::StopIpForwarding(IpFamily family,
1181 const std::string& iif,
1182 const std::string& oif) {
1183 return ModifyIpForwarding(family, "-D", iif, oif);
1184}
1185
1186bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1187 const std::string& ifname2) {
1188 // Only start Ipv6 forwarding if -C returns false and it had not been
1189 // started yet.
1190 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1191 false /*log_failures*/) &&
1192 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1193 return false;
1194 }
1195
1196 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1197 false /*log_failures*/) &&
1198 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001199 RemoveIPv6Forwarding(ifname1, ifname2);
1200 return false;
1201 }
1202
1203 return true;
1204}
1205
1206void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1207 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001208 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1209 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001210}
1211
Garrick Evans3d97a392020-02-21 15:24:37 +09001212bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1213 uint32_t addr,
1214 uint32_t netmask) {
1215 struct rtentry route;
1216 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001217 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1218 SetSockaddrIn(&route.rt_dst, addr & netmask);
1219 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001220 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001221 return ModifyRtentry(SIOCADDRT, &route);
1222}
Garrick Evans3d97a392020-02-21 15:24:37 +09001223
Hugo Benichie8758b52020-04-03 14:49:01 +09001224bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1225 uint32_t addr,
1226 uint32_t netmask) {
1227 struct rtentry route;
1228 memset(&route, 0, sizeof(route));
1229 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1230 SetSockaddrIn(&route.rt_dst, addr & netmask);
1231 SetSockaddrIn(&route.rt_genmask, netmask);
1232 route.rt_flags = RTF_UP | RTF_GATEWAY;
1233 return ModifyRtentry(SIOCDELRT, &route);
1234}
1235
1236bool Datapath::AddIPv4Route(const std::string& ifname,
1237 uint32_t addr,
1238 uint32_t netmask) {
1239 struct rtentry route;
1240 memset(&route, 0, sizeof(route));
1241 SetSockaddrIn(&route.rt_dst, addr & netmask);
1242 SetSockaddrIn(&route.rt_genmask, netmask);
1243 char rt_dev[IFNAMSIZ];
1244 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1245 rt_dev[IFNAMSIZ - 1] = '\0';
1246 route.rt_dev = rt_dev;
1247 route.rt_flags = RTF_UP | RTF_GATEWAY;
1248 return ModifyRtentry(SIOCADDRT, &route);
1249}
1250
1251bool Datapath::DeleteIPv4Route(const std::string& ifname,
1252 uint32_t addr,
1253 uint32_t netmask) {
1254 struct rtentry route;
1255 memset(&route, 0, sizeof(route));
1256 SetSockaddrIn(&route.rt_dst, addr & netmask);
1257 SetSockaddrIn(&route.rt_genmask, netmask);
1258 char rt_dev[IFNAMSIZ];
1259 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1260 rt_dev[IFNAMSIZ - 1] = '\0';
1261 route.rt_dev = rt_dev;
1262 route.rt_flags = RTF_UP | RTF_GATEWAY;
1263 return ModifyRtentry(SIOCDELRT, &route);
1264}
1265
Taoyu Lia0727dc2020-09-24 19:54:59 +09001266bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001267 DCHECK(route);
1268 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001269 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001270 return false;
1271 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001272 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1273 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001274 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001275 return false;
1276 }
1277 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1278 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001279 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001280 return false;
1281 }
1282 return true;
1283}
1284
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001285bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1286 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1287 kArcAddr, kAdbServerPort, ifname,
1288 kLocalhostAddr, kAdbProxyTcpListenPort);
1289}
1290
1291void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1292 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1293 kArcAddr, kAdbServerPort, ifname,
1294 kLocalhostAddr, kAdbProxyTcpListenPort);
1295}
1296
1297bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1298 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1299 kAdbProxyTcpListenPort, ifname);
1300}
1301
1302void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1303 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1304 kAdbProxyTcpListenPort, ifname);
1305}
1306
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001307void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1308 if_nametoindex_[ifname] = ifindex;
1309}
1310
1311int Datapath::FindIfIndex(const std::string& ifname) {
1312 uint32_t ifindex = if_nametoindex(ifname.c_str());
1313 if (ifindex > 0) {
1314 if_nametoindex_[ifname] = ifindex;
1315 return ifindex;
1316 }
1317
1318 const auto it = if_nametoindex_.find(ifname);
1319 if (it != if_nametoindex_.end())
1320 return it->second;
1321
1322 return 0;
1323}
1324
Hugo Benichifcf81022020-12-04 11:01:37 +09001325std::ostream& operator<<(std::ostream& stream,
1326 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001327 stream << "{ pid: " << nsinfo.pid
1328 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001329 if (!nsinfo.outbound_ifname.empty()) {
1330 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1331 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001332 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1333 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001334 << ", peer_ifname: " << nsinfo.peer_ifname
1335 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1336 return stream;
1337}
1338
Garrick Evans3388a032020-03-24 11:25:55 +09001339} // namespace patchpanel