blob: b9f0fef0e7f2b2792ed2acb7cfcd389a8e8b6e05 [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";
52
Hugo Benichi2a940542020-10-26 18:50:49 +090053// Constant fwmark mask for matching local socket traffic that should be routed
54// through a VPN connection. The traffic must not be part of an existing
55// connection and must match exactly the VPN routing intent policy bit.
56const Fwmark kFwmarkVpnMatchingMask = kFwmarkRoutingMask | kFwmarkVpnMask;
57
Garrick Evans8a067562020-05-11 12:47:30 +090058std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
59 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090060 if (n.length() < IFNAMSIZ)
61 return n;
Garrick Evans54861622019-07-19 09:05:09 +090062
Garrick Evans2f581a02020-05-11 10:43:35 +090063 // Best effort attempt to preserve the interface number, assuming it's the
64 // last char in the name.
65 auto c = ifname[ifname.length() - 1];
66 n.resize(IFNAMSIZ - 1);
67 n[n.length() - 1] = c;
68 return n;
Garrick Evans54861622019-07-19 09:05:09 +090069}
Garrick Evansf0ab7132019-06-18 14:50:42 +090070
Garrick Evans8a067562020-05-11 12:47:30 +090071} // namespace
72
73std::string ArcVethHostName(const std::string& ifname) {
74 return PrefixIfname("veth", ifname);
75}
76
77std::string ArcBridgeName(const std::string& ifname) {
78 return PrefixIfname("arc_", ifname);
79}
80
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090081Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
82 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090083
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090084Datapath::Datapath(MinijailedProcessRunner* process_runner,
85 Firewall* firewall,
86 ioctl_t ioctl_hook)
87 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +090088 CHECK(process_runner_);
89}
90
Garrick Evans260ff302019-07-25 11:22:50 +090091MinijailedProcessRunner& Datapath::runner() const {
92 return *process_runner_;
93}
94
Hugo Benichibf811c62020-09-07 17:30:45 +090095void Datapath::Start() {
96 // Enable IPv4 packet forwarding
97 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
98 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
99 << " Guest connectivity will not work correctly.";
100
101 // Limit local port range: Android owns 47104-61000.
102 // TODO(garrick): The original history behind this tweak is gone. Some
103 // investigation is needed to see if it is still applicable.
104 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
105 "32768 47103") != 0)
106 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
107 << " apps may not work correctly.";
108
109 // Enable IPv6 packet forwarding
110 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
111 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
112 << " IPv6 functionality may be broken.";
113
114 if (!AddSNATMarkRules())
115 LOG(ERROR) << "Failed to install SNAT mark rules."
116 << " Guest connectivity may be broken.";
117
Hugo Benichi58125d32020-09-09 11:25:45 +0900118 // Create a FORWARD ACCEPT rule for connections already established.
119 if (process_runner_->iptables(
120 "filter", {"-A", "FORWARD", "-m", "state", "--state",
121 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900122 LOG(ERROR) << "Failed to install forwarding rule for established"
123 << " connections.";
124
125 // chromium:898210: Drop any locally originated traffic that would exit a
126 // physical interface with a source IPv4 address from the subnet of IPs used
127 // for VMs, containers, and connected namespaces This is needed to prevent
128 // packets leaking with an incorrect src IP when a local process binds to the
129 // wrong interface.
130 for (const auto& oif : kPhysicalIfnamePrefixes) {
131 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
132 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
133 << kGuestIPv4Subnet << " exiting " << oif;
134 }
135
136 if (!AddOutboundIPv4SNATMark("vmtap+"))
137 LOG(ERROR) << "Failed to set up NAT for TAP devices."
138 << " Guest connectivity may be broken.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900139
Taoyu Li78f0c9a2020-12-25 22:58:26 +0900140 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
141 // wrongly cause neighbor discovery icmpv6 packets to be dropped. Add these
142 // rules to bypass connmark rule for those packets.
143 for (const auto& type : kNeighborDiscoveryTypes) {
144 if (!ModifyIptables(IpFamily::IPv6, "mangle",
145 {"-A", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
146 "-j", "ACCEPT", "-w"}))
147 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
148 << " packets";
149 }
150
Hugo Benichi2a940542020-10-26 18:50:49 +0900151 // Applies the routing tag saved in conntrack for any established connection
152 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900153 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
154 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900155 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
156
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900157 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
158 // tag and tagging the local traffic that should be routed through a VPN.
159 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyLocalSourceMarkChain))
160 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
161 << " mangle chain";
162 // Ensure that the chain is empty if patchpanel is restarting after a crash.
163 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyLocalSourceMarkChain))
164 LOG(ERROR) << "Failed to flush " << kApplyLocalSourceMarkChain
165 << " mangle chain";
166 if (!ModifyIptables(IpFamily::Dual, "mangle",
167 {"-A", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
168 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
169 << " to mangle OUTPUT";
170 // Create rules for tagging local sources with the source tag and the vpn
171 // policy tag.
172 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900173 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900174 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
175 << " in " << kApplyLocalSourceMarkChain;
176 }
177 // Finally add a catch-all rule for tagging any remaining local sources with
178 // the SYSTEM source tag
179 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
180 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
181
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900182 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
183 // traffic that should be routed through a VPN.
184 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyVpnMarkChain))
185 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
186 // Ensure that the chain is empty if patchpanel is restarting after a crash.
187 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyVpnMarkChain))
188 LOG(ERROR) << "Failed to flush " << kApplyVpnMarkChain << " mangle chain";
189 // All local outgoing traffic eligible to VPN routing should traverse the VPN
190 // marking chain.
191 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", "" /*iif*/, kFwmarkRouteOnVpn,
192 kFwmarkVpnMask))
193 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
194 // Any traffic that already has a routing tag applied is accepted.
195 if (!ModifyIptables(
196 IpFamily::Dual, "mangle",
197 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
198 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
199 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
200 "connections";
Hugo Benichibf811c62020-09-07 17:30:45 +0900201}
202
203void Datapath::Stop() {
204 RemoveOutboundIPv4SNATMark("vmtap+");
Hugo Benichi58125d32020-09-09 11:25:45 +0900205 process_runner_->iptables("filter",
206 {"-D", "FORWARD", "-m", "state", "--state",
207 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"});
Hugo Benichibf811c62020-09-07 17:30:45 +0900208 RemoveSNATMarkRules();
209 for (const auto& oif : kPhysicalIfnamePrefixes)
210 RemoveSourceIPv4DropRule(oif, kGuestIPv4Subnet);
211
212 // Restore original local port range.
213 // TODO(garrick): The original history behind this tweak is gone. Some
214 // investigation is needed to see if it is still applicable.
215 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
216 "32768 61000") != 0)
217 LOG(ERROR) << "Failed to restore local port range";
218
219 // Disable packet forwarding
220 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
221 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
222
223 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
224 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900225
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900226 // Detach the VPN marking mangle chain
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900227 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-D", "" /*iif*/, kFwmarkRouteOnVpn,
228 kFwmarkVpnMask))
229 LOG(ERROR)
230 << "Failed to remove from mangle OUTPUT chain jump rule to VPN chain";
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900231
232 // Detach apply_local_source_mark from mangle PREROUTING
233 if (!ModifyIptables(IpFamily::Dual, "mangle",
234 {"-D", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
235 LOG(ERROR) << "Failed to detach " << kApplyLocalSourceMarkChain
236 << " from mangle OUTPUT";
237
Hugo Benichi2a940542020-10-26 18:50:49 +0900238 // Stops applying routing tags saved in conntrack for sockets created in the
239 // host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900240 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-D", "" /*iif*/,
241 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900242 LOG(ERROR) << "Failed to remove OUTPUT CONNMARK restore rule";
243
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900244 // Delete the mangle chains
245 for (const auto* chain : {kApplyLocalSourceMarkChain, kApplyVpnMarkChain}) {
246 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", chain))
247 LOG(ERROR) << "Failed to flush " << chain << " mangle chain";
248
249 if (!ModifyChain(IpFamily::Dual, "mangle", "-X", chain))
250 LOG(ERROR) << "Failed to delete " << chain << " mangle chain";
251 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900252}
253
Hugo Benichi33860d72020-07-09 16:34:01 +0900254bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
255 // Try first to delete any netns with name |netns_name| in case patchpanel
256 // did not exit cleanly.
257 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
258 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
259 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
260}
261
262bool Datapath::NetnsDeleteName(const std::string& netns_name) {
263 return process_runner_->ip_netns_delete(netns_name) == 0;
264}
265
Garrick Evans8a949dc2019-07-18 16:17:53 +0900266bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900267 uint32_t ipv4_addr,
268 uint32_t ipv4_prefix_len) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900269 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900270 if (process_runner_->brctl("addbr", {ifname}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900271 return false;
272 }
273
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900274 if (process_runner_->ip(
275 "addr", "add",
276 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
277 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
278 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900279 RemoveBridge(ifname);
280 return false;
281 }
282
283 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900284 RemoveBridge(ifname);
285 return false;
286 }
287
288 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900289 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900290 RemoveBridge(ifname);
291 return false;
292 }
293
294 return true;
295}
296
297void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900298 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900299 process_runner_->ip("link", "set", {ifname, "down"});
Garrick Evans8e8e3472020-01-23 14:03:50 +0900300 process_runner_->brctl("delbr", {ifname});
Garrick Evans8a949dc2019-07-18 16:17:53 +0900301}
302
Garrick Evans621ed262019-11-13 12:28:43 +0900303bool Datapath::AddToBridge(const std::string& br_ifname,
304 const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900305 return (process_runner_->brctl("addif", {br_ifname, ifname}) == 0);
Garrick Evans621ed262019-11-13 12:28:43 +0900306}
307
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900308std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900309 const MacAddress* mac_addr,
310 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900311 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900312 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
313 if (!dev.is_valid()) {
314 PLOG(ERROR) << "Failed to open " << kTunDev;
315 return "";
316 }
317
318 struct ifreq ifr;
319 memset(&ifr, 0, sizeof(ifr));
320 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
321 sizeof(ifr.ifr_name));
322 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
323
324 // If a template was given as the name, ifr_name will be updated with the
325 // actual interface name.
326 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900327 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900328 return "";
329 }
330 const char* ifname = ifr.ifr_name;
331
332 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900333 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900334 return "";
335 }
336
Garrick Evans4f9f5572019-11-26 10:25:16 +0900337 if (!user.empty()) {
338 uid_t uid = -1;
339 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
340 PLOG(ERROR) << "Unable to look up UID for " << user;
341 RemoveTAP(ifname);
342 return "";
343 }
344 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
345 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
346 << ifname;
347 RemoveTAP(ifname);
348 return "";
349 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900350 }
351
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900352 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900353 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
354 if (!sock.is_valid()) {
355 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900356 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900357 RemoveTAP(ifname);
358 return "";
359 }
360
Garrick Evans621ed262019-11-13 12:28:43 +0900361 if (ipv4_addr) {
362 struct sockaddr_in* addr =
363 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
364 addr->sin_family = AF_INET;
365 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
366 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
367 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
368 << " {" << ipv4_addr->ToCidrString() << "}";
369 RemoveTAP(ifname);
370 return "";
371 }
372
373 struct sockaddr_in* netmask =
374 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
375 netmask->sin_family = AF_INET;
376 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
377 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
378 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
379 << " {" << ipv4_addr->ToCidrString() << "}";
380 RemoveTAP(ifname);
381 return "";
382 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900383 }
384
Garrick Evans621ed262019-11-13 12:28:43 +0900385 if (mac_addr) {
386 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
387 hwaddr->sa_family = ARPHRD_ETHER;
388 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
389 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
390 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
391 << " {" << MacAddressToString(*mac_addr) << "}";
392 RemoveTAP(ifname);
393 return "";
394 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900395 }
396
397 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900398 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900399 RemoveTAP(ifname);
400 return "";
401 }
402
403 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
404 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900405 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900406 RemoveTAP(ifname);
407 return "";
408 }
409
410 return ifname;
411}
412
413void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900414 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900415}
416
Hugo Benichi33860d72020-07-09 16:34:01 +0900417bool Datapath::ConnectVethPair(pid_t netns_pid,
418 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900419 const std::string& veth_ifname,
420 const std::string& peer_ifname,
421 const MacAddress& remote_mac_addr,
422 uint32_t remote_ipv4_addr,
423 uint32_t remote_ipv4_prefix_len,
424 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900425 // Set up the virtual pair across the current namespace and |netns_name|.
426 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
427 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
428 << peer_ifname;
429 return false;
430 }
431
432 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900433 {
Hugo Benichi33860d72020-07-09 16:34:01 +0900434 ScopedNS ns(netns_pid);
435 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900436 LOG(ERROR)
437 << "Cannot create virtual link -- invalid container namespace?";
438 return false;
439 }
440
Hugo Benichi76675592020-04-08 14:29:57 +0900441 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
442 remote_ipv4_prefix_len, true /* link up */,
443 remote_multicast_flag)) {
444 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
445 RemoveInterface(peer_ifname);
446 return false;
447 }
448 }
449
Hugo Benichi76675592020-04-08 14:29:57 +0900450 if (!ToggleInterface(veth_ifname, true /*up*/)) {
451 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
452 RemoveInterface(veth_ifname);
453 return false;
454 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900455
Hugo Benichi76675592020-04-08 14:29:57 +0900456 return true;
457}
458
Hugo Benichi33860d72020-07-09 16:34:01 +0900459bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
460 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900461 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900462 return process_runner_->ip("link", "add",
463 {veth_ifname, "type", "veth", "peer", "name",
464 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900465}
Garrick Evans54861622019-07-19 09:05:09 +0900466
Garrick Evans2470caa2020-03-04 14:15:41 +0900467bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
468 const std::string link = up ? "up" : "down";
469 return process_runner_->ip("link", "set", {ifname, link}) == 0;
470}
Garrick Evans54861622019-07-19 09:05:09 +0900471
Garrick Evans2470caa2020-03-04 14:15:41 +0900472bool Datapath::ConfigureInterface(const std::string& ifname,
473 const MacAddress& mac_addr,
474 uint32_t ipv4_addr,
475 uint32_t ipv4_prefix_len,
476 bool up,
477 bool enable_multicast) {
478 const std::string link = up ? "up" : "down";
479 const std::string multicast = enable_multicast ? "on" : "off";
480 return (process_runner_->ip(
481 "addr", "add",
482 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
483 IPv4AddressToString(
484 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
485 "dev", ifname}) == 0) &&
486 (process_runner_->ip("link", "set",
487 {
488 "dev",
489 ifname,
490 link,
491 "addr",
492 MacAddressToString(mac_addr),
493 "multicast",
494 multicast,
495 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900496}
497
498void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900499 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900500}
501
Hugo Benichi321f23b2020-09-25 15:42:05 +0900502bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
503 const std::string& src_ip) {
504 return process_runner_->iptables("filter", {"-I", "OUTPUT", "-o", oif, "-s",
505 src_ip, "-j", "DROP", "-w"}) == 0;
506}
507
508bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
509 const std::string& src_ip) {
510 return process_runner_->iptables("filter", {"-D", "OUTPUT", "-o", oif, "-s",
511 src_ip, "-j", "DROP", "-w"}) == 0;
512}
513
Hugo Benichifcf81022020-12-04 11:01:37 +0900514bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900515 // Veth interface configuration and client routing configuration:
516 // - attach a name to the client namespace.
517 // - create veth pair across the current namespace and the client namespace.
518 // - configure IPv4 address on remote veth inside client namespace.
519 // - configure IPv4 address on local veth inside host namespace.
520 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900521 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
522 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
523 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900524 return false;
525 }
526
Hugo Benichifcf81022020-12-04 11:01:37 +0900527 if (!ConnectVethPair(
528 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
529 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
530 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900531 LOG(ERROR) << "Failed to create veth pair for"
532 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900533 << nsinfo.pid;
534 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900535 return false;
536 }
537
Hugo Benichifcf81022020-12-04 11:01:37 +0900538 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
539 nsinfo.peer_subnet->AddressAtOffset(0),
540 nsinfo.peer_subnet->PrefixLength(),
541 true /* link up */, false /* enable_multicast */)) {
542 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
543 RemoveInterface(nsinfo.host_ifname);
544 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900545 return false;
546 }
547
548 {
Hugo Benichifcf81022020-12-04 11:01:37 +0900549 ScopedNS ns(nsinfo.pid);
550 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
551 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
552 RemoveInterface(nsinfo.host_ifname);
553 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900554 return false;
555 }
556
Hugo Benichifcf81022020-12-04 11:01:37 +0900557 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
558 INADDR_ANY)) {
559 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
560 << " inside namespace pid " << nsinfo.pid;
561 RemoveInterface(nsinfo.host_ifname);
562 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900563 return false;
564 }
565 }
566
567 // Host namespace routing configuration
568 // - ingress: add route to client subnet via |host_ifname|.
569 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
570 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
571 // Note that by default unsolicited ingress traffic is not forwarded to the
572 // client namespace unless the client specifically set port forwarding
573 // through permission_broker DBus APIs.
574 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
575 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900576 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
577 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
578 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900579 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900580 RemoveInterface(nsinfo.host_ifname);
581 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900582 return false;
583 }
584
Hugo Benichi7c342672020-09-08 09:18:14 +0900585 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900586 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900587 LOG(ERROR) << "Failed to set SNAT for traffic"
588 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900589 << nsinfo.host_ifname;
590 RemoveInterface(nsinfo.host_ifname);
591 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
592 nsinfo.peer_subnet->BaseAddress(), netmask);
593 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
594 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900595 return false;
596 }
597
Hugo Benichi93306e52020-12-04 16:08:00 +0900598 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
599 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
600 nsinfo.route_on_vpn);
601
Hugo Benichi7c342672020-09-08 09:18:14 +0900602 return true;
603}
604
Hugo Benichifcf81022020-12-04 11:01:37 +0900605void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900606 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
607 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
608 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900609 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900610 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
611 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
612 nsinfo.peer_subnet->BaseAddress(),
613 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
614 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900615}
616
Hugo Benichi8d622b52020-08-13 15:24:12 +0900617void Datapath::StartRoutingDevice(const std::string& ext_ifname,
618 const std::string& int_ifname,
619 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900620 TrafficSource source,
621 bool route_on_vpn) {
622 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900623 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900624 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
625 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
626 << "->" << int_ifname;
627
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900628 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900629 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
630 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900631
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900632 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900633 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
634 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900635
Hugo Benichi2a940542020-10-26 18:50:49 +0900636 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
637 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
638 << source << " for " << int_ifname;
639
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900640 if (!ext_ifname.empty()) {
641 // If |ext_ifname| is not null, mark egress traffic with the
642 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi2a940542020-10-26 18:50:49 +0900643 if (!ModifyFwmarkRoutingTag("PREROUTING", "-A", ext_ifname, int_ifname))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900644 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
645 << ext_ifname << "<-" << int_ifname;
646 } else {
647 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
648 // PREROUTING to apply any fwmark routing tag saved for the current
649 // connection, and rely on implicit routing to the default logical network
650 // otherwise.
Hugo Benichi1af52392020-11-27 18:09:32 +0900651 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname,
652 kFwmarkRoutingMask))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900653 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
654 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900655
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900656 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900657 // default network is eligible to be routed through a VPN if |route_on_vpn|
658 // is true.
659 if (route_on_vpn &&
660 !ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900661 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900662 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900663}
664
665void Datapath::StopRoutingDevice(const std::string& ext_ifname,
666 const std::string& int_ifname,
667 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900668 TrafficSource source,
669 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900670 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900671 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900672 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
673 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900674 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900675 if (!ext_ifname.empty()) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900676 ModifyFwmarkRoutingTag("PREROUTING", "-D", ext_ifname, int_ifname);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900677 } else {
Hugo Benichi1af52392020-11-27 18:09:32 +0900678 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname,
679 kFwmarkRoutingMask);
Hugo Benichi93306e52020-12-04 16:08:00 +0900680 if (route_on_vpn)
681 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900682 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900683}
684
Garrick Evansf0ab7132019-06-18 14:50:42 +0900685bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
686 const std::string& ipv4_addr) {
687 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900688 if (process_runner_->iptables(
689 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
690 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900691 return false;
692
693 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900694 if (process_runner_->iptables(
695 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
696 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900697 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
698 return false;
699 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900700 if (process_runner_->iptables(
701 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
702 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900703 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
704 return false;
705 }
706
707 return true;
708}
709
710void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
711 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900712 process_runner_->iptables(
713 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
714 "--to-destination", ipv4_addr, "-w"});
715 process_runner_->iptables(
716 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
717 "--to-destination", ipv4_addr, "-w"});
718 process_runner_->iptables(
719 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
720 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900721}
722
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900723// TODO(b/161507671) Stop relying on the traffic fwmark 1/1 once forwarded
724// egress traffic is routed through the fwmark routing tag.
Garrick Evansd291af62020-05-25 10:39:06 +0900725bool Datapath::AddSNATMarkRules() {
Taoyu Li79871c92020-07-02 16:09:39 +0900726 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
727 // need to be explicitly dropped.
728 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900729 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
Taoyu Li79871c92020-07-02 16:09:39 +0900730 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0) {
731 return false;
732 }
Garrick Evansd291af62020-05-25 10:39:06 +0900733 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900734 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900735 "ACCEPT", "-w"}) != 0) {
736 return false;
737 }
738 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900739 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900740 "MASQUERADE", "-w"}) != 0) {
741 RemoveSNATMarkRules();
742 return false;
743 }
744 return true;
745}
746
747void Datapath::RemoveSNATMarkRules() {
748 process_runner_->iptables("nat", {"-D", "POSTROUTING", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900749 "1/1", "-j", "MASQUERADE", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900750 process_runner_->iptables("filter", {"-D", "FORWARD", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900751 "1/1", "-j", "ACCEPT", "-w"});
Taoyu Li79871c92020-07-02 16:09:39 +0900752 process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900753 "filter", {"-D", "FORWARD", "-m", "mark", "--mark", "1/1", "-m", "state",
Taoyu Li79871c92020-07-02 16:09:39 +0900754 "--state", "INVALID", "-j", "DROP", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900755}
756
Hugo Benichie8758b52020-04-03 14:49:01 +0900757bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
758 return process_runner_->iptables(
759 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900760 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900761}
762
763void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
764 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900765 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900766}
767
Garrick Evans664a82f2019-12-17 12:18:05 +0900768bool Datapath::MaskInterfaceFlags(const std::string& ifname,
769 uint16_t on,
770 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900771 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
772 if (!sock.is_valid()) {
773 PLOG(ERROR) << "Failed to create control socket";
774 return false;
775 }
776 ifreq ifr;
777 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
778 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
779 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
780 return false;
781 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900782 ifr.ifr_flags |= on;
783 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900784 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900785 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
786 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900787 return false;
788 }
789 return true;
790}
791
Garrick Evans260ff302019-07-25 11:22:50 +0900792bool Datapath::AddIPv6HostRoute(const std::string& ifname,
793 const std::string& ipv6_addr,
794 int ipv6_prefix_len) {
795 std::string ipv6_addr_cidr =
796 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
797
Garrick Evans8e8e3472020-01-23 14:03:50 +0900798 return process_runner_->ip6("route", "replace",
799 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900800}
801
802void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
803 const std::string& ipv6_addr,
804 int ipv6_prefix_len) {
805 std::string ipv6_addr_cidr =
806 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
807
Garrick Evans8e8e3472020-01-23 14:03:50 +0900808 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900809}
810
Taoyu Lia0727dc2020-09-24 19:54:59 +0900811bool Datapath::AddIPv6Address(const std::string& ifname,
812 const std::string& ipv6_addr) {
813 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900814}
815
Taoyu Lia0727dc2020-09-24 19:54:59 +0900816void Datapath::RemoveIPv6Address(const std::string& ifname,
817 const std::string& ipv6_addr) {
818 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900819}
820
Hugo Benichi76be34a2020-08-26 22:35:54 +0900821void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi1af52392020-11-27 18:09:32 +0900822 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi76be34a2020-08-26 22:35:54 +0900823 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
824 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900825 // Save in CONNMARK the source tag for egress traffic of this connection.
826 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
827 kFwmarkAllSourcesMask))
828 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
829 "source tag on "
830 << ext_ifname;
831 // Restore from CONNMARK the source tag for ingress traffic of this connection
832 // (returned traffic).
833 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
834 kFwmarkAllSourcesMask))
835 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
836 "traffic received on "
837 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900838}
839
840void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
841 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
842 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900843 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
844 kFwmarkAllSourcesMask))
845 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
846 "fwmark source tag on "
847 << ext_ifname;
848 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
849 kFwmarkAllSourcesMask))
850 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
851 "traffic received on "
852 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900853}
854
Hugo Benichi2a940542020-10-26 18:50:49 +0900855void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
856 StartConnectionPinning(vpn_ifname);
857 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", vpn_ifname, ""))
858 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +0900859 if (vpn_ifname != kArcBridge)
860 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
861 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi2a940542020-10-26 18:50:49 +0900862}
863
864void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900865 if (vpn_ifname != kArcBridge)
866 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
867 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi2a940542020-10-26 18:50:49 +0900868 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", vpn_ifname, ""))
869 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
870 StopConnectionPinning(vpn_ifname);
871}
872
Hugo Benichi76be34a2020-08-26 22:35:54 +0900873bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
874 const std::string& op,
875 const std::string& oif) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900876 int ifindex = FindIfIndex(oif);
877 if (ifindex == 0) {
878 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
879 return false;
880 }
881
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900882 return ModifyConnmarkSet(family, "POSTROUTING", op, oif,
883 Fwmark::FromIfIndex(ifindex), kFwmarkRoutingMask);
884}
885
886bool Datapath::ModifyConnmarkSet(IpFamily family,
887 const std::string& chain,
888 const std::string& op,
889 const std::string& oif,
890 Fwmark mark,
891 Fwmark mask) {
892 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
893 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
894 return false;
895 }
896
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900897 std::vector<std::string> args = {op, chain};
898 if (!oif.empty()) {
899 args.push_back("-o");
900 args.push_back(oif);
901 }
902 args.push_back("-j");
903 args.push_back("CONNMARK");
904 args.push_back("--set-mark");
905 args.push_back(mark.ToString() + "/" + mask.ToString());
906 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +0900907
Hugo Benichi58f264a2020-10-16 18:16:05 +0900908 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +0900909}
910
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900911bool Datapath::ModifyConnmarkRestore(IpFamily family,
912 const std::string& chain,
913 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +0900914 const std::string& iif,
915 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900916 if (chain != "OUTPUT" && (chain != "PREROUTING" || iif.empty())) {
917 LOG(ERROR) << "Invalid arguments chain=" << chain << " iif=" << iif;
918 return false;
919 }
920
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900921 std::vector<std::string> args = {op, chain};
922 if (!iif.empty()) {
923 args.push_back("-i");
924 args.push_back(iif);
925 }
926 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +0900927 mask.ToString(), "-w"});
928 return ModifyIptables(family, "mangle", args);
929}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900930
Hugo Benichi1af52392020-11-27 18:09:32 +0900931bool Datapath::ModifyConnmarkSave(IpFamily family,
932 const std::string& chain,
933 const std::string& op,
934 const std::string& oif,
935 Fwmark mask) {
936 std::vector<std::string> args = {op, chain};
937 if (!oif.empty()) {
938 args.push_back("-o");
939 args.push_back(oif);
940 }
941 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
942 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +0900943 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900944}
945
Hugo Benichi2a940542020-10-26 18:50:49 +0900946bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
947 const std::string& op,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900948 const std::string& ext_ifname,
949 const std::string& int_ifname) {
950 int ifindex = FindIfIndex(ext_ifname);
951 if (ifindex == 0) {
952 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
953 return false;
954 }
955
Hugo Benichi2a940542020-10-26 18:50:49 +0900956 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900957 0 /*classid*/, Fwmark::FromIfIndex(ifindex),
958 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900959}
960
Hugo Benichi9be19b12020-08-14 15:33:40 +0900961bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
962 const std::string& iif,
963 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900964 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900965 0 /*classid*/, Fwmark::FromSource(source),
966 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900967}
968
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900969bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
970 TrafficSource source) {
971 std::vector<std::string> args = {"-A",
972 kApplyLocalSourceMarkChain,
973 "-m",
974 "mark",
975 "--mark",
976 "0x0/" + kFwmarkAllSourcesMask.ToString(),
977 "-j",
978 "MARK",
979 "--set-mark",
980 Fwmark::FromSource(source).ToString() + "/" +
981 kFwmarkAllSourcesMask.ToString(),
982 "-w"};
983 return ModifyIptables(IpFamily::Dual, "mangle", args);
984}
Hugo Benichi9be19b12020-08-14 15:33:40 +0900985
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900986bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
987 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900988 if (std::string(source.uid_name).empty() && source.classid == 0)
989 return false;
990
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900991 Fwmark mark = Fwmark::FromSource(source.source_type);
992 if (source.is_on_vpn)
993 mark = mark | kFwmarkRouteOnVpn;
994
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900995 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
996 "" /*iif*/, source.uid_name, source.classid, mark,
997 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900998}
999
1000bool Datapath::ModifyFwmark(IpFamily family,
1001 const std::string& chain,
1002 const std::string& op,
1003 const std::string& iif,
1004 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001005 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001006 Fwmark mark,
1007 Fwmark mask,
1008 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001009 std::vector<std::string> args = {op, chain};
1010 if (!iif.empty()) {
1011 args.push_back("-i");
1012 args.push_back(iif);
1013 }
1014 if (!uid_name.empty()) {
1015 args.push_back("-m");
1016 args.push_back("owner");
1017 args.push_back("--uid-owner");
1018 args.push_back(uid_name);
1019 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001020 if (classid != 0) {
1021 args.push_back("-m");
1022 args.push_back("cgroup");
1023 args.push_back("--cgroup");
1024 args.push_back(base::StringPrintf("0x%08x", classid));
1025 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001026 args.push_back("-j");
1027 args.push_back("MARK");
1028 args.push_back("--set-mark");
1029 args.push_back(mark.ToString() + "/" + mask.ToString());
1030 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001031
Hugo Benichi58f264a2020-10-16 18:16:05 +09001032 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001033}
1034
Hugo Benichid82d8832020-08-14 10:05:03 +09001035bool Datapath::ModifyIpForwarding(IpFamily family,
1036 const std::string& op,
1037 const std::string& iif,
1038 const std::string& oif,
1039 bool log_failures) {
1040 if (iif.empty() && oif.empty()) {
1041 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1042 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001043 return false;
1044 }
1045
Hugo Benichid82d8832020-08-14 10:05:03 +09001046 std::vector<std::string> args = {op, "FORWARD"};
1047 if (!iif.empty()) {
1048 args.push_back("-i");
1049 args.push_back(iif);
1050 }
1051 if (!oif.empty()) {
1052 args.push_back("-o");
1053 args.push_back(oif);
1054 }
1055 args.push_back("-j");
1056 args.push_back("ACCEPT");
1057 args.push_back("-w");
1058
Hugo Benichi58f264a2020-10-16 18:16:05 +09001059 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001060}
1061
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001062bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1063 const std::string& op,
1064 const std::string& iif,
1065 Fwmark mark,
1066 Fwmark mask) {
1067 std::vector<std::string> args = {op, chain};
1068 if (!iif.empty()) {
1069 args.push_back("-i");
1070 args.push_back(iif);
1071 }
1072 if (mark.Value() != 0 && mask.Value() != 0) {
1073 args.push_back("-m");
1074 args.push_back("mark");
1075 args.push_back("--mark");
1076 args.push_back(mark.ToString() + "/" + mask.ToString());
1077 }
1078 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1079 return ModifyIptables(IpFamily::Dual, "mangle", args);
1080}
1081
1082bool Datapath::ModifyChain(IpFamily family,
1083 const std::string& table,
1084 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001085 const std::string& chain,
1086 bool log_failures) {
1087 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001088}
1089
1090bool Datapath::ModifyIptables(IpFamily family,
1091 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001092 const std::vector<std::string>& argv,
1093 bool log_failures) {
1094 switch (family) {
1095 case IPv4:
1096 case IPv6:
1097 case Dual:
1098 break;
1099 default:
1100 LOG(ERROR) << "Could not execute iptables command " << table
1101 << base::JoinString(argv, " ") << ": incorrect IP family "
1102 << family;
1103 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001104 }
1105
1106 bool success = true;
1107 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001108 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001109 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001110 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001111 return success;
1112}
1113
Hugo Benichid82d8832020-08-14 10:05:03 +09001114bool Datapath::StartIpForwarding(IpFamily family,
1115 const std::string& iif,
1116 const std::string& oif) {
1117 return ModifyIpForwarding(family, "-A", iif, oif);
1118}
1119
1120bool Datapath::StopIpForwarding(IpFamily family,
1121 const std::string& iif,
1122 const std::string& oif) {
1123 return ModifyIpForwarding(family, "-D", iif, oif);
1124}
1125
1126bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1127 const std::string& ifname2) {
1128 // Only start Ipv6 forwarding if -C returns false and it had not been
1129 // started yet.
1130 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1131 false /*log_failures*/) &&
1132 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1133 return false;
1134 }
1135
1136 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1137 false /*log_failures*/) &&
1138 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001139 RemoveIPv6Forwarding(ifname1, ifname2);
1140 return false;
1141 }
1142
1143 return true;
1144}
1145
1146void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1147 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001148 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1149 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001150}
1151
Garrick Evans3d97a392020-02-21 15:24:37 +09001152bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1153 uint32_t addr,
1154 uint32_t netmask) {
1155 struct rtentry route;
1156 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001157 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1158 SetSockaddrIn(&route.rt_dst, addr & netmask);
1159 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001160 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001161 return ModifyRtentry(SIOCADDRT, &route);
1162}
Garrick Evans3d97a392020-02-21 15:24:37 +09001163
Hugo Benichie8758b52020-04-03 14:49:01 +09001164bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1165 uint32_t addr,
1166 uint32_t netmask) {
1167 struct rtentry route;
1168 memset(&route, 0, sizeof(route));
1169 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1170 SetSockaddrIn(&route.rt_dst, addr & netmask);
1171 SetSockaddrIn(&route.rt_genmask, netmask);
1172 route.rt_flags = RTF_UP | RTF_GATEWAY;
1173 return ModifyRtentry(SIOCDELRT, &route);
1174}
1175
1176bool Datapath::AddIPv4Route(const std::string& ifname,
1177 uint32_t addr,
1178 uint32_t netmask) {
1179 struct rtentry route;
1180 memset(&route, 0, sizeof(route));
1181 SetSockaddrIn(&route.rt_dst, addr & netmask);
1182 SetSockaddrIn(&route.rt_genmask, netmask);
1183 char rt_dev[IFNAMSIZ];
1184 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1185 rt_dev[IFNAMSIZ - 1] = '\0';
1186 route.rt_dev = rt_dev;
1187 route.rt_flags = RTF_UP | RTF_GATEWAY;
1188 return ModifyRtentry(SIOCADDRT, &route);
1189}
1190
1191bool Datapath::DeleteIPv4Route(const std::string& ifname,
1192 uint32_t addr,
1193 uint32_t netmask) {
1194 struct rtentry route;
1195 memset(&route, 0, sizeof(route));
1196 SetSockaddrIn(&route.rt_dst, addr & netmask);
1197 SetSockaddrIn(&route.rt_genmask, netmask);
1198 char rt_dev[IFNAMSIZ];
1199 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1200 rt_dev[IFNAMSIZ - 1] = '\0';
1201 route.rt_dev = rt_dev;
1202 route.rt_flags = RTF_UP | RTF_GATEWAY;
1203 return ModifyRtentry(SIOCDELRT, &route);
1204}
1205
Taoyu Lia0727dc2020-09-24 19:54:59 +09001206bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001207 DCHECK(route);
1208 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001209 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001210 return false;
1211 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001212 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1213 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001214 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001215 return false;
1216 }
1217 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1218 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001219 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001220 return false;
1221 }
1222 return true;
1223}
1224
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001225bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1226 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1227 kArcAddr, kAdbServerPort, ifname,
1228 kLocalhostAddr, kAdbProxyTcpListenPort);
1229}
1230
1231void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1232 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1233 kArcAddr, kAdbServerPort, ifname,
1234 kLocalhostAddr, kAdbProxyTcpListenPort);
1235}
1236
1237bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1238 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1239 kAdbProxyTcpListenPort, ifname);
1240}
1241
1242void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1243 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1244 kAdbProxyTcpListenPort, ifname);
1245}
1246
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001247void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1248 if_nametoindex_[ifname] = ifindex;
1249}
1250
1251int Datapath::FindIfIndex(const std::string& ifname) {
1252 uint32_t ifindex = if_nametoindex(ifname.c_str());
1253 if (ifindex > 0) {
1254 if_nametoindex_[ifname] = ifindex;
1255 return ifindex;
1256 }
1257
1258 const auto it = if_nametoindex_.find(ifname);
1259 if (it != if_nametoindex_.end())
1260 return it->second;
1261
1262 return 0;
1263}
1264
Hugo Benichifcf81022020-12-04 11:01:37 +09001265std::ostream& operator<<(std::ostream& stream,
1266 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001267 stream << "{ pid: " << nsinfo.pid
1268 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001269 if (!nsinfo.outbound_ifname.empty()) {
1270 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1271 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001272 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1273 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001274 << ", peer_ifname: " << nsinfo.peer_ifname
1275 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1276 return stream;
1277}
1278
Garrick Evans3388a032020-03-24 11:25:55 +09001279} // namespace patchpanel