blob: fde6603c7ce4913c69aa571c163e3dfa1ad8f537 [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"
Garrick Evans3388a032020-03-24 11:25:55 +090029#include "patchpanel/net_util.h"
30#include "patchpanel/scoped_ns.h"
Garrick Evansc7ae82c2019-09-04 16:25:10 +090031
Garrick Evans3388a032020-03-24 11:25:55 +090032namespace patchpanel {
Garrick Evans54861622019-07-19 09:05:09 +090033
Garrick Evansc7ae82c2019-09-04 16:25:10 +090034namespace {
Hugo Benichi76675592020-04-08 14:29:57 +090035// TODO(hugobenichi) Consolidate this constant definition in a single place.
36constexpr pid_t kTestPID = -2;
Garrick Evansc7ae82c2019-09-04 16:25:10 +090037constexpr char kDefaultIfname[] = "vmtap%d";
38constexpr char kTunDev[] = "/dev/net/tun";
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090039constexpr char kArcAddr[] = "100.115.92.2";
40constexpr char kLocalhostAddr[] = "127.0.0.1";
41constexpr uint16_t kAdbServerPort = 5555;
Hugo Benichie8758b52020-04-03 14:49:01 +090042
Hugo Benichibf811c62020-09-07 17:30:45 +090043// Constants used for dropping locally originated traffic bound to an incorrect
44// source IPv4 address.
45constexpr char kGuestIPv4Subnet[] = "100.115.92.0/23";
46constexpr std::array<const char*, 6> kPhysicalIfnamePrefixes{
47 {"eth+", "wlan+", "mlan+", "usb+", "wwan+", "rmnet+"}};
48
Hugo Benichi3a9162b2020-09-09 15:47:40 +090049constexpr char kApplyLocalSourceMarkChain[] = "apply_local_source_mark";
Hugo Benichi3ef370b2020-11-16 19:07:17 +090050constexpr char kApplyVpnMarkChain[] = "apply_vpn_mark";
51
Hugo Benichi2a940542020-10-26 18:50:49 +090052// Constant fwmark mask for matching local socket traffic that should be routed
53// through a VPN connection. The traffic must not be part of an existing
54// connection and must match exactly the VPN routing intent policy bit.
55const Fwmark kFwmarkVpnMatchingMask = kFwmarkRoutingMask | kFwmarkVpnMask;
56
Garrick Evans8a067562020-05-11 12:47:30 +090057std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
58 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090059 if (n.length() < IFNAMSIZ)
60 return n;
Garrick Evans54861622019-07-19 09:05:09 +090061
Garrick Evans2f581a02020-05-11 10:43:35 +090062 // Best effort attempt to preserve the interface number, assuming it's the
63 // last char in the name.
64 auto c = ifname[ifname.length() - 1];
65 n.resize(IFNAMSIZ - 1);
66 n[n.length() - 1] = c;
67 return n;
Garrick Evans54861622019-07-19 09:05:09 +090068}
Garrick Evansf0ab7132019-06-18 14:50:42 +090069
Garrick Evans8a067562020-05-11 12:47:30 +090070} // namespace
71
72std::string ArcVethHostName(const std::string& ifname) {
73 return PrefixIfname("veth", ifname);
74}
75
76std::string ArcBridgeName(const std::string& ifname) {
77 return PrefixIfname("arc_", ifname);
78}
79
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090080Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
81 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090082
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090083Datapath::Datapath(MinijailedProcessRunner* process_runner,
84 Firewall* firewall,
85 ioctl_t ioctl_hook)
86 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +090087 CHECK(process_runner_);
88}
89
Garrick Evans260ff302019-07-25 11:22:50 +090090MinijailedProcessRunner& Datapath::runner() const {
91 return *process_runner_;
92}
93
Hugo Benichibf811c62020-09-07 17:30:45 +090094void Datapath::Start() {
95 // Enable IPv4 packet forwarding
96 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
97 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
98 << " Guest connectivity will not work correctly.";
99
100 // Limit local port range: Android owns 47104-61000.
101 // TODO(garrick): The original history behind this tweak is gone. Some
102 // investigation is needed to see if it is still applicable.
103 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
104 "32768 47103") != 0)
105 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
106 << " apps may not work correctly.";
107
108 // Enable IPv6 packet forwarding
109 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
110 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
111 << " IPv6 functionality may be broken.";
112
113 if (!AddSNATMarkRules())
114 LOG(ERROR) << "Failed to install SNAT mark rules."
115 << " Guest connectivity may be broken.";
116
Hugo Benichi58125d32020-09-09 11:25:45 +0900117 // Create a FORWARD ACCEPT rule for connections already established.
118 if (process_runner_->iptables(
119 "filter", {"-A", "FORWARD", "-m", "state", "--state",
120 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900121 LOG(ERROR) << "Failed to install forwarding rule for established"
122 << " connections.";
123
124 // chromium:898210: Drop any locally originated traffic that would exit a
125 // physical interface with a source IPv4 address from the subnet of IPs used
126 // for VMs, containers, and connected namespaces This is needed to prevent
127 // packets leaking with an incorrect src IP when a local process binds to the
128 // wrong interface.
129 for (const auto& oif : kPhysicalIfnamePrefixes) {
130 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
131 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
132 << kGuestIPv4Subnet << " exiting " << oif;
133 }
134
135 if (!AddOutboundIPv4SNATMark("vmtap+"))
136 LOG(ERROR) << "Failed to set up NAT for TAP devices."
137 << " Guest connectivity may be broken.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900138
Hugo Benichi2a940542020-10-26 18:50:49 +0900139 // Applies the routing tag saved in conntrack for any established connection
140 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900141 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
142 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900143 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
144
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900145 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
146 // tag and tagging the local traffic that should be routed through a VPN.
147 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyLocalSourceMarkChain))
148 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
149 << " mangle chain";
150 // Ensure that the chain is empty if patchpanel is restarting after a crash.
151 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyLocalSourceMarkChain))
152 LOG(ERROR) << "Failed to flush " << kApplyLocalSourceMarkChain
153 << " mangle chain";
154 if (!ModifyIptables(IpFamily::Dual, "mangle",
155 {"-A", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
156 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
157 << " to mangle OUTPUT";
158 // Create rules for tagging local sources with the source tag and the vpn
159 // policy tag.
160 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900161 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900162 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
163 << " in " << kApplyLocalSourceMarkChain;
164 }
165 // Finally add a catch-all rule for tagging any remaining local sources with
166 // the SYSTEM source tag
167 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
168 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
169
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900170 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
171 // traffic that should be routed through a VPN.
172 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyVpnMarkChain))
173 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
174 // Ensure that the chain is empty if patchpanel is restarting after a crash.
175 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyVpnMarkChain))
176 LOG(ERROR) << "Failed to flush " << kApplyVpnMarkChain << " mangle chain";
177 // All local outgoing traffic eligible to VPN routing should traverse the VPN
178 // marking chain.
179 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", "" /*iif*/, kFwmarkRouteOnVpn,
180 kFwmarkVpnMask))
181 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
182 // Any traffic that already has a routing tag applied is accepted.
183 if (!ModifyIptables(
184 IpFamily::Dual, "mangle",
185 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
186 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
187 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
188 "connections";
Hugo Benichibf811c62020-09-07 17:30:45 +0900189}
190
191void Datapath::Stop() {
192 RemoveOutboundIPv4SNATMark("vmtap+");
Hugo Benichi58125d32020-09-09 11:25:45 +0900193 process_runner_->iptables("filter",
194 {"-D", "FORWARD", "-m", "state", "--state",
195 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"});
Hugo Benichibf811c62020-09-07 17:30:45 +0900196 RemoveSNATMarkRules();
197 for (const auto& oif : kPhysicalIfnamePrefixes)
198 RemoveSourceIPv4DropRule(oif, kGuestIPv4Subnet);
199
200 // Restore original local port range.
201 // TODO(garrick): The original history behind this tweak is gone. Some
202 // investigation is needed to see if it is still applicable.
203 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
204 "32768 61000") != 0)
205 LOG(ERROR) << "Failed to restore local port range";
206
207 // Disable packet forwarding
208 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
209 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
210
211 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
212 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900213
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900214 // Detach the VPN marking mangle chain
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900215 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-D", "" /*iif*/, kFwmarkRouteOnVpn,
216 kFwmarkVpnMask))
217 LOG(ERROR)
218 << "Failed to remove from mangle OUTPUT chain jump rule to VPN chain";
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900219
220 // Detach apply_local_source_mark from mangle PREROUTING
221 if (!ModifyIptables(IpFamily::Dual, "mangle",
222 {"-D", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
223 LOG(ERROR) << "Failed to detach " << kApplyLocalSourceMarkChain
224 << " from mangle OUTPUT";
225
Hugo Benichi2a940542020-10-26 18:50:49 +0900226 // Stops applying routing tags saved in conntrack for sockets created in the
227 // host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900228 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-D", "" /*iif*/,
229 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900230 LOG(ERROR) << "Failed to remove OUTPUT CONNMARK restore rule";
231
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900232 // Delete the mangle chains
233 for (const auto* chain : {kApplyLocalSourceMarkChain, kApplyVpnMarkChain}) {
234 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", chain))
235 LOG(ERROR) << "Failed to flush " << chain << " mangle chain";
236
237 if (!ModifyChain(IpFamily::Dual, "mangle", "-X", chain))
238 LOG(ERROR) << "Failed to delete " << chain << " mangle chain";
239 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900240}
241
Hugo Benichi33860d72020-07-09 16:34:01 +0900242bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
243 // Try first to delete any netns with name |netns_name| in case patchpanel
244 // did not exit cleanly.
245 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
246 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
247 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
248}
249
250bool Datapath::NetnsDeleteName(const std::string& netns_name) {
251 return process_runner_->ip_netns_delete(netns_name) == 0;
252}
253
Garrick Evans8a949dc2019-07-18 16:17:53 +0900254bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900255 uint32_t ipv4_addr,
256 uint32_t ipv4_prefix_len) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900257 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900258 if (process_runner_->brctl("addbr", {ifname}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900259 return false;
260 }
261
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900262 if (process_runner_->ip(
263 "addr", "add",
264 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
265 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
266 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900267 RemoveBridge(ifname);
268 return false;
269 }
270
271 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900272 RemoveBridge(ifname);
273 return false;
274 }
275
276 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900277 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900278 RemoveBridge(ifname);
279 return false;
280 }
281
282 return true;
283}
284
285void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900286 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900287 process_runner_->ip("link", "set", {ifname, "down"});
Garrick Evans8e8e3472020-01-23 14:03:50 +0900288 process_runner_->brctl("delbr", {ifname});
Garrick Evans8a949dc2019-07-18 16:17:53 +0900289}
290
Garrick Evans621ed262019-11-13 12:28:43 +0900291bool Datapath::AddToBridge(const std::string& br_ifname,
292 const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900293 return (process_runner_->brctl("addif", {br_ifname, ifname}) == 0);
Garrick Evans621ed262019-11-13 12:28:43 +0900294}
295
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900296std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900297 const MacAddress* mac_addr,
298 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900299 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900300 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
301 if (!dev.is_valid()) {
302 PLOG(ERROR) << "Failed to open " << kTunDev;
303 return "";
304 }
305
306 struct ifreq ifr;
307 memset(&ifr, 0, sizeof(ifr));
308 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
309 sizeof(ifr.ifr_name));
310 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
311
312 // If a template was given as the name, ifr_name will be updated with the
313 // actual interface name.
314 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900315 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900316 return "";
317 }
318 const char* ifname = ifr.ifr_name;
319
320 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900321 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900322 return "";
323 }
324
Garrick Evans4f9f5572019-11-26 10:25:16 +0900325 if (!user.empty()) {
326 uid_t uid = -1;
327 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
328 PLOG(ERROR) << "Unable to look up UID for " << user;
329 RemoveTAP(ifname);
330 return "";
331 }
332 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
333 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
334 << ifname;
335 RemoveTAP(ifname);
336 return "";
337 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900338 }
339
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900340 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900341 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
342 if (!sock.is_valid()) {
343 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900344 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900345 RemoveTAP(ifname);
346 return "";
347 }
348
Garrick Evans621ed262019-11-13 12:28:43 +0900349 if (ipv4_addr) {
350 struct sockaddr_in* addr =
351 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
352 addr->sin_family = AF_INET;
353 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
354 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
355 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
356 << " {" << ipv4_addr->ToCidrString() << "}";
357 RemoveTAP(ifname);
358 return "";
359 }
360
361 struct sockaddr_in* netmask =
362 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
363 netmask->sin_family = AF_INET;
364 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
365 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
366 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
367 << " {" << ipv4_addr->ToCidrString() << "}";
368 RemoveTAP(ifname);
369 return "";
370 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900371 }
372
Garrick Evans621ed262019-11-13 12:28:43 +0900373 if (mac_addr) {
374 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
375 hwaddr->sa_family = ARPHRD_ETHER;
376 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
377 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
378 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
379 << " {" << MacAddressToString(*mac_addr) << "}";
380 RemoveTAP(ifname);
381 return "";
382 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900383 }
384
385 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900386 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900387 RemoveTAP(ifname);
388 return "";
389 }
390
391 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
392 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900393 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900394 RemoveTAP(ifname);
395 return "";
396 }
397
398 return ifname;
399}
400
401void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900402 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900403}
404
Hugo Benichi33860d72020-07-09 16:34:01 +0900405bool Datapath::ConnectVethPair(pid_t netns_pid,
406 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900407 const std::string& veth_ifname,
408 const std::string& peer_ifname,
409 const MacAddress& remote_mac_addr,
410 uint32_t remote_ipv4_addr,
411 uint32_t remote_ipv4_prefix_len,
412 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900413 // Set up the virtual pair across the current namespace and |netns_name|.
414 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
415 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
416 << peer_ifname;
417 return false;
418 }
419
420 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900421 {
Hugo Benichi33860d72020-07-09 16:34:01 +0900422 ScopedNS ns(netns_pid);
423 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900424 LOG(ERROR)
425 << "Cannot create virtual link -- invalid container namespace?";
426 return false;
427 }
428
Hugo Benichi76675592020-04-08 14:29:57 +0900429 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
430 remote_ipv4_prefix_len, true /* link up */,
431 remote_multicast_flag)) {
432 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
433 RemoveInterface(peer_ifname);
434 return false;
435 }
436 }
437
Hugo Benichi76675592020-04-08 14:29:57 +0900438 if (!ToggleInterface(veth_ifname, true /*up*/)) {
439 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
440 RemoveInterface(veth_ifname);
441 return false;
442 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900443
Hugo Benichi76675592020-04-08 14:29:57 +0900444 return true;
445}
446
Hugo Benichi33860d72020-07-09 16:34:01 +0900447bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
448 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900449 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900450 return process_runner_->ip("link", "add",
451 {veth_ifname, "type", "veth", "peer", "name",
452 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900453}
Garrick Evans54861622019-07-19 09:05:09 +0900454
Garrick Evans2470caa2020-03-04 14:15:41 +0900455bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
456 const std::string link = up ? "up" : "down";
457 return process_runner_->ip("link", "set", {ifname, link}) == 0;
458}
Garrick Evans54861622019-07-19 09:05:09 +0900459
Garrick Evans2470caa2020-03-04 14:15:41 +0900460bool Datapath::ConfigureInterface(const std::string& ifname,
461 const MacAddress& mac_addr,
462 uint32_t ipv4_addr,
463 uint32_t ipv4_prefix_len,
464 bool up,
465 bool enable_multicast) {
466 const std::string link = up ? "up" : "down";
467 const std::string multicast = enable_multicast ? "on" : "off";
468 return (process_runner_->ip(
469 "addr", "add",
470 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
471 IPv4AddressToString(
472 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
473 "dev", ifname}) == 0) &&
474 (process_runner_->ip("link", "set",
475 {
476 "dev",
477 ifname,
478 link,
479 "addr",
480 MacAddressToString(mac_addr),
481 "multicast",
482 multicast,
483 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900484}
485
486void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900487 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900488}
489
Hugo Benichi321f23b2020-09-25 15:42:05 +0900490bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
491 const std::string& src_ip) {
492 return process_runner_->iptables("filter", {"-I", "OUTPUT", "-o", oif, "-s",
493 src_ip, "-j", "DROP", "-w"}) == 0;
494}
495
496bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
497 const std::string& src_ip) {
498 return process_runner_->iptables("filter", {"-D", "OUTPUT", "-o", oif, "-s",
499 src_ip, "-j", "DROP", "-w"}) == 0;
500}
501
Hugo Benichifcf81022020-12-04 11:01:37 +0900502bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900503 // Veth interface configuration and client routing configuration:
504 // - attach a name to the client namespace.
505 // - create veth pair across the current namespace and the client namespace.
506 // - configure IPv4 address on remote veth inside client namespace.
507 // - configure IPv4 address on local veth inside host namespace.
508 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900509 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
510 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
511 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900512 return false;
513 }
514
Hugo Benichifcf81022020-12-04 11:01:37 +0900515 if (!ConnectVethPair(
516 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
517 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
518 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900519 LOG(ERROR) << "Failed to create veth pair for"
520 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900521 << nsinfo.pid;
522 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900523 return false;
524 }
525
Hugo Benichifcf81022020-12-04 11:01:37 +0900526 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
527 nsinfo.peer_subnet->AddressAtOffset(0),
528 nsinfo.peer_subnet->PrefixLength(),
529 true /* link up */, false /* enable_multicast */)) {
530 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
531 RemoveInterface(nsinfo.host_ifname);
532 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900533 return false;
534 }
535
536 {
Hugo Benichifcf81022020-12-04 11:01:37 +0900537 ScopedNS ns(nsinfo.pid);
538 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
539 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
540 RemoveInterface(nsinfo.host_ifname);
541 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900542 return false;
543 }
544
Hugo Benichifcf81022020-12-04 11:01:37 +0900545 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
546 INADDR_ANY)) {
547 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
548 << " inside namespace pid " << nsinfo.pid;
549 RemoveInterface(nsinfo.host_ifname);
550 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900551 return false;
552 }
553 }
554
555 // Host namespace routing configuration
556 // - ingress: add route to client subnet via |host_ifname|.
557 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
558 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
559 // Note that by default unsolicited ingress traffic is not forwarded to the
560 // client namespace unless the client specifically set port forwarding
561 // through permission_broker DBus APIs.
562 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
563 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900564 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
565 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
566 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900567 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900568 RemoveInterface(nsinfo.host_ifname);
569 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900570 return false;
571 }
572
Hugo Benichi7c342672020-09-08 09:18:14 +0900573 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900574 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900575 LOG(ERROR) << "Failed to set SNAT for traffic"
576 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900577 << nsinfo.host_ifname;
578 RemoveInterface(nsinfo.host_ifname);
579 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
580 nsinfo.peer_subnet->BaseAddress(), netmask);
581 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
582 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900583 return false;
584 }
585
Hugo Benichi93306e52020-12-04 16:08:00 +0900586 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
587 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
588 nsinfo.route_on_vpn);
589
Hugo Benichi7c342672020-09-08 09:18:14 +0900590 return true;
591}
592
Hugo Benichifcf81022020-12-04 11:01:37 +0900593void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900594 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
595 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
596 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900597 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900598 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
599 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
600 nsinfo.peer_subnet->BaseAddress(),
601 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
602 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900603}
604
Hugo Benichi8d622b52020-08-13 15:24:12 +0900605void Datapath::StartRoutingDevice(const std::string& ext_ifname,
606 const std::string& int_ifname,
607 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900608 TrafficSource source,
609 bool route_on_vpn) {
610 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900611 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
612 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
613 << "->" << int_ifname;
614
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900615 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900616 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
617 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900618
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900619 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900620 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
621 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900622
Hugo Benichi2a940542020-10-26 18:50:49 +0900623 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
624 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
625 << source << " for " << int_ifname;
626
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900627 if (!ext_ifname.empty()) {
628 // If |ext_ifname| is not null, mark egress traffic with the
629 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi2a940542020-10-26 18:50:49 +0900630 if (!ModifyFwmarkRoutingTag("PREROUTING", "-A", ext_ifname, int_ifname))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900631 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
632 << ext_ifname << "<-" << int_ifname;
633 } else {
634 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
635 // PREROUTING to apply any fwmark routing tag saved for the current
636 // connection, and rely on implicit routing to the default logical network
637 // otherwise.
Hugo Benichi1af52392020-11-27 18:09:32 +0900638 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname,
639 kFwmarkRoutingMask))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900640 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
641 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900642
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900643 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900644 // default network is eligible to be routed through a VPN if |route_on_vpn|
645 // is true.
646 if (route_on_vpn &&
647 !ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900648 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900649 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900650}
651
652void Datapath::StopRoutingDevice(const std::string& ext_ifname,
653 const std::string& int_ifname,
654 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900655 TrafficSource source,
656 bool route_on_vpn) {
657 if (source == TrafficSource::ARC && !ext_ifname.empty())
Hugo Benichi8d622b52020-08-13 15:24:12 +0900658 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900659 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
660 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900661 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900662 if (!ext_ifname.empty()) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900663 ModifyFwmarkRoutingTag("PREROUTING", "-D", ext_ifname, int_ifname);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900664 } else {
Hugo Benichi1af52392020-11-27 18:09:32 +0900665 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname,
666 kFwmarkRoutingMask);
Hugo Benichi93306e52020-12-04 16:08:00 +0900667 if (route_on_vpn)
668 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900669 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900670}
671
Garrick Evansf0ab7132019-06-18 14:50:42 +0900672bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
673 const std::string& ipv4_addr) {
674 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900675 if (process_runner_->iptables(
676 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
677 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900678 return false;
679
680 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900681 if (process_runner_->iptables(
682 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
683 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900684 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
685 return false;
686 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900687 if (process_runner_->iptables(
688 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
689 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900690 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
691 return false;
692 }
693
694 return true;
695}
696
697void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
698 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900699 process_runner_->iptables(
700 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
701 "--to-destination", ipv4_addr, "-w"});
702 process_runner_->iptables(
703 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
704 "--to-destination", ipv4_addr, "-w"});
705 process_runner_->iptables(
706 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
707 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900708}
709
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900710// TODO(b/161507671) Stop relying on the traffic fwmark 1/1 once forwarded
711// egress traffic is routed through the fwmark routing tag.
Garrick Evansd291af62020-05-25 10:39:06 +0900712bool Datapath::AddSNATMarkRules() {
Taoyu Li79871c92020-07-02 16:09:39 +0900713 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
714 // need to be explicitly dropped.
715 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900716 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
Taoyu Li79871c92020-07-02 16:09:39 +0900717 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0) {
718 return false;
719 }
Garrick Evansd291af62020-05-25 10:39:06 +0900720 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900721 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900722 "ACCEPT", "-w"}) != 0) {
723 return false;
724 }
725 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900726 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900727 "MASQUERADE", "-w"}) != 0) {
728 RemoveSNATMarkRules();
729 return false;
730 }
731 return true;
732}
733
734void Datapath::RemoveSNATMarkRules() {
735 process_runner_->iptables("nat", {"-D", "POSTROUTING", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900736 "1/1", "-j", "MASQUERADE", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900737 process_runner_->iptables("filter", {"-D", "FORWARD", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900738 "1/1", "-j", "ACCEPT", "-w"});
Taoyu Li79871c92020-07-02 16:09:39 +0900739 process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900740 "filter", {"-D", "FORWARD", "-m", "mark", "--mark", "1/1", "-m", "state",
Taoyu Li79871c92020-07-02 16:09:39 +0900741 "--state", "INVALID", "-j", "DROP", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900742}
743
Hugo Benichie8758b52020-04-03 14:49:01 +0900744bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
745 return process_runner_->iptables(
746 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900747 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900748}
749
750void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
751 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900752 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900753}
754
Garrick Evans664a82f2019-12-17 12:18:05 +0900755bool Datapath::MaskInterfaceFlags(const std::string& ifname,
756 uint16_t on,
757 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900758 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
759 if (!sock.is_valid()) {
760 PLOG(ERROR) << "Failed to create control socket";
761 return false;
762 }
763 ifreq ifr;
764 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
765 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
766 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
767 return false;
768 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900769 ifr.ifr_flags |= on;
770 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900771 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900772 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
773 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900774 return false;
775 }
776 return true;
777}
778
Garrick Evans260ff302019-07-25 11:22:50 +0900779bool Datapath::AddIPv6HostRoute(const std::string& ifname,
780 const std::string& ipv6_addr,
781 int ipv6_prefix_len) {
782 std::string ipv6_addr_cidr =
783 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
784
Garrick Evans8e8e3472020-01-23 14:03:50 +0900785 return process_runner_->ip6("route", "replace",
786 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900787}
788
789void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
790 const std::string& ipv6_addr,
791 int ipv6_prefix_len) {
792 std::string ipv6_addr_cidr =
793 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
794
Garrick Evans8e8e3472020-01-23 14:03:50 +0900795 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900796}
797
Taoyu Lia0727dc2020-09-24 19:54:59 +0900798bool Datapath::AddIPv6Address(const std::string& ifname,
799 const std::string& ipv6_addr) {
800 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900801}
802
Taoyu Lia0727dc2020-09-24 19:54:59 +0900803void Datapath::RemoveIPv6Address(const std::string& ifname,
804 const std::string& ipv6_addr) {
805 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900806}
807
Hugo Benichi76be34a2020-08-26 22:35:54 +0900808void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi1af52392020-11-27 18:09:32 +0900809 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi76be34a2020-08-26 22:35:54 +0900810 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
811 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900812 // Save in CONNMARK the source tag for egress traffic of this connection.
813 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
814 kFwmarkAllSourcesMask))
815 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
816 "source tag on "
817 << ext_ifname;
818 // Restore from CONNMARK the source tag for ingress traffic of this connection
819 // (returned traffic).
820 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
821 kFwmarkAllSourcesMask))
822 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
823 "traffic received on "
824 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900825}
826
827void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
828 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
829 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900830 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
831 kFwmarkAllSourcesMask))
832 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
833 "fwmark source tag on "
834 << ext_ifname;
835 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
836 kFwmarkAllSourcesMask))
837 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
838 "traffic received on "
839 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900840}
841
Hugo Benichi2a940542020-10-26 18:50:49 +0900842void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
843 StartConnectionPinning(vpn_ifname);
844 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", vpn_ifname, ""))
845 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
846}
847
848void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
849 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", vpn_ifname, ""))
850 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
851 StopConnectionPinning(vpn_ifname);
852}
853
Hugo Benichi76be34a2020-08-26 22:35:54 +0900854bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
855 const std::string& op,
856 const std::string& oif) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900857 int ifindex = FindIfIndex(oif);
858 if (ifindex == 0) {
859 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
860 return false;
861 }
862
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900863 return ModifyConnmarkSet(family, "POSTROUTING", op, oif,
864 Fwmark::FromIfIndex(ifindex), kFwmarkRoutingMask);
865}
866
867bool Datapath::ModifyConnmarkSet(IpFamily family,
868 const std::string& chain,
869 const std::string& op,
870 const std::string& oif,
871 Fwmark mark,
872 Fwmark mask) {
873 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
874 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
875 return false;
876 }
877
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900878 std::vector<std::string> args = {op, chain};
879 if (!oif.empty()) {
880 args.push_back("-o");
881 args.push_back(oif);
882 }
883 args.push_back("-j");
884 args.push_back("CONNMARK");
885 args.push_back("--set-mark");
886 args.push_back(mark.ToString() + "/" + mask.ToString());
887 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +0900888
Hugo Benichi58f264a2020-10-16 18:16:05 +0900889 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +0900890}
891
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900892bool Datapath::ModifyConnmarkRestore(IpFamily family,
893 const std::string& chain,
894 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +0900895 const std::string& iif,
896 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900897 if (chain != "OUTPUT" && (chain != "PREROUTING" || iif.empty())) {
898 LOG(ERROR) << "Invalid arguments chain=" << chain << " iif=" << iif;
899 return false;
900 }
901
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900902 std::vector<std::string> args = {op, chain};
903 if (!iif.empty()) {
904 args.push_back("-i");
905 args.push_back(iif);
906 }
907 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +0900908 mask.ToString(), "-w"});
909 return ModifyIptables(family, "mangle", args);
910}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900911
Hugo Benichi1af52392020-11-27 18:09:32 +0900912bool Datapath::ModifyConnmarkSave(IpFamily family,
913 const std::string& chain,
914 const std::string& op,
915 const std::string& oif,
916 Fwmark mask) {
917 std::vector<std::string> args = {op, chain};
918 if (!oif.empty()) {
919 args.push_back("-o");
920 args.push_back(oif);
921 }
922 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
923 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +0900924 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900925}
926
Hugo Benichi2a940542020-10-26 18:50:49 +0900927bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
928 const std::string& op,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900929 const std::string& ext_ifname,
930 const std::string& int_ifname) {
931 int ifindex = FindIfIndex(ext_ifname);
932 if (ifindex == 0) {
933 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
934 return false;
935 }
936
Hugo Benichi2a940542020-10-26 18:50:49 +0900937 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900938 0 /*classid*/, Fwmark::FromIfIndex(ifindex),
939 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900940}
941
Hugo Benichi9be19b12020-08-14 15:33:40 +0900942bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
943 const std::string& iif,
944 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900945 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900946 0 /*classid*/, Fwmark::FromSource(source),
947 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900948}
949
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900950bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
951 TrafficSource source) {
952 std::vector<std::string> args = {"-A",
953 kApplyLocalSourceMarkChain,
954 "-m",
955 "mark",
956 "--mark",
957 "0x0/" + kFwmarkAllSourcesMask.ToString(),
958 "-j",
959 "MARK",
960 "--set-mark",
961 Fwmark::FromSource(source).ToString() + "/" +
962 kFwmarkAllSourcesMask.ToString(),
963 "-w"};
964 return ModifyIptables(IpFamily::Dual, "mangle", args);
965}
Hugo Benichi9be19b12020-08-14 15:33:40 +0900966
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900967bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
968 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900969 if (std::string(source.uid_name).empty() && source.classid == 0)
970 return false;
971
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900972 Fwmark mark = Fwmark::FromSource(source.source_type);
973 if (source.is_on_vpn)
974 mark = mark | kFwmarkRouteOnVpn;
975
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900976 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
977 "" /*iif*/, source.uid_name, source.classid, mark,
978 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900979}
980
981bool Datapath::ModifyFwmark(IpFamily family,
982 const std::string& chain,
983 const std::string& op,
984 const std::string& iif,
985 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900986 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900987 Fwmark mark,
988 Fwmark mask,
989 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900990 std::vector<std::string> args = {op, chain};
991 if (!iif.empty()) {
992 args.push_back("-i");
993 args.push_back(iif);
994 }
995 if (!uid_name.empty()) {
996 args.push_back("-m");
997 args.push_back("owner");
998 args.push_back("--uid-owner");
999 args.push_back(uid_name);
1000 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001001 if (classid != 0) {
1002 args.push_back("-m");
1003 args.push_back("cgroup");
1004 args.push_back("--cgroup");
1005 args.push_back(base::StringPrintf("0x%08x", classid));
1006 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001007 args.push_back("-j");
1008 args.push_back("MARK");
1009 args.push_back("--set-mark");
1010 args.push_back(mark.ToString() + "/" + mask.ToString());
1011 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001012
Hugo Benichi58f264a2020-10-16 18:16:05 +09001013 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001014}
1015
Hugo Benichid82d8832020-08-14 10:05:03 +09001016bool Datapath::ModifyIpForwarding(IpFamily family,
1017 const std::string& op,
1018 const std::string& iif,
1019 const std::string& oif,
1020 bool log_failures) {
1021 if (iif.empty() && oif.empty()) {
1022 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1023 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001024 return false;
1025 }
1026
Hugo Benichid82d8832020-08-14 10:05:03 +09001027 std::vector<std::string> args = {op, "FORWARD"};
1028 if (!iif.empty()) {
1029 args.push_back("-i");
1030 args.push_back(iif);
1031 }
1032 if (!oif.empty()) {
1033 args.push_back("-o");
1034 args.push_back(oif);
1035 }
1036 args.push_back("-j");
1037 args.push_back("ACCEPT");
1038 args.push_back("-w");
1039
Hugo Benichi58f264a2020-10-16 18:16:05 +09001040 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001041}
1042
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001043bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1044 const std::string& op,
1045 const std::string& iif,
1046 Fwmark mark,
1047 Fwmark mask) {
1048 std::vector<std::string> args = {op, chain};
1049 if (!iif.empty()) {
1050 args.push_back("-i");
1051 args.push_back(iif);
1052 }
1053 if (mark.Value() != 0 && mask.Value() != 0) {
1054 args.push_back("-m");
1055 args.push_back("mark");
1056 args.push_back("--mark");
1057 args.push_back(mark.ToString() + "/" + mask.ToString());
1058 }
1059 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1060 return ModifyIptables(IpFamily::Dual, "mangle", args);
1061}
1062
1063bool Datapath::ModifyChain(IpFamily family,
1064 const std::string& table,
1065 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001066 const std::string& chain,
1067 bool log_failures) {
1068 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001069}
1070
1071bool Datapath::ModifyIptables(IpFamily family,
1072 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001073 const std::vector<std::string>& argv,
1074 bool log_failures) {
1075 switch (family) {
1076 case IPv4:
1077 case IPv6:
1078 case Dual:
1079 break;
1080 default:
1081 LOG(ERROR) << "Could not execute iptables command " << table
1082 << base::JoinString(argv, " ") << ": incorrect IP family "
1083 << family;
1084 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001085 }
1086
1087 bool success = true;
1088 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001089 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001090 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001091 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001092 return success;
1093}
1094
Hugo Benichid82d8832020-08-14 10:05:03 +09001095bool Datapath::StartIpForwarding(IpFamily family,
1096 const std::string& iif,
1097 const std::string& oif) {
1098 return ModifyIpForwarding(family, "-A", iif, oif);
1099}
1100
1101bool Datapath::StopIpForwarding(IpFamily family,
1102 const std::string& iif,
1103 const std::string& oif) {
1104 return ModifyIpForwarding(family, "-D", iif, oif);
1105}
1106
1107bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1108 const std::string& ifname2) {
1109 // Only start Ipv6 forwarding if -C returns false and it had not been
1110 // started yet.
1111 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1112 false /*log_failures*/) &&
1113 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1114 return false;
1115 }
1116
1117 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1118 false /*log_failures*/) &&
1119 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001120 RemoveIPv6Forwarding(ifname1, ifname2);
1121 return false;
1122 }
1123
1124 return true;
1125}
1126
1127void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1128 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001129 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1130 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001131}
1132
Garrick Evans3d97a392020-02-21 15:24:37 +09001133bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1134 uint32_t addr,
1135 uint32_t netmask) {
1136 struct rtentry route;
1137 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001138 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1139 SetSockaddrIn(&route.rt_dst, addr & netmask);
1140 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001141 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001142 return ModifyRtentry(SIOCADDRT, &route);
1143}
Garrick Evans3d97a392020-02-21 15:24:37 +09001144
Hugo Benichie8758b52020-04-03 14:49:01 +09001145bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1146 uint32_t addr,
1147 uint32_t netmask) {
1148 struct rtentry route;
1149 memset(&route, 0, sizeof(route));
1150 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1151 SetSockaddrIn(&route.rt_dst, addr & netmask);
1152 SetSockaddrIn(&route.rt_genmask, netmask);
1153 route.rt_flags = RTF_UP | RTF_GATEWAY;
1154 return ModifyRtentry(SIOCDELRT, &route);
1155}
1156
1157bool Datapath::AddIPv4Route(const std::string& ifname,
1158 uint32_t addr,
1159 uint32_t netmask) {
1160 struct rtentry route;
1161 memset(&route, 0, sizeof(route));
1162 SetSockaddrIn(&route.rt_dst, addr & netmask);
1163 SetSockaddrIn(&route.rt_genmask, netmask);
1164 char rt_dev[IFNAMSIZ];
1165 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1166 rt_dev[IFNAMSIZ - 1] = '\0';
1167 route.rt_dev = rt_dev;
1168 route.rt_flags = RTF_UP | RTF_GATEWAY;
1169 return ModifyRtentry(SIOCADDRT, &route);
1170}
1171
1172bool Datapath::DeleteIPv4Route(const std::string& ifname,
1173 uint32_t addr,
1174 uint32_t netmask) {
1175 struct rtentry route;
1176 memset(&route, 0, sizeof(route));
1177 SetSockaddrIn(&route.rt_dst, addr & netmask);
1178 SetSockaddrIn(&route.rt_genmask, netmask);
1179 char rt_dev[IFNAMSIZ];
1180 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1181 rt_dev[IFNAMSIZ - 1] = '\0';
1182 route.rt_dev = rt_dev;
1183 route.rt_flags = RTF_UP | RTF_GATEWAY;
1184 return ModifyRtentry(SIOCDELRT, &route);
1185}
1186
Taoyu Lia0727dc2020-09-24 19:54:59 +09001187bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001188 DCHECK(route);
1189 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001190 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001191 return false;
1192 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001193 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1194 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001195 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001196 return false;
1197 }
1198 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1199 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001200 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001201 return false;
1202 }
1203 return true;
1204}
1205
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001206bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1207 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1208 kArcAddr, kAdbServerPort, ifname,
1209 kLocalhostAddr, kAdbProxyTcpListenPort);
1210}
1211
1212void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1213 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1214 kArcAddr, kAdbServerPort, ifname,
1215 kLocalhostAddr, kAdbProxyTcpListenPort);
1216}
1217
1218bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1219 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1220 kAdbProxyTcpListenPort, ifname);
1221}
1222
1223void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1224 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1225 kAdbProxyTcpListenPort, ifname);
1226}
1227
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001228void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1229 if_nametoindex_[ifname] = ifindex;
1230}
1231
1232int Datapath::FindIfIndex(const std::string& ifname) {
1233 uint32_t ifindex = if_nametoindex(ifname.c_str());
1234 if (ifindex > 0) {
1235 if_nametoindex_[ifname] = ifindex;
1236 return ifindex;
1237 }
1238
1239 const auto it = if_nametoindex_.find(ifname);
1240 if (it != if_nametoindex_.end())
1241 return it->second;
1242
1243 return 0;
1244}
1245
Hugo Benichifcf81022020-12-04 11:01:37 +09001246std::ostream& operator<<(std::ostream& stream,
1247 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001248 stream << "{ pid: " << nsinfo.pid
1249 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001250 if (!nsinfo.outbound_ifname.empty()) {
1251 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1252 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001253 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1254 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001255 << ", peer_ifname: " << nsinfo.peer_ifname
1256 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1257 return stream;
1258}
1259
Garrick Evans3388a032020-03-24 11:25:55 +09001260} // namespace patchpanel