blob: 0468533e2425d3ed29bb4063c6dccf970b36eaf3 [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) {
Hugo Benichi891275e2020-12-16 10:35:34 +0900856 if (process_runner_->iptables("nat", {"-A", "POSTROUTING", "-o", vpn_ifname,
857 "-j", "MASQUERADE", "-w"}) != 0)
858 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900859 StartConnectionPinning(vpn_ifname);
860 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", vpn_ifname, ""))
861 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +0900862 if (vpn_ifname != kArcBridge)
863 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
864 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi2a940542020-10-26 18:50:49 +0900865}
866
867void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900868 if (vpn_ifname != kArcBridge)
869 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
870 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi2a940542020-10-26 18:50:49 +0900871 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", vpn_ifname, ""))
872 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
873 StopConnectionPinning(vpn_ifname);
Hugo Benichi891275e2020-12-16 10:35:34 +0900874 if (process_runner_->iptables("nat", {"-D", "POSTROUTING", "-o", vpn_ifname,
875 "-j", "MASQUERADE", "-w"}) != 0)
876 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900877}
878
Hugo Benichi76be34a2020-08-26 22:35:54 +0900879bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
880 const std::string& op,
881 const std::string& oif) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900882 int ifindex = FindIfIndex(oif);
883 if (ifindex == 0) {
884 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
885 return false;
886 }
887
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900888 return ModifyConnmarkSet(family, "POSTROUTING", op, oif,
889 Fwmark::FromIfIndex(ifindex), kFwmarkRoutingMask);
890}
891
892bool Datapath::ModifyConnmarkSet(IpFamily family,
893 const std::string& chain,
894 const std::string& op,
895 const std::string& oif,
896 Fwmark mark,
897 Fwmark mask) {
898 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
899 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
900 return false;
901 }
902
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900903 std::vector<std::string> args = {op, chain};
904 if (!oif.empty()) {
905 args.push_back("-o");
906 args.push_back(oif);
907 }
908 args.push_back("-j");
909 args.push_back("CONNMARK");
910 args.push_back("--set-mark");
911 args.push_back(mark.ToString() + "/" + mask.ToString());
912 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +0900913
Hugo Benichi58f264a2020-10-16 18:16:05 +0900914 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +0900915}
916
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900917bool Datapath::ModifyConnmarkRestore(IpFamily family,
918 const std::string& chain,
919 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +0900920 const std::string& iif,
921 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900922 if (chain != "OUTPUT" && (chain != "PREROUTING" || iif.empty())) {
923 LOG(ERROR) << "Invalid arguments chain=" << chain << " iif=" << iif;
924 return false;
925 }
926
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900927 std::vector<std::string> args = {op, chain};
928 if (!iif.empty()) {
929 args.push_back("-i");
930 args.push_back(iif);
931 }
932 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +0900933 mask.ToString(), "-w"});
934 return ModifyIptables(family, "mangle", args);
935}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900936
Hugo Benichi1af52392020-11-27 18:09:32 +0900937bool Datapath::ModifyConnmarkSave(IpFamily family,
938 const std::string& chain,
939 const std::string& op,
940 const std::string& oif,
941 Fwmark mask) {
942 std::vector<std::string> args = {op, chain};
943 if (!oif.empty()) {
944 args.push_back("-o");
945 args.push_back(oif);
946 }
947 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
948 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +0900949 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900950}
951
Hugo Benichi2a940542020-10-26 18:50:49 +0900952bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
953 const std::string& op,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900954 const std::string& ext_ifname,
955 const std::string& int_ifname) {
956 int ifindex = FindIfIndex(ext_ifname);
957 if (ifindex == 0) {
958 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
959 return false;
960 }
961
Hugo Benichi2a940542020-10-26 18:50:49 +0900962 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900963 0 /*classid*/, Fwmark::FromIfIndex(ifindex),
964 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900965}
966
Hugo Benichi9be19b12020-08-14 15:33:40 +0900967bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
968 const std::string& iif,
969 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900970 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900971 0 /*classid*/, Fwmark::FromSource(source),
972 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900973}
974
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900975bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
976 TrafficSource source) {
977 std::vector<std::string> args = {"-A",
978 kApplyLocalSourceMarkChain,
979 "-m",
980 "mark",
981 "--mark",
982 "0x0/" + kFwmarkAllSourcesMask.ToString(),
983 "-j",
984 "MARK",
985 "--set-mark",
986 Fwmark::FromSource(source).ToString() + "/" +
987 kFwmarkAllSourcesMask.ToString(),
988 "-w"};
989 return ModifyIptables(IpFamily::Dual, "mangle", args);
990}
Hugo Benichi9be19b12020-08-14 15:33:40 +0900991
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900992bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
993 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900994 if (std::string(source.uid_name).empty() && source.classid == 0)
995 return false;
996
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900997 Fwmark mark = Fwmark::FromSource(source.source_type);
998 if (source.is_on_vpn)
999 mark = mark | kFwmarkRouteOnVpn;
1000
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001001 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1002 "" /*iif*/, source.uid_name, source.classid, mark,
1003 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001004}
1005
1006bool Datapath::ModifyFwmark(IpFamily family,
1007 const std::string& chain,
1008 const std::string& op,
1009 const std::string& iif,
1010 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001011 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001012 Fwmark mark,
1013 Fwmark mask,
1014 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001015 std::vector<std::string> args = {op, chain};
1016 if (!iif.empty()) {
1017 args.push_back("-i");
1018 args.push_back(iif);
1019 }
1020 if (!uid_name.empty()) {
1021 args.push_back("-m");
1022 args.push_back("owner");
1023 args.push_back("--uid-owner");
1024 args.push_back(uid_name);
1025 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001026 if (classid != 0) {
1027 args.push_back("-m");
1028 args.push_back("cgroup");
1029 args.push_back("--cgroup");
1030 args.push_back(base::StringPrintf("0x%08x", classid));
1031 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001032 args.push_back("-j");
1033 args.push_back("MARK");
1034 args.push_back("--set-mark");
1035 args.push_back(mark.ToString() + "/" + mask.ToString());
1036 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001037
Hugo Benichi58f264a2020-10-16 18:16:05 +09001038 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001039}
1040
Hugo Benichid82d8832020-08-14 10:05:03 +09001041bool Datapath::ModifyIpForwarding(IpFamily family,
1042 const std::string& op,
1043 const std::string& iif,
1044 const std::string& oif,
1045 bool log_failures) {
1046 if (iif.empty() && oif.empty()) {
1047 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1048 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001049 return false;
1050 }
1051
Hugo Benichid82d8832020-08-14 10:05:03 +09001052 std::vector<std::string> args = {op, "FORWARD"};
1053 if (!iif.empty()) {
1054 args.push_back("-i");
1055 args.push_back(iif);
1056 }
1057 if (!oif.empty()) {
1058 args.push_back("-o");
1059 args.push_back(oif);
1060 }
1061 args.push_back("-j");
1062 args.push_back("ACCEPT");
1063 args.push_back("-w");
1064
Hugo Benichi58f264a2020-10-16 18:16:05 +09001065 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001066}
1067
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001068bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1069 const std::string& op,
1070 const std::string& iif,
1071 Fwmark mark,
1072 Fwmark mask) {
1073 std::vector<std::string> args = {op, chain};
1074 if (!iif.empty()) {
1075 args.push_back("-i");
1076 args.push_back(iif);
1077 }
1078 if (mark.Value() != 0 && mask.Value() != 0) {
1079 args.push_back("-m");
1080 args.push_back("mark");
1081 args.push_back("--mark");
1082 args.push_back(mark.ToString() + "/" + mask.ToString());
1083 }
1084 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1085 return ModifyIptables(IpFamily::Dual, "mangle", args);
1086}
1087
1088bool Datapath::ModifyChain(IpFamily family,
1089 const std::string& table,
1090 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001091 const std::string& chain,
1092 bool log_failures) {
1093 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001094}
1095
1096bool Datapath::ModifyIptables(IpFamily family,
1097 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001098 const std::vector<std::string>& argv,
1099 bool log_failures) {
1100 switch (family) {
1101 case IPv4:
1102 case IPv6:
1103 case Dual:
1104 break;
1105 default:
1106 LOG(ERROR) << "Could not execute iptables command " << table
1107 << base::JoinString(argv, " ") << ": incorrect IP family "
1108 << family;
1109 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001110 }
1111
1112 bool success = true;
1113 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001114 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001115 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001116 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001117 return success;
1118}
1119
Hugo Benichid82d8832020-08-14 10:05:03 +09001120bool Datapath::StartIpForwarding(IpFamily family,
1121 const std::string& iif,
1122 const std::string& oif) {
1123 return ModifyIpForwarding(family, "-A", iif, oif);
1124}
1125
1126bool Datapath::StopIpForwarding(IpFamily family,
1127 const std::string& iif,
1128 const std::string& oif) {
1129 return ModifyIpForwarding(family, "-D", iif, oif);
1130}
1131
1132bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1133 const std::string& ifname2) {
1134 // Only start Ipv6 forwarding if -C returns false and it had not been
1135 // started yet.
1136 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1137 false /*log_failures*/) &&
1138 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1139 return false;
1140 }
1141
1142 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1143 false /*log_failures*/) &&
1144 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001145 RemoveIPv6Forwarding(ifname1, ifname2);
1146 return false;
1147 }
1148
1149 return true;
1150}
1151
1152void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1153 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001154 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1155 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001156}
1157
Garrick Evans3d97a392020-02-21 15:24:37 +09001158bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1159 uint32_t addr,
1160 uint32_t netmask) {
1161 struct rtentry route;
1162 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001163 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1164 SetSockaddrIn(&route.rt_dst, addr & netmask);
1165 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001166 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001167 return ModifyRtentry(SIOCADDRT, &route);
1168}
Garrick Evans3d97a392020-02-21 15:24:37 +09001169
Hugo Benichie8758b52020-04-03 14:49:01 +09001170bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1171 uint32_t addr,
1172 uint32_t netmask) {
1173 struct rtentry route;
1174 memset(&route, 0, sizeof(route));
1175 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1176 SetSockaddrIn(&route.rt_dst, addr & netmask);
1177 SetSockaddrIn(&route.rt_genmask, netmask);
1178 route.rt_flags = RTF_UP | RTF_GATEWAY;
1179 return ModifyRtentry(SIOCDELRT, &route);
1180}
1181
1182bool Datapath::AddIPv4Route(const std::string& ifname,
1183 uint32_t addr,
1184 uint32_t netmask) {
1185 struct rtentry route;
1186 memset(&route, 0, sizeof(route));
1187 SetSockaddrIn(&route.rt_dst, addr & netmask);
1188 SetSockaddrIn(&route.rt_genmask, netmask);
1189 char rt_dev[IFNAMSIZ];
1190 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1191 rt_dev[IFNAMSIZ - 1] = '\0';
1192 route.rt_dev = rt_dev;
1193 route.rt_flags = RTF_UP | RTF_GATEWAY;
1194 return ModifyRtentry(SIOCADDRT, &route);
1195}
1196
1197bool Datapath::DeleteIPv4Route(const std::string& ifname,
1198 uint32_t addr,
1199 uint32_t netmask) {
1200 struct rtentry route;
1201 memset(&route, 0, sizeof(route));
1202 SetSockaddrIn(&route.rt_dst, addr & netmask);
1203 SetSockaddrIn(&route.rt_genmask, netmask);
1204 char rt_dev[IFNAMSIZ];
1205 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1206 rt_dev[IFNAMSIZ - 1] = '\0';
1207 route.rt_dev = rt_dev;
1208 route.rt_flags = RTF_UP | RTF_GATEWAY;
1209 return ModifyRtentry(SIOCDELRT, &route);
1210}
1211
Taoyu Lia0727dc2020-09-24 19:54:59 +09001212bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001213 DCHECK(route);
1214 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001215 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001216 return false;
1217 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001218 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1219 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001220 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001221 return false;
1222 }
1223 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1224 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001225 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001226 return false;
1227 }
1228 return true;
1229}
1230
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001231bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1232 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1233 kArcAddr, kAdbServerPort, ifname,
1234 kLocalhostAddr, kAdbProxyTcpListenPort);
1235}
1236
1237void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1238 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1239 kArcAddr, kAdbServerPort, ifname,
1240 kLocalhostAddr, kAdbProxyTcpListenPort);
1241}
1242
1243bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1244 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1245 kAdbProxyTcpListenPort, ifname);
1246}
1247
1248void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1249 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1250 kAdbProxyTcpListenPort, ifname);
1251}
1252
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001253void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1254 if_nametoindex_[ifname] = ifindex;
1255}
1256
1257int Datapath::FindIfIndex(const std::string& ifname) {
1258 uint32_t ifindex = if_nametoindex(ifname.c_str());
1259 if (ifindex > 0) {
1260 if_nametoindex_[ifname] = ifindex;
1261 return ifindex;
1262 }
1263
1264 const auto it = if_nametoindex_.find(ifname);
1265 if (it != if_nametoindex_.end())
1266 return it->second;
1267
1268 return 0;
1269}
1270
Hugo Benichifcf81022020-12-04 11:01:37 +09001271std::ostream& operator<<(std::ostream& stream,
1272 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001273 stream << "{ pid: " << nsinfo.pid
1274 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001275 if (!nsinfo.outbound_ifname.empty()) {
1276 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1277 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001278 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1279 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001280 << ", peer_ifname: " << nsinfo.peer_ifname
1281 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1282 return stream;
1283}
1284
Garrick Evans3388a032020-03-24 11:25:55 +09001285} // namespace patchpanel