blob: fc84da5f0e614a6ebc54a43f0f3b62bf82e603ef [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
Taoyu Li78f0c9a2020-12-25 22:58:26 +0900139 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
140 // wrongly cause neighbor discovery icmpv6 packets to be dropped. Add these
141 // rules to bypass connmark rule for those packets.
142 for (const auto& type : kNeighborDiscoveryTypes) {
143 if (!ModifyIptables(IpFamily::IPv6, "mangle",
144 {"-A", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
145 "-j", "ACCEPT", "-w"}))
146 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
147 << " packets";
148 }
149
Hugo Benichi2a940542020-10-26 18:50:49 +0900150 // Applies the routing tag saved in conntrack for any established connection
151 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900152 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
153 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900154 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
155
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900156 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
157 // tag and tagging the local traffic that should be routed through a VPN.
158 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyLocalSourceMarkChain))
159 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
160 << " mangle chain";
161 // Ensure that the chain is empty if patchpanel is restarting after a crash.
162 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyLocalSourceMarkChain))
163 LOG(ERROR) << "Failed to flush " << kApplyLocalSourceMarkChain
164 << " mangle chain";
165 if (!ModifyIptables(IpFamily::Dual, "mangle",
166 {"-A", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
167 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
168 << " to mangle OUTPUT";
169 // Create rules for tagging local sources with the source tag and the vpn
170 // policy tag.
171 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900172 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900173 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
174 << " in " << kApplyLocalSourceMarkChain;
175 }
176 // Finally add a catch-all rule for tagging any remaining local sources with
177 // the SYSTEM source tag
178 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
179 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
180
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900181 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
182 // traffic that should be routed through a VPN.
183 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyVpnMarkChain))
184 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
185 // Ensure that the chain is empty if patchpanel is restarting after a crash.
186 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyVpnMarkChain))
187 LOG(ERROR) << "Failed to flush " << kApplyVpnMarkChain << " mangle chain";
188 // All local outgoing traffic eligible to VPN routing should traverse the VPN
189 // marking chain.
190 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", "" /*iif*/, kFwmarkRouteOnVpn,
191 kFwmarkVpnMask))
192 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
193 // Any traffic that already has a routing tag applied is accepted.
194 if (!ModifyIptables(
195 IpFamily::Dual, "mangle",
196 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
197 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
198 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
199 "connections";
Hugo Benichibf811c62020-09-07 17:30:45 +0900200}
201
202void Datapath::Stop() {
203 RemoveOutboundIPv4SNATMark("vmtap+");
Hugo Benichi58125d32020-09-09 11:25:45 +0900204 process_runner_->iptables("filter",
205 {"-D", "FORWARD", "-m", "state", "--state",
206 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"});
Hugo Benichibf811c62020-09-07 17:30:45 +0900207 RemoveSNATMarkRules();
208 for (const auto& oif : kPhysicalIfnamePrefixes)
209 RemoveSourceIPv4DropRule(oif, kGuestIPv4Subnet);
210
211 // Restore original local port range.
212 // TODO(garrick): The original history behind this tweak is gone. Some
213 // investigation is needed to see if it is still applicable.
214 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
215 "32768 61000") != 0)
216 LOG(ERROR) << "Failed to restore local port range";
217
218 // Disable packet forwarding
219 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
220 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
221
222 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
223 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900224
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900225 // Detach the VPN marking mangle chain
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900226 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-D", "" /*iif*/, kFwmarkRouteOnVpn,
227 kFwmarkVpnMask))
228 LOG(ERROR)
229 << "Failed to remove from mangle OUTPUT chain jump rule to VPN chain";
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900230
231 // Detach apply_local_source_mark from mangle PREROUTING
232 if (!ModifyIptables(IpFamily::Dual, "mangle",
233 {"-D", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
234 LOG(ERROR) << "Failed to detach " << kApplyLocalSourceMarkChain
235 << " from mangle OUTPUT";
236
Hugo Benichi2a940542020-10-26 18:50:49 +0900237 // Stops applying routing tags saved in conntrack for sockets created in the
238 // host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900239 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-D", "" /*iif*/,
240 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900241 LOG(ERROR) << "Failed to remove OUTPUT CONNMARK restore rule";
242
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900243 // Delete the mangle chains
244 for (const auto* chain : {kApplyLocalSourceMarkChain, kApplyVpnMarkChain}) {
245 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", chain))
246 LOG(ERROR) << "Failed to flush " << chain << " mangle chain";
247
248 if (!ModifyChain(IpFamily::Dual, "mangle", "-X", chain))
249 LOG(ERROR) << "Failed to delete " << chain << " mangle chain";
250 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900251}
252
Hugo Benichi33860d72020-07-09 16:34:01 +0900253bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
254 // Try first to delete any netns with name |netns_name| in case patchpanel
255 // did not exit cleanly.
256 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
257 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
258 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
259}
260
261bool Datapath::NetnsDeleteName(const std::string& netns_name) {
262 return process_runner_->ip_netns_delete(netns_name) == 0;
263}
264
Garrick Evans8a949dc2019-07-18 16:17:53 +0900265bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900266 uint32_t ipv4_addr,
267 uint32_t ipv4_prefix_len) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900268 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900269 if (process_runner_->brctl("addbr", {ifname}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900270 return false;
271 }
272
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900273 if (process_runner_->ip(
274 "addr", "add",
275 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
276 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
277 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900278 RemoveBridge(ifname);
279 return false;
280 }
281
282 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900283 RemoveBridge(ifname);
284 return false;
285 }
286
287 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900288 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900289 RemoveBridge(ifname);
290 return false;
291 }
292
293 return true;
294}
295
296void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900297 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900298 process_runner_->ip("link", "set", {ifname, "down"});
Garrick Evans8e8e3472020-01-23 14:03:50 +0900299 process_runner_->brctl("delbr", {ifname});
Garrick Evans8a949dc2019-07-18 16:17:53 +0900300}
301
Garrick Evans621ed262019-11-13 12:28:43 +0900302bool Datapath::AddToBridge(const std::string& br_ifname,
303 const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900304 return (process_runner_->brctl("addif", {br_ifname, ifname}) == 0);
Garrick Evans621ed262019-11-13 12:28:43 +0900305}
306
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900307std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900308 const MacAddress* mac_addr,
309 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900310 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900311 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
312 if (!dev.is_valid()) {
313 PLOG(ERROR) << "Failed to open " << kTunDev;
314 return "";
315 }
316
317 struct ifreq ifr;
318 memset(&ifr, 0, sizeof(ifr));
319 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
320 sizeof(ifr.ifr_name));
321 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
322
323 // If a template was given as the name, ifr_name will be updated with the
324 // actual interface name.
325 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900326 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900327 return "";
328 }
329 const char* ifname = ifr.ifr_name;
330
331 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900332 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900333 return "";
334 }
335
Garrick Evans4f9f5572019-11-26 10:25:16 +0900336 if (!user.empty()) {
337 uid_t uid = -1;
338 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
339 PLOG(ERROR) << "Unable to look up UID for " << user;
340 RemoveTAP(ifname);
341 return "";
342 }
343 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
344 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
345 << ifname;
346 RemoveTAP(ifname);
347 return "";
348 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900349 }
350
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900351 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900352 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
353 if (!sock.is_valid()) {
354 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900355 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900356 RemoveTAP(ifname);
357 return "";
358 }
359
Garrick Evans621ed262019-11-13 12:28:43 +0900360 if (ipv4_addr) {
361 struct sockaddr_in* addr =
362 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
363 addr->sin_family = AF_INET;
364 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
365 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
366 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
367 << " {" << ipv4_addr->ToCidrString() << "}";
368 RemoveTAP(ifname);
369 return "";
370 }
371
372 struct sockaddr_in* netmask =
373 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
374 netmask->sin_family = AF_INET;
375 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
376 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
377 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
378 << " {" << ipv4_addr->ToCidrString() << "}";
379 RemoveTAP(ifname);
380 return "";
381 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900382 }
383
Garrick Evans621ed262019-11-13 12:28:43 +0900384 if (mac_addr) {
385 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
386 hwaddr->sa_family = ARPHRD_ETHER;
387 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
388 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
389 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
390 << " {" << MacAddressToString(*mac_addr) << "}";
391 RemoveTAP(ifname);
392 return "";
393 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900394 }
395
396 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900397 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900398 RemoveTAP(ifname);
399 return "";
400 }
401
402 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
403 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900404 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900405 RemoveTAP(ifname);
406 return "";
407 }
408
409 return ifname;
410}
411
412void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900413 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900414}
415
Hugo Benichi33860d72020-07-09 16:34:01 +0900416bool Datapath::ConnectVethPair(pid_t netns_pid,
417 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900418 const std::string& veth_ifname,
419 const std::string& peer_ifname,
420 const MacAddress& remote_mac_addr,
421 uint32_t remote_ipv4_addr,
422 uint32_t remote_ipv4_prefix_len,
423 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900424 // Set up the virtual pair across the current namespace and |netns_name|.
425 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
426 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
427 << peer_ifname;
428 return false;
429 }
430
431 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900432 {
Hugo Benichi33860d72020-07-09 16:34:01 +0900433 ScopedNS ns(netns_pid);
434 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900435 LOG(ERROR)
436 << "Cannot create virtual link -- invalid container namespace?";
437 return false;
438 }
439
Hugo Benichi76675592020-04-08 14:29:57 +0900440 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
441 remote_ipv4_prefix_len, true /* link up */,
442 remote_multicast_flag)) {
443 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
444 RemoveInterface(peer_ifname);
445 return false;
446 }
447 }
448
Hugo Benichi76675592020-04-08 14:29:57 +0900449 if (!ToggleInterface(veth_ifname, true /*up*/)) {
450 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
451 RemoveInterface(veth_ifname);
452 return false;
453 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900454
Hugo Benichi76675592020-04-08 14:29:57 +0900455 return true;
456}
457
Hugo Benichi33860d72020-07-09 16:34:01 +0900458bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
459 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900460 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900461 return process_runner_->ip("link", "add",
462 {veth_ifname, "type", "veth", "peer", "name",
463 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900464}
Garrick Evans54861622019-07-19 09:05:09 +0900465
Garrick Evans2470caa2020-03-04 14:15:41 +0900466bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
467 const std::string link = up ? "up" : "down";
468 return process_runner_->ip("link", "set", {ifname, link}) == 0;
469}
Garrick Evans54861622019-07-19 09:05:09 +0900470
Garrick Evans2470caa2020-03-04 14:15:41 +0900471bool Datapath::ConfigureInterface(const std::string& ifname,
472 const MacAddress& mac_addr,
473 uint32_t ipv4_addr,
474 uint32_t ipv4_prefix_len,
475 bool up,
476 bool enable_multicast) {
477 const std::string link = up ? "up" : "down";
478 const std::string multicast = enable_multicast ? "on" : "off";
479 return (process_runner_->ip(
480 "addr", "add",
481 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
482 IPv4AddressToString(
483 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
484 "dev", ifname}) == 0) &&
485 (process_runner_->ip("link", "set",
486 {
487 "dev",
488 ifname,
489 link,
490 "addr",
491 MacAddressToString(mac_addr),
492 "multicast",
493 multicast,
494 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900495}
496
497void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900498 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900499}
500
Hugo Benichi321f23b2020-09-25 15:42:05 +0900501bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
502 const std::string& src_ip) {
503 return process_runner_->iptables("filter", {"-I", "OUTPUT", "-o", oif, "-s",
504 src_ip, "-j", "DROP", "-w"}) == 0;
505}
506
507bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
508 const std::string& src_ip) {
509 return process_runner_->iptables("filter", {"-D", "OUTPUT", "-o", oif, "-s",
510 src_ip, "-j", "DROP", "-w"}) == 0;
511}
512
Hugo Benichifcf81022020-12-04 11:01:37 +0900513bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900514 // Veth interface configuration and client routing configuration:
515 // - attach a name to the client namespace.
516 // - create veth pair across the current namespace and the client namespace.
517 // - configure IPv4 address on remote veth inside client namespace.
518 // - configure IPv4 address on local veth inside host namespace.
519 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900520 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
521 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
522 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900523 return false;
524 }
525
Hugo Benichifcf81022020-12-04 11:01:37 +0900526 if (!ConnectVethPair(
527 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
528 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
529 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900530 LOG(ERROR) << "Failed to create veth pair for"
531 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900532 << nsinfo.pid;
533 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900534 return false;
535 }
536
Hugo Benichifcf81022020-12-04 11:01:37 +0900537 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
538 nsinfo.peer_subnet->AddressAtOffset(0),
539 nsinfo.peer_subnet->PrefixLength(),
540 true /* link up */, false /* enable_multicast */)) {
541 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
542 RemoveInterface(nsinfo.host_ifname);
543 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900544 return false;
545 }
546
547 {
Hugo Benichifcf81022020-12-04 11:01:37 +0900548 ScopedNS ns(nsinfo.pid);
549 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
550 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
551 RemoveInterface(nsinfo.host_ifname);
552 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900553 return false;
554 }
555
Hugo Benichifcf81022020-12-04 11:01:37 +0900556 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
557 INADDR_ANY)) {
558 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
559 << " inside namespace pid " << nsinfo.pid;
560 RemoveInterface(nsinfo.host_ifname);
561 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900562 return false;
563 }
564 }
565
566 // Host namespace routing configuration
567 // - ingress: add route to client subnet via |host_ifname|.
568 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
569 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
570 // Note that by default unsolicited ingress traffic is not forwarded to the
571 // client namespace unless the client specifically set port forwarding
572 // through permission_broker DBus APIs.
573 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
574 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900575 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
576 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
577 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900578 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900579 RemoveInterface(nsinfo.host_ifname);
580 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900581 return false;
582 }
583
Hugo Benichi7c342672020-09-08 09:18:14 +0900584 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900585 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900586 LOG(ERROR) << "Failed to set SNAT for traffic"
587 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900588 << nsinfo.host_ifname;
589 RemoveInterface(nsinfo.host_ifname);
590 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
591 nsinfo.peer_subnet->BaseAddress(), netmask);
592 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
593 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900594 return false;
595 }
596
Hugo Benichi93306e52020-12-04 16:08:00 +0900597 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
598 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
599 nsinfo.route_on_vpn);
600
Hugo Benichi7c342672020-09-08 09:18:14 +0900601 return true;
602}
603
Hugo Benichifcf81022020-12-04 11:01:37 +0900604void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900605 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
606 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
607 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900608 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900609 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
610 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
611 nsinfo.peer_subnet->BaseAddress(),
612 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
613 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900614}
615
Hugo Benichi8d622b52020-08-13 15:24:12 +0900616void Datapath::StartRoutingDevice(const std::string& ext_ifname,
617 const std::string& int_ifname,
618 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900619 TrafficSource source,
620 bool route_on_vpn) {
621 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900622 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
623 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
624 << "->" << int_ifname;
625
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900626 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900627 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
628 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900629
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900630 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900631 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
632 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900633
Hugo Benichi2a940542020-10-26 18:50:49 +0900634 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
635 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
636 << source << " for " << int_ifname;
637
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900638 if (!ext_ifname.empty()) {
639 // If |ext_ifname| is not null, mark egress traffic with the
640 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi2a940542020-10-26 18:50:49 +0900641 if (!ModifyFwmarkRoutingTag("PREROUTING", "-A", ext_ifname, int_ifname))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900642 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
643 << ext_ifname << "<-" << int_ifname;
644 } else {
645 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
646 // PREROUTING to apply any fwmark routing tag saved for the current
647 // connection, and rely on implicit routing to the default logical network
648 // otherwise.
Hugo Benichi1af52392020-11-27 18:09:32 +0900649 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname,
650 kFwmarkRoutingMask))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900651 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
652 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900653
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900654 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900655 // default network is eligible to be routed through a VPN if |route_on_vpn|
656 // is true.
657 if (route_on_vpn &&
658 !ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900659 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900660 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900661}
662
663void Datapath::StopRoutingDevice(const std::string& ext_ifname,
664 const std::string& int_ifname,
665 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900666 TrafficSource source,
667 bool route_on_vpn) {
668 if (source == TrafficSource::ARC && !ext_ifname.empty())
Hugo Benichi8d622b52020-08-13 15:24:12 +0900669 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900670 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
671 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900672 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900673 if (!ext_ifname.empty()) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900674 ModifyFwmarkRoutingTag("PREROUTING", "-D", ext_ifname, int_ifname);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900675 } else {
Hugo Benichi1af52392020-11-27 18:09:32 +0900676 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname,
677 kFwmarkRoutingMask);
Hugo Benichi93306e52020-12-04 16:08:00 +0900678 if (route_on_vpn)
679 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900680 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900681}
682
Garrick Evansf0ab7132019-06-18 14:50:42 +0900683bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
684 const std::string& ipv4_addr) {
685 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900686 if (process_runner_->iptables(
687 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
688 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900689 return false;
690
691 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900692 if (process_runner_->iptables(
693 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
694 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900695 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
696 return false;
697 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900698 if (process_runner_->iptables(
699 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
700 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900701 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
702 return false;
703 }
704
705 return true;
706}
707
708void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
709 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900710 process_runner_->iptables(
711 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
712 "--to-destination", ipv4_addr, "-w"});
713 process_runner_->iptables(
714 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
715 "--to-destination", ipv4_addr, "-w"});
716 process_runner_->iptables(
717 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
718 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900719}
720
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900721// TODO(b/161507671) Stop relying on the traffic fwmark 1/1 once forwarded
722// egress traffic is routed through the fwmark routing tag.
Garrick Evansd291af62020-05-25 10:39:06 +0900723bool Datapath::AddSNATMarkRules() {
Taoyu Li79871c92020-07-02 16:09:39 +0900724 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
725 // need to be explicitly dropped.
726 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900727 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
Taoyu Li79871c92020-07-02 16:09:39 +0900728 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0) {
729 return false;
730 }
Garrick Evansd291af62020-05-25 10:39:06 +0900731 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900732 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900733 "ACCEPT", "-w"}) != 0) {
734 return false;
735 }
736 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900737 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900738 "MASQUERADE", "-w"}) != 0) {
739 RemoveSNATMarkRules();
740 return false;
741 }
742 return true;
743}
744
745void Datapath::RemoveSNATMarkRules() {
746 process_runner_->iptables("nat", {"-D", "POSTROUTING", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900747 "1/1", "-j", "MASQUERADE", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900748 process_runner_->iptables("filter", {"-D", "FORWARD", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900749 "1/1", "-j", "ACCEPT", "-w"});
Taoyu Li79871c92020-07-02 16:09:39 +0900750 process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900751 "filter", {"-D", "FORWARD", "-m", "mark", "--mark", "1/1", "-m", "state",
Taoyu Li79871c92020-07-02 16:09:39 +0900752 "--state", "INVALID", "-j", "DROP", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900753}
754
Hugo Benichie8758b52020-04-03 14:49:01 +0900755bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
756 return process_runner_->iptables(
757 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900758 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900759}
760
761void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
762 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900763 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900764}
765
Garrick Evans664a82f2019-12-17 12:18:05 +0900766bool Datapath::MaskInterfaceFlags(const std::string& ifname,
767 uint16_t on,
768 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900769 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
770 if (!sock.is_valid()) {
771 PLOG(ERROR) << "Failed to create control socket";
772 return false;
773 }
774 ifreq ifr;
775 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
776 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
777 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
778 return false;
779 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900780 ifr.ifr_flags |= on;
781 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900782 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900783 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
784 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900785 return false;
786 }
787 return true;
788}
789
Garrick Evans260ff302019-07-25 11:22:50 +0900790bool Datapath::AddIPv6HostRoute(const std::string& ifname,
791 const std::string& ipv6_addr,
792 int ipv6_prefix_len) {
793 std::string ipv6_addr_cidr =
794 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
795
Garrick Evans8e8e3472020-01-23 14:03:50 +0900796 return process_runner_->ip6("route", "replace",
797 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900798}
799
800void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
801 const std::string& ipv6_addr,
802 int ipv6_prefix_len) {
803 std::string ipv6_addr_cidr =
804 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
805
Garrick Evans8e8e3472020-01-23 14:03:50 +0900806 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900807}
808
Taoyu Lia0727dc2020-09-24 19:54:59 +0900809bool Datapath::AddIPv6Address(const std::string& ifname,
810 const std::string& ipv6_addr) {
811 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900812}
813
Taoyu Lia0727dc2020-09-24 19:54:59 +0900814void Datapath::RemoveIPv6Address(const std::string& ifname,
815 const std::string& ipv6_addr) {
816 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900817}
818
Hugo Benichi76be34a2020-08-26 22:35:54 +0900819void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi1af52392020-11-27 18:09:32 +0900820 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi76be34a2020-08-26 22:35:54 +0900821 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
822 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900823 // Save in CONNMARK the source tag for egress traffic of this connection.
824 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
825 kFwmarkAllSourcesMask))
826 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
827 "source tag on "
828 << ext_ifname;
829 // Restore from CONNMARK the source tag for ingress traffic of this connection
830 // (returned traffic).
831 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
832 kFwmarkAllSourcesMask))
833 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
834 "traffic received on "
835 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900836}
837
838void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
839 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
840 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900841 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
842 kFwmarkAllSourcesMask))
843 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
844 "fwmark source tag on "
845 << ext_ifname;
846 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
847 kFwmarkAllSourcesMask))
848 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
849 "traffic received on "
850 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900851}
852
Hugo Benichi2a940542020-10-26 18:50:49 +0900853void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
854 StartConnectionPinning(vpn_ifname);
855 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", vpn_ifname, ""))
856 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
857}
858
859void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
860 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", vpn_ifname, ""))
861 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
862 StopConnectionPinning(vpn_ifname);
863}
864
Hugo Benichi76be34a2020-08-26 22:35:54 +0900865bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
866 const std::string& op,
867 const std::string& oif) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900868 int ifindex = FindIfIndex(oif);
869 if (ifindex == 0) {
870 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
871 return false;
872 }
873
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900874 return ModifyConnmarkSet(family, "POSTROUTING", op, oif,
875 Fwmark::FromIfIndex(ifindex), kFwmarkRoutingMask);
876}
877
878bool Datapath::ModifyConnmarkSet(IpFamily family,
879 const std::string& chain,
880 const std::string& op,
881 const std::string& oif,
882 Fwmark mark,
883 Fwmark mask) {
884 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
885 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
886 return false;
887 }
888
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900889 std::vector<std::string> args = {op, chain};
890 if (!oif.empty()) {
891 args.push_back("-o");
892 args.push_back(oif);
893 }
894 args.push_back("-j");
895 args.push_back("CONNMARK");
896 args.push_back("--set-mark");
897 args.push_back(mark.ToString() + "/" + mask.ToString());
898 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +0900899
Hugo Benichi58f264a2020-10-16 18:16:05 +0900900 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +0900901}
902
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900903bool Datapath::ModifyConnmarkRestore(IpFamily family,
904 const std::string& chain,
905 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +0900906 const std::string& iif,
907 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900908 if (chain != "OUTPUT" && (chain != "PREROUTING" || iif.empty())) {
909 LOG(ERROR) << "Invalid arguments chain=" << chain << " iif=" << iif;
910 return false;
911 }
912
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900913 std::vector<std::string> args = {op, chain};
914 if (!iif.empty()) {
915 args.push_back("-i");
916 args.push_back(iif);
917 }
918 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +0900919 mask.ToString(), "-w"});
920 return ModifyIptables(family, "mangle", args);
921}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900922
Hugo Benichi1af52392020-11-27 18:09:32 +0900923bool Datapath::ModifyConnmarkSave(IpFamily family,
924 const std::string& chain,
925 const std::string& op,
926 const std::string& oif,
927 Fwmark mask) {
928 std::vector<std::string> args = {op, chain};
929 if (!oif.empty()) {
930 args.push_back("-o");
931 args.push_back(oif);
932 }
933 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
934 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +0900935 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900936}
937
Hugo Benichi2a940542020-10-26 18:50:49 +0900938bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
939 const std::string& op,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900940 const std::string& ext_ifname,
941 const std::string& int_ifname) {
942 int ifindex = FindIfIndex(ext_ifname);
943 if (ifindex == 0) {
944 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
945 return false;
946 }
947
Hugo Benichi2a940542020-10-26 18:50:49 +0900948 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900949 0 /*classid*/, Fwmark::FromIfIndex(ifindex),
950 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900951}
952
Hugo Benichi9be19b12020-08-14 15:33:40 +0900953bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
954 const std::string& iif,
955 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900956 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900957 0 /*classid*/, Fwmark::FromSource(source),
958 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900959}
960
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900961bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
962 TrafficSource source) {
963 std::vector<std::string> args = {"-A",
964 kApplyLocalSourceMarkChain,
965 "-m",
966 "mark",
967 "--mark",
968 "0x0/" + kFwmarkAllSourcesMask.ToString(),
969 "-j",
970 "MARK",
971 "--set-mark",
972 Fwmark::FromSource(source).ToString() + "/" +
973 kFwmarkAllSourcesMask.ToString(),
974 "-w"};
975 return ModifyIptables(IpFamily::Dual, "mangle", args);
976}
Hugo Benichi9be19b12020-08-14 15:33:40 +0900977
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900978bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
979 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900980 if (std::string(source.uid_name).empty() && source.classid == 0)
981 return false;
982
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900983 Fwmark mark = Fwmark::FromSource(source.source_type);
984 if (source.is_on_vpn)
985 mark = mark | kFwmarkRouteOnVpn;
986
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900987 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
988 "" /*iif*/, source.uid_name, source.classid, mark,
989 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900990}
991
992bool Datapath::ModifyFwmark(IpFamily family,
993 const std::string& chain,
994 const std::string& op,
995 const std::string& iif,
996 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900997 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900998 Fwmark mark,
999 Fwmark mask,
1000 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001001 std::vector<std::string> args = {op, chain};
1002 if (!iif.empty()) {
1003 args.push_back("-i");
1004 args.push_back(iif);
1005 }
1006 if (!uid_name.empty()) {
1007 args.push_back("-m");
1008 args.push_back("owner");
1009 args.push_back("--uid-owner");
1010 args.push_back(uid_name);
1011 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001012 if (classid != 0) {
1013 args.push_back("-m");
1014 args.push_back("cgroup");
1015 args.push_back("--cgroup");
1016 args.push_back(base::StringPrintf("0x%08x", classid));
1017 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001018 args.push_back("-j");
1019 args.push_back("MARK");
1020 args.push_back("--set-mark");
1021 args.push_back(mark.ToString() + "/" + mask.ToString());
1022 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001023
Hugo Benichi58f264a2020-10-16 18:16:05 +09001024 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001025}
1026
Hugo Benichid82d8832020-08-14 10:05:03 +09001027bool Datapath::ModifyIpForwarding(IpFamily family,
1028 const std::string& op,
1029 const std::string& iif,
1030 const std::string& oif,
1031 bool log_failures) {
1032 if (iif.empty() && oif.empty()) {
1033 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1034 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001035 return false;
1036 }
1037
Hugo Benichid82d8832020-08-14 10:05:03 +09001038 std::vector<std::string> args = {op, "FORWARD"};
1039 if (!iif.empty()) {
1040 args.push_back("-i");
1041 args.push_back(iif);
1042 }
1043 if (!oif.empty()) {
1044 args.push_back("-o");
1045 args.push_back(oif);
1046 }
1047 args.push_back("-j");
1048 args.push_back("ACCEPT");
1049 args.push_back("-w");
1050
Hugo Benichi58f264a2020-10-16 18:16:05 +09001051 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001052}
1053
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001054bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1055 const std::string& op,
1056 const std::string& iif,
1057 Fwmark mark,
1058 Fwmark mask) {
1059 std::vector<std::string> args = {op, chain};
1060 if (!iif.empty()) {
1061 args.push_back("-i");
1062 args.push_back(iif);
1063 }
1064 if (mark.Value() != 0 && mask.Value() != 0) {
1065 args.push_back("-m");
1066 args.push_back("mark");
1067 args.push_back("--mark");
1068 args.push_back(mark.ToString() + "/" + mask.ToString());
1069 }
1070 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1071 return ModifyIptables(IpFamily::Dual, "mangle", args);
1072}
1073
1074bool Datapath::ModifyChain(IpFamily family,
1075 const std::string& table,
1076 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001077 const std::string& chain,
1078 bool log_failures) {
1079 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001080}
1081
1082bool Datapath::ModifyIptables(IpFamily family,
1083 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001084 const std::vector<std::string>& argv,
1085 bool log_failures) {
1086 switch (family) {
1087 case IPv4:
1088 case IPv6:
1089 case Dual:
1090 break;
1091 default:
1092 LOG(ERROR) << "Could not execute iptables command " << table
1093 << base::JoinString(argv, " ") << ": incorrect IP family "
1094 << family;
1095 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001096 }
1097
1098 bool success = true;
1099 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001100 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001101 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001102 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001103 return success;
1104}
1105
Hugo Benichid82d8832020-08-14 10:05:03 +09001106bool Datapath::StartIpForwarding(IpFamily family,
1107 const std::string& iif,
1108 const std::string& oif) {
1109 return ModifyIpForwarding(family, "-A", iif, oif);
1110}
1111
1112bool Datapath::StopIpForwarding(IpFamily family,
1113 const std::string& iif,
1114 const std::string& oif) {
1115 return ModifyIpForwarding(family, "-D", iif, oif);
1116}
1117
1118bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1119 const std::string& ifname2) {
1120 // Only start Ipv6 forwarding if -C returns false and it had not been
1121 // started yet.
1122 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1123 false /*log_failures*/) &&
1124 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1125 return false;
1126 }
1127
1128 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1129 false /*log_failures*/) &&
1130 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001131 RemoveIPv6Forwarding(ifname1, ifname2);
1132 return false;
1133 }
1134
1135 return true;
1136}
1137
1138void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1139 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001140 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1141 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001142}
1143
Garrick Evans3d97a392020-02-21 15:24:37 +09001144bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1145 uint32_t addr,
1146 uint32_t netmask) {
1147 struct rtentry route;
1148 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001149 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1150 SetSockaddrIn(&route.rt_dst, addr & netmask);
1151 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001152 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001153 return ModifyRtentry(SIOCADDRT, &route);
1154}
Garrick Evans3d97a392020-02-21 15:24:37 +09001155
Hugo Benichie8758b52020-04-03 14:49:01 +09001156bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1157 uint32_t addr,
1158 uint32_t netmask) {
1159 struct rtentry route;
1160 memset(&route, 0, sizeof(route));
1161 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1162 SetSockaddrIn(&route.rt_dst, addr & netmask);
1163 SetSockaddrIn(&route.rt_genmask, netmask);
1164 route.rt_flags = RTF_UP | RTF_GATEWAY;
1165 return ModifyRtentry(SIOCDELRT, &route);
1166}
1167
1168bool Datapath::AddIPv4Route(const std::string& ifname,
1169 uint32_t addr,
1170 uint32_t netmask) {
1171 struct rtentry route;
1172 memset(&route, 0, sizeof(route));
1173 SetSockaddrIn(&route.rt_dst, addr & netmask);
1174 SetSockaddrIn(&route.rt_genmask, netmask);
1175 char rt_dev[IFNAMSIZ];
1176 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1177 rt_dev[IFNAMSIZ - 1] = '\0';
1178 route.rt_dev = rt_dev;
1179 route.rt_flags = RTF_UP | RTF_GATEWAY;
1180 return ModifyRtentry(SIOCADDRT, &route);
1181}
1182
1183bool Datapath::DeleteIPv4Route(const std::string& ifname,
1184 uint32_t addr,
1185 uint32_t netmask) {
1186 struct rtentry route;
1187 memset(&route, 0, sizeof(route));
1188 SetSockaddrIn(&route.rt_dst, addr & netmask);
1189 SetSockaddrIn(&route.rt_genmask, netmask);
1190 char rt_dev[IFNAMSIZ];
1191 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1192 rt_dev[IFNAMSIZ - 1] = '\0';
1193 route.rt_dev = rt_dev;
1194 route.rt_flags = RTF_UP | RTF_GATEWAY;
1195 return ModifyRtentry(SIOCDELRT, &route);
1196}
1197
Taoyu Lia0727dc2020-09-24 19:54:59 +09001198bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001199 DCHECK(route);
1200 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001201 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001202 return false;
1203 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001204 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1205 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001206 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001207 return false;
1208 }
1209 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1210 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001211 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001212 return false;
1213 }
1214 return true;
1215}
1216
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001217bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1218 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1219 kArcAddr, kAdbServerPort, ifname,
1220 kLocalhostAddr, kAdbProxyTcpListenPort);
1221}
1222
1223void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1224 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1225 kArcAddr, kAdbServerPort, ifname,
1226 kLocalhostAddr, kAdbProxyTcpListenPort);
1227}
1228
1229bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1230 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1231 kAdbProxyTcpListenPort, ifname);
1232}
1233
1234void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1235 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1236 kAdbProxyTcpListenPort, ifname);
1237}
1238
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001239void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1240 if_nametoindex_[ifname] = ifindex;
1241}
1242
1243int Datapath::FindIfIndex(const std::string& ifname) {
1244 uint32_t ifindex = if_nametoindex(ifname.c_str());
1245 if (ifindex > 0) {
1246 if_nametoindex_[ifname] = ifindex;
1247 return ifindex;
1248 }
1249
1250 const auto it = if_nametoindex_.find(ifname);
1251 if (it != if_nametoindex_.end())
1252 return it->second;
1253
1254 return 0;
1255}
1256
Hugo Benichifcf81022020-12-04 11:01:37 +09001257std::ostream& operator<<(std::ostream& stream,
1258 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001259 stream << "{ pid: " << nsinfo.pid
1260 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001261 if (!nsinfo.outbound_ifname.empty()) {
1262 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1263 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001264 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1265 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001266 << ", peer_ifname: " << nsinfo.peer_ifname
1267 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1268 return stream;
1269}
1270
Garrick Evans3388a032020-03-24 11:25:55 +09001271} // namespace patchpanel