blob: 988f781cc4c2e85d10b366b99661e34376cb75e1 [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 Benichid82d8832020-08-14 10:05:03 +090018#include <vector>
19
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>
Hugo Benichi58f264a2020-10-16 18:16:05 +090023#include <base/strings/string_util.h>
Garrick Evans54861622019-07-19 09:05:09 +090024#include <base/strings/string_number_conversions.h>
Garrick Evans4f9f5572019-11-26 10:25:16 +090025#include <brillo/userdb_utils.h>
Garrick Evans54861622019-07-19 09:05:09 +090026
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090027#include "patchpanel/adb_proxy.h"
Garrick Evans3388a032020-03-24 11:25:55 +090028#include "patchpanel/net_util.h"
29#include "patchpanel/scoped_ns.h"
Garrick Evansc7ae82c2019-09-04 16:25:10 +090030
Garrick Evans3388a032020-03-24 11:25:55 +090031namespace patchpanel {
Garrick Evans54861622019-07-19 09:05:09 +090032
Garrick Evansc7ae82c2019-09-04 16:25:10 +090033namespace {
Hugo Benichi76675592020-04-08 14:29:57 +090034// TODO(hugobenichi) Consolidate this constant definition in a single place.
35constexpr pid_t kTestPID = -2;
Garrick Evansc7ae82c2019-09-04 16:25:10 +090036constexpr char kDefaultIfname[] = "vmtap%d";
37constexpr char kTunDev[] = "/dev/net/tun";
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090038constexpr char kArcAddr[] = "100.115.92.2";
39constexpr char kLocalhostAddr[] = "127.0.0.1";
40constexpr uint16_t kAdbServerPort = 5555;
Hugo Benichie8758b52020-04-03 14:49:01 +090041
Hugo Benichibf811c62020-09-07 17:30:45 +090042// Constants used for dropping locally originated traffic bound to an incorrect
43// source IPv4 address.
44constexpr char kGuestIPv4Subnet[] = "100.115.92.0/23";
45constexpr std::array<const char*, 6> kPhysicalIfnamePrefixes{
46 {"eth+", "wlan+", "mlan+", "usb+", "wwan+", "rmnet+"}};
47
Hugo Benichi3a9162b2020-09-09 15:47:40 +090048constexpr char kApplyLocalSourceMarkChain[] = "apply_local_source_mark";
Hugo Benichi3ef370b2020-11-16 19:07:17 +090049constexpr char kApplyVpnMarkChain[] = "apply_vpn_mark";
50
Garrick Evans8a067562020-05-11 12:47:30 +090051std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
52 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090053 if (n.length() < IFNAMSIZ)
54 return n;
Garrick Evans54861622019-07-19 09:05:09 +090055
Garrick Evans2f581a02020-05-11 10:43:35 +090056 // Best effort attempt to preserve the interface number, assuming it's the
57 // last char in the name.
58 auto c = ifname[ifname.length() - 1];
59 n.resize(IFNAMSIZ - 1);
60 n[n.length() - 1] = c;
61 return n;
Garrick Evans54861622019-07-19 09:05:09 +090062}
Garrick Evansf0ab7132019-06-18 14:50:42 +090063
Garrick Evans8a067562020-05-11 12:47:30 +090064} // namespace
65
66std::string ArcVethHostName(const std::string& ifname) {
67 return PrefixIfname("veth", ifname);
68}
69
70std::string ArcBridgeName(const std::string& ifname) {
71 return PrefixIfname("arc_", ifname);
72}
73
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090074Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
75 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090076
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090077Datapath::Datapath(MinijailedProcessRunner* process_runner,
78 Firewall* firewall,
79 ioctl_t ioctl_hook)
80 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +090081 CHECK(process_runner_);
82}
83
Garrick Evans260ff302019-07-25 11:22:50 +090084MinijailedProcessRunner& Datapath::runner() const {
85 return *process_runner_;
86}
87
Hugo Benichibf811c62020-09-07 17:30:45 +090088void Datapath::Start() {
89 // Enable IPv4 packet forwarding
90 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
91 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
92 << " Guest connectivity will not work correctly.";
93
94 // Limit local port range: Android owns 47104-61000.
95 // TODO(garrick): The original history behind this tweak is gone. Some
96 // investigation is needed to see if it is still applicable.
97 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
98 "32768 47103") != 0)
99 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
100 << " apps may not work correctly.";
101
102 // Enable IPv6 packet forwarding
103 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
104 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
105 << " IPv6 functionality may be broken.";
106
107 if (!AddSNATMarkRules())
108 LOG(ERROR) << "Failed to install SNAT mark rules."
109 << " Guest connectivity may be broken.";
110
Hugo Benichi58125d32020-09-09 11:25:45 +0900111 // Create a FORWARD ACCEPT rule for connections already established.
112 if (process_runner_->iptables(
113 "filter", {"-A", "FORWARD", "-m", "state", "--state",
114 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900115 LOG(ERROR) << "Failed to install forwarding rule for established"
116 << " connections.";
117
118 // chromium:898210: Drop any locally originated traffic that would exit a
119 // physical interface with a source IPv4 address from the subnet of IPs used
120 // for VMs, containers, and connected namespaces This is needed to prevent
121 // packets leaking with an incorrect src IP when a local process binds to the
122 // wrong interface.
123 for (const auto& oif : kPhysicalIfnamePrefixes) {
124 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
125 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
126 << kGuestIPv4Subnet << " exiting " << oif;
127 }
128
129 if (!AddOutboundIPv4SNATMark("vmtap+"))
130 LOG(ERROR) << "Failed to set up NAT for TAP devices."
131 << " Guest connectivity may be broken.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900132
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900133 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
134 // tag and tagging the local traffic that should be routed through a VPN.
135 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyLocalSourceMarkChain))
136 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
137 << " mangle chain";
138 // Ensure that the chain is empty if patchpanel is restarting after a crash.
139 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyLocalSourceMarkChain))
140 LOG(ERROR) << "Failed to flush " << kApplyLocalSourceMarkChain
141 << " mangle chain";
142 if (!ModifyIptables(IpFamily::Dual, "mangle",
143 {"-A", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
144 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
145 << " to mangle OUTPUT";
146 // Create rules for tagging local sources with the source tag and the vpn
147 // policy tag.
148 for (const auto& source : kLocalSourceTypes) {
149 if (ModifyFwmarkLocalSourceTag("-A", source))
150 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
151 << " in " << kApplyLocalSourceMarkChain;
152 }
153 // Finally add a catch-all rule for tagging any remaining local sources with
154 // the SYSTEM source tag
155 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
156 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
157
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900158 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
159 // traffic that should be routed through a VPN.
160 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyVpnMarkChain))
161 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
162 // Ensure that the chain is empty if patchpanel is restarting after a crash.
163 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyVpnMarkChain))
164 LOG(ERROR) << "Failed to flush " << kApplyVpnMarkChain << " mangle chain";
165 // All local outgoing traffic eligible to VPN routing should traverse the VPN
166 // marking chain.
167 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", "" /*iif*/, kFwmarkRouteOnVpn,
168 kFwmarkVpnMask))
169 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
170 // Any traffic that already has a routing tag applied is accepted.
171 if (!ModifyIptables(
172 IpFamily::Dual, "mangle",
173 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
174 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
175 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
176 "connections";
177 // TODO(b/161507671) Dynamically add fwmark routing tagging rules based on
178 // the VPN tunnel interface.
Hugo Benichibf811c62020-09-07 17:30:45 +0900179}
180
181void Datapath::Stop() {
182 RemoveOutboundIPv4SNATMark("vmtap+");
Hugo Benichi58125d32020-09-09 11:25:45 +0900183 process_runner_->iptables("filter",
184 {"-D", "FORWARD", "-m", "state", "--state",
185 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"});
Hugo Benichibf811c62020-09-07 17:30:45 +0900186 RemoveSNATMarkRules();
187 for (const auto& oif : kPhysicalIfnamePrefixes)
188 RemoveSourceIPv4DropRule(oif, kGuestIPv4Subnet);
189
190 // Restore original local port range.
191 // TODO(garrick): The original history behind this tweak is gone. Some
192 // investigation is needed to see if it is still applicable.
193 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
194 "32768 61000") != 0)
195 LOG(ERROR) << "Failed to restore local port range";
196
197 // Disable packet forwarding
198 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
199 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
200
201 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
202 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900203
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900204 // Detach the VPN marking mangle chain
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900205 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-D", "" /*iif*/, kFwmarkRouteOnVpn,
206 kFwmarkVpnMask))
207 LOG(ERROR)
208 << "Failed to remove from mangle OUTPUT chain jump rule to VPN chain";
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900209
210 // Detach apply_local_source_mark from mangle PREROUTING
211 if (!ModifyIptables(IpFamily::Dual, "mangle",
212 {"-D", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
213 LOG(ERROR) << "Failed to detach " << kApplyLocalSourceMarkChain
214 << " from mangle OUTPUT";
215
216 // Delete the mangle chains
217 for (const auto* chain : {kApplyLocalSourceMarkChain, kApplyVpnMarkChain}) {
218 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", chain))
219 LOG(ERROR) << "Failed to flush " << chain << " mangle chain";
220
221 if (!ModifyChain(IpFamily::Dual, "mangle", "-X", chain))
222 LOG(ERROR) << "Failed to delete " << chain << " mangle chain";
223 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900224}
225
Hugo Benichi33860d72020-07-09 16:34:01 +0900226bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
227 // Try first to delete any netns with name |netns_name| in case patchpanel
228 // did not exit cleanly.
229 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
230 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
231 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
232}
233
234bool Datapath::NetnsDeleteName(const std::string& netns_name) {
235 return process_runner_->ip_netns_delete(netns_name) == 0;
236}
237
Garrick Evans8a949dc2019-07-18 16:17:53 +0900238bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900239 uint32_t ipv4_addr,
240 uint32_t ipv4_prefix_len) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900241 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900242 if (process_runner_->brctl("addbr", {ifname}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900243 return false;
244 }
245
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900246 if (process_runner_->ip(
247 "addr", "add",
248 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
249 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
250 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900251 RemoveBridge(ifname);
252 return false;
253 }
254
255 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900256 RemoveBridge(ifname);
257 return false;
258 }
259
260 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900261 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900262 RemoveBridge(ifname);
263 return false;
264 }
265
266 return true;
267}
268
269void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900270 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900271 process_runner_->ip("link", "set", {ifname, "down"});
Garrick Evans8e8e3472020-01-23 14:03:50 +0900272 process_runner_->brctl("delbr", {ifname});
Garrick Evans8a949dc2019-07-18 16:17:53 +0900273}
274
Garrick Evans621ed262019-11-13 12:28:43 +0900275bool Datapath::AddToBridge(const std::string& br_ifname,
276 const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900277 return (process_runner_->brctl("addif", {br_ifname, ifname}) == 0);
Garrick Evans621ed262019-11-13 12:28:43 +0900278}
279
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900280std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900281 const MacAddress* mac_addr,
282 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900283 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900284 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
285 if (!dev.is_valid()) {
286 PLOG(ERROR) << "Failed to open " << kTunDev;
287 return "";
288 }
289
290 struct ifreq ifr;
291 memset(&ifr, 0, sizeof(ifr));
292 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
293 sizeof(ifr.ifr_name));
294 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
295
296 // If a template was given as the name, ifr_name will be updated with the
297 // actual interface name.
298 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900299 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900300 return "";
301 }
302 const char* ifname = ifr.ifr_name;
303
304 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900305 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900306 return "";
307 }
308
Garrick Evans4f9f5572019-11-26 10:25:16 +0900309 if (!user.empty()) {
310 uid_t uid = -1;
311 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
312 PLOG(ERROR) << "Unable to look up UID for " << user;
313 RemoveTAP(ifname);
314 return "";
315 }
316 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
317 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
318 << ifname;
319 RemoveTAP(ifname);
320 return "";
321 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900322 }
323
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900324 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900325 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
326 if (!sock.is_valid()) {
327 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900328 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900329 RemoveTAP(ifname);
330 return "";
331 }
332
Garrick Evans621ed262019-11-13 12:28:43 +0900333 if (ipv4_addr) {
334 struct sockaddr_in* addr =
335 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
336 addr->sin_family = AF_INET;
337 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
338 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
339 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
340 << " {" << ipv4_addr->ToCidrString() << "}";
341 RemoveTAP(ifname);
342 return "";
343 }
344
345 struct sockaddr_in* netmask =
346 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
347 netmask->sin_family = AF_INET;
348 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
349 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
350 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
351 << " {" << ipv4_addr->ToCidrString() << "}";
352 RemoveTAP(ifname);
353 return "";
354 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900355 }
356
Garrick Evans621ed262019-11-13 12:28:43 +0900357 if (mac_addr) {
358 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
359 hwaddr->sa_family = ARPHRD_ETHER;
360 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
361 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
362 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
363 << " {" << MacAddressToString(*mac_addr) << "}";
364 RemoveTAP(ifname);
365 return "";
366 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900367 }
368
369 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900370 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900371 RemoveTAP(ifname);
372 return "";
373 }
374
375 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
376 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900377 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900378 RemoveTAP(ifname);
379 return "";
380 }
381
382 return ifname;
383}
384
385void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900386 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900387}
388
Hugo Benichi33860d72020-07-09 16:34:01 +0900389bool Datapath::ConnectVethPair(pid_t netns_pid,
390 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900391 const std::string& veth_ifname,
392 const std::string& peer_ifname,
393 const MacAddress& remote_mac_addr,
394 uint32_t remote_ipv4_addr,
395 uint32_t remote_ipv4_prefix_len,
396 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900397 // Set up the virtual pair across the current namespace and |netns_name|.
398 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
399 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
400 << peer_ifname;
401 return false;
402 }
403
404 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900405 {
Hugo Benichi33860d72020-07-09 16:34:01 +0900406 ScopedNS ns(netns_pid);
407 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900408 LOG(ERROR)
409 << "Cannot create virtual link -- invalid container namespace?";
410 return false;
411 }
412
Hugo Benichi76675592020-04-08 14:29:57 +0900413 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
414 remote_ipv4_prefix_len, true /* link up */,
415 remote_multicast_flag)) {
416 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
417 RemoveInterface(peer_ifname);
418 return false;
419 }
420 }
421
Hugo Benichi76675592020-04-08 14:29:57 +0900422 if (!ToggleInterface(veth_ifname, true /*up*/)) {
423 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
424 RemoveInterface(veth_ifname);
425 return false;
426 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900427
Hugo Benichi76675592020-04-08 14:29:57 +0900428 return true;
429}
430
Hugo Benichi33860d72020-07-09 16:34:01 +0900431bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
432 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900433 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900434 return process_runner_->ip("link", "add",
435 {veth_ifname, "type", "veth", "peer", "name",
436 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900437}
Garrick Evans54861622019-07-19 09:05:09 +0900438
Garrick Evans2470caa2020-03-04 14:15:41 +0900439bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
440 const std::string link = up ? "up" : "down";
441 return process_runner_->ip("link", "set", {ifname, link}) == 0;
442}
Garrick Evans54861622019-07-19 09:05:09 +0900443
Garrick Evans2470caa2020-03-04 14:15:41 +0900444bool Datapath::ConfigureInterface(const std::string& ifname,
445 const MacAddress& mac_addr,
446 uint32_t ipv4_addr,
447 uint32_t ipv4_prefix_len,
448 bool up,
449 bool enable_multicast) {
450 const std::string link = up ? "up" : "down";
451 const std::string multicast = enable_multicast ? "on" : "off";
452 return (process_runner_->ip(
453 "addr", "add",
454 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
455 IPv4AddressToString(
456 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
457 "dev", ifname}) == 0) &&
458 (process_runner_->ip("link", "set",
459 {
460 "dev",
461 ifname,
462 link,
463 "addr",
464 MacAddressToString(mac_addr),
465 "multicast",
466 multicast,
467 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900468}
469
470void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900471 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900472}
473
Hugo Benichi321f23b2020-09-25 15:42:05 +0900474bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
475 const std::string& src_ip) {
476 return process_runner_->iptables("filter", {"-I", "OUTPUT", "-o", oif, "-s",
477 src_ip, "-j", "DROP", "-w"}) == 0;
478}
479
480bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
481 const std::string& src_ip) {
482 return process_runner_->iptables("filter", {"-D", "OUTPUT", "-o", oif, "-s",
483 src_ip, "-j", "DROP", "-w"}) == 0;
484}
485
Hugo Benichi7c342672020-09-08 09:18:14 +0900486bool Datapath::StartRoutingNamespace(pid_t pid,
487 const std::string& netns_name,
488 const std::string& host_ifname,
489 const std::string& peer_ifname,
490 uint32_t subnet_ipv4_addr,
491 uint32_t subnet_prefixlen,
492 uint32_t host_ipv4_addr,
493 uint32_t peer_ipv4_addr,
494 const MacAddress& peer_mac_addr) {
495 // Veth interface configuration and client routing configuration:
496 // - attach a name to the client namespace.
497 // - create veth pair across the current namespace and the client namespace.
498 // - configure IPv4 address on remote veth inside client namespace.
499 // - configure IPv4 address on local veth inside host namespace.
500 // - add a default IPv4 /0 route sending traffic to that remote veth.
501 if (!NetnsAttachName(netns_name, pid)) {
502 LOG(ERROR) << "Failed to attach name " << netns_name << " to namespace pid "
503 << pid;
504 return false;
505 }
506
507 if (!ConnectVethPair(pid, netns_name, host_ifname, peer_ifname, peer_mac_addr,
508 peer_ipv4_addr, subnet_prefixlen,
509 false /* enable_multicast */)) {
510 LOG(ERROR) << "Failed to create veth pair for"
511 " namespace pid "
512 << pid;
513 NetnsDeleteName(netns_name);
514 return false;
515 }
516
517 if (!ConfigureInterface(host_ifname, peer_mac_addr, host_ipv4_addr,
518 subnet_prefixlen, true /* link up */,
519 false /* enable_multicast */)) {
520 LOG(ERROR) << "Cannot configure host interface " << host_ifname;
521 RemoveInterface(host_ifname);
522 NetnsDeleteName(netns_name);
523 return false;
524 }
525
526 {
527 ScopedNS ns(pid);
528 if (!ns.IsValid() && pid != kTestPID) {
529 LOG(ERROR) << "Invalid namespace pid " << pid;
530 RemoveInterface(host_ifname);
531 NetnsDeleteName(netns_name);
532 return false;
533 }
534
535 if (!AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY)) {
536 LOG(ERROR) << "Failed to add default /0 route to " << host_ifname
537 << " inside namespace pid " << pid;
538 RemoveInterface(host_ifname);
539 NetnsDeleteName(netns_name);
540 return false;
541 }
542 }
543
544 // Host namespace routing configuration
545 // - ingress: add route to client subnet via |host_ifname|.
546 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
547 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
548 // Note that by default unsolicited ingress traffic is not forwarded to the
549 // client namespace unless the client specifically set port forwarding
550 // through permission_broker DBus APIs.
551 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
552 // both ways between client namespace and other guest containers and VMs.
553 // TODO(b/161507671) If outbound_physical_device is defined, then set strong
554 // routing to that interface routing table.
555 uint32_t netmask = Ipv4Netmask(subnet_prefixlen);
556 if (!AddIPv4Route(host_ipv4_addr, subnet_ipv4_addr, netmask)) {
557 LOG(ERROR) << "Failed to set route to client namespace";
558 RemoveInterface(host_ifname);
559 NetnsDeleteName(netns_name);
560 return false;
561 }
562
Hugo Benichi58125d32020-09-09 11:25:45 +0900563 if (!StartIpForwarding(IpFamily::IPv4, "", host_ifname)) {
564 LOG(ERROR) << "Failed to allow FORWARD for ingress traffic into "
Hugo Benichi7c342672020-09-08 09:18:14 +0900565 << host_ifname;
566 RemoveInterface(host_ifname);
567 DeleteIPv4Route(host_ipv4_addr, subnet_ipv4_addr, netmask);
568 NetnsDeleteName(netns_name);
569 return false;
570 }
571
572 // TODO(b/161508179) Add fwmark source tagging based on client usage.
573 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
574 if (!AddOutboundIPv4SNATMark(host_ifname)) {
575 LOG(ERROR) << "Failed to set SNAT for traffic"
576 " outgoing from "
577 << host_ifname;
578 RemoveInterface(host_ifname);
579 DeleteIPv4Route(host_ipv4_addr, subnet_ipv4_addr, netmask);
Hugo Benichi58125d32020-09-09 11:25:45 +0900580 StopIpForwarding(IpFamily::IPv4, "", host_ifname);
Hugo Benichi7c342672020-09-08 09:18:14 +0900581 NetnsDeleteName(netns_name);
582 return false;
583 }
584
585 return true;
586}
587
588void Datapath::StopRoutingNamespace(const std::string& netns_name,
589 const std::string& host_ifname,
590 uint32_t subnet_ipv4_addr,
591 uint32_t subnet_prefixlen,
592 uint32_t host_ipv4_addr) {
593 RemoveInterface(host_ifname);
Hugo Benichi58125d32020-09-09 11:25:45 +0900594 StopIpForwarding(IpFamily::IPv4, "", host_ifname);
Hugo Benichi7c342672020-09-08 09:18:14 +0900595 RemoveOutboundIPv4SNATMark(host_ifname);
596 DeleteIPv4Route(host_ipv4_addr, subnet_ipv4_addr,
597 Ipv4Netmask(subnet_prefixlen));
598 NetnsDeleteName(netns_name);
599}
600
Hugo Benichi8d622b52020-08-13 15:24:12 +0900601void Datapath::StartRoutingDevice(const std::string& ext_ifname,
602 const std::string& int_ifname,
603 uint32_t int_ipv4_addr,
604 TrafficSource source) {
605 if (!ext_ifname.empty() &&
606 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
607 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
608 << "->" << int_ifname;
609
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900610 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900611 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
612 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900613
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900614 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900615 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
616 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900617
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900618 if (!ext_ifname.empty()) {
619 // If |ext_ifname| is not null, mark egress traffic with the
620 // fwmark routing tag corresponding to |ext_ifname|.
621 if (!ModifyFwmarkRoutingTag("-A", ext_ifname, int_ifname))
622 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
623 << ext_ifname << "<-" << int_ifname;
624 } else {
625 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
626 // PREROUTING to apply any fwmark routing tag saved for the current
627 // connection, and rely on implicit routing to the default logical network
628 // otherwise.
629 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname))
630 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
631 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900632
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900633 // Forwarded traffic from downstream virtual devices routed to the system
634 // logical default network is always eligible to be routed through a VPN.
635 if (!ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
636 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900637 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900638
Hugo Benichi9be19b12020-08-14 15:33:40 +0900639 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
640 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
641 << source << " for " << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900642}
643
644void Datapath::StopRoutingDevice(const std::string& ext_ifname,
645 const std::string& int_ifname,
646 uint32_t int_ipv4_addr,
647 TrafficSource source) {
648 if (!ext_ifname.empty())
649 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900650 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
651 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900652 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900653 if (!ext_ifname.empty()) {
654 ModifyFwmarkRoutingTag("-D", ext_ifname, int_ifname);
655 } else {
656 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname);
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900657 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900658 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900659}
660
Garrick Evansf0ab7132019-06-18 14:50:42 +0900661bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
662 const std::string& ipv4_addr) {
663 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900664 if (process_runner_->iptables(
665 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
666 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900667 return false;
668
669 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900670 if (process_runner_->iptables(
671 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
672 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900673 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
674 return false;
675 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900676 if (process_runner_->iptables(
677 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
678 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900679 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
680 return false;
681 }
682
683 return true;
684}
685
686void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
687 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900688 process_runner_->iptables(
689 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
690 "--to-destination", ipv4_addr, "-w"});
691 process_runner_->iptables(
692 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
693 "--to-destination", ipv4_addr, "-w"});
694 process_runner_->iptables(
695 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
696 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900697}
698
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900699// TODO(b/161507671) Stop relying on the traffic fwmark 1/1 once forwarded
700// egress traffic is routed through the fwmark routing tag.
Garrick Evansd291af62020-05-25 10:39:06 +0900701bool Datapath::AddSNATMarkRules() {
Taoyu Li79871c92020-07-02 16:09:39 +0900702 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
703 // need to be explicitly dropped.
704 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900705 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
Taoyu Li79871c92020-07-02 16:09:39 +0900706 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0) {
707 return false;
708 }
Garrick Evansd291af62020-05-25 10:39:06 +0900709 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900710 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900711 "ACCEPT", "-w"}) != 0) {
712 return false;
713 }
714 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900715 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900716 "MASQUERADE", "-w"}) != 0) {
717 RemoveSNATMarkRules();
718 return false;
719 }
720 return true;
721}
722
723void Datapath::RemoveSNATMarkRules() {
724 process_runner_->iptables("nat", {"-D", "POSTROUTING", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900725 "1/1", "-j", "MASQUERADE", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900726 process_runner_->iptables("filter", {"-D", "FORWARD", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900727 "1/1", "-j", "ACCEPT", "-w"});
Taoyu Li79871c92020-07-02 16:09:39 +0900728 process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900729 "filter", {"-D", "FORWARD", "-m", "mark", "--mark", "1/1", "-m", "state",
Taoyu Li79871c92020-07-02 16:09:39 +0900730 "--state", "INVALID", "-j", "DROP", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900731}
732
Hugo Benichie8758b52020-04-03 14:49:01 +0900733bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
734 return process_runner_->iptables(
735 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900736 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900737}
738
739void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
740 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900741 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900742}
743
Garrick Evans664a82f2019-12-17 12:18:05 +0900744bool Datapath::MaskInterfaceFlags(const std::string& ifname,
745 uint16_t on,
746 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900747 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
748 if (!sock.is_valid()) {
749 PLOG(ERROR) << "Failed to create control socket";
750 return false;
751 }
752 ifreq ifr;
753 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
754 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
755 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
756 return false;
757 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900758 ifr.ifr_flags |= on;
759 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900760 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900761 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
762 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900763 return false;
764 }
765 return true;
766}
767
Garrick Evans260ff302019-07-25 11:22:50 +0900768bool Datapath::AddIPv6HostRoute(const std::string& ifname,
769 const std::string& ipv6_addr,
770 int ipv6_prefix_len) {
771 std::string ipv6_addr_cidr =
772 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
773
Garrick Evans8e8e3472020-01-23 14:03:50 +0900774 return process_runner_->ip6("route", "replace",
775 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900776}
777
778void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
779 const std::string& ipv6_addr,
780 int ipv6_prefix_len) {
781 std::string ipv6_addr_cidr =
782 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
783
Garrick Evans8e8e3472020-01-23 14:03:50 +0900784 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900785}
786
Taoyu Lia0727dc2020-09-24 19:54:59 +0900787bool Datapath::AddIPv6Address(const std::string& ifname,
788 const std::string& ipv6_addr) {
789 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900790}
791
Taoyu Lia0727dc2020-09-24 19:54:59 +0900792void Datapath::RemoveIPv6Address(const std::string& ifname,
793 const std::string& ipv6_addr) {
794 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900795}
796
Hugo Benichi76be34a2020-08-26 22:35:54 +0900797void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
798 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
799 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
800}
801
802void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
803 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
804 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
805}
806
807bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
808 const std::string& op,
809 const std::string& oif) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900810 int ifindex = FindIfIndex(oif);
811 if (ifindex == 0) {
812 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
813 return false;
814 }
815
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900816 return ModifyConnmarkSet(family, "POSTROUTING", op, oif,
817 Fwmark::FromIfIndex(ifindex), kFwmarkRoutingMask);
818}
819
820bool Datapath::ModifyConnmarkSet(IpFamily family,
821 const std::string& chain,
822 const std::string& op,
823 const std::string& oif,
824 Fwmark mark,
825 Fwmark mask) {
826 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
827 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
828 return false;
829 }
830
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900831 std::vector<std::string> args = {op, chain};
832 if (!oif.empty()) {
833 args.push_back("-o");
834 args.push_back(oif);
835 }
836 args.push_back("-j");
837 args.push_back("CONNMARK");
838 args.push_back("--set-mark");
839 args.push_back(mark.ToString() + "/" + mask.ToString());
840 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +0900841
Hugo Benichi58f264a2020-10-16 18:16:05 +0900842 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +0900843}
844
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900845bool Datapath::ModifyConnmarkRestore(IpFamily family,
846 const std::string& chain,
847 const std::string& op,
848 const std::string& iif) {
849 if (chain != "OUTPUT" && (chain != "PREROUTING" || iif.empty())) {
850 LOG(ERROR) << "Invalid arguments chain=" << chain << " iif=" << iif;
851 return false;
852 }
853
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900854 std::vector<std::string> args = {op, chain};
855 if (!iif.empty()) {
856 args.push_back("-i");
857 args.push_back(iif);
858 }
859 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi7c342672020-09-08 09:18:14 +0900860 kFwmarkRoutingMask.ToString(), "-w"});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900861
Hugo Benichi58f264a2020-10-16 18:16:05 +0900862 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900863}
864
865bool Datapath::ModifyFwmarkRoutingTag(const std::string& op,
866 const std::string& ext_ifname,
867 const std::string& int_ifname) {
868 int ifindex = FindIfIndex(ext_ifname);
869 if (ifindex == 0) {
870 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
871 return false;
872 }
873
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900874 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, int_ifname,
875 "" /*uid_name*/, Fwmark::FromIfIndex(ifindex),
876 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900877}
878
Hugo Benichi9be19b12020-08-14 15:33:40 +0900879bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
880 const std::string& iif,
881 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900882 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
883 Fwmark::FromSource(source), kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900884}
885
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900886bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
887 TrafficSource source) {
888 std::vector<std::string> args = {"-A",
889 kApplyLocalSourceMarkChain,
890 "-m",
891 "mark",
892 "--mark",
893 "0x0/" + kFwmarkAllSourcesMask.ToString(),
894 "-j",
895 "MARK",
896 "--set-mark",
897 Fwmark::FromSource(source).ToString() + "/" +
898 kFwmarkAllSourcesMask.ToString(),
899 "-w"};
900 return ModifyIptables(IpFamily::Dual, "mangle", args);
901}
Hugo Benichi9be19b12020-08-14 15:33:40 +0900902
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900903bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
904 const LocalSourceSpecs& source) {
905 Fwmark mark = Fwmark::FromSource(source.source_type);
906 if (source.is_on_vpn)
907 mark = mark | kFwmarkRouteOnVpn;
908
909 const std::string& uid_name = source.uid_name;
910 if (!uid_name.empty())
911 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
912 "" /*iif*/, uid_name, mark, kFwmarkPolicyMask);
913
914 return false;
915 // TODO(b/167479541) Supports entries specifying a cgroup classid value.
916}
917
918bool Datapath::ModifyFwmark(IpFamily family,
919 const std::string& chain,
920 const std::string& op,
921 const std::string& iif,
922 const std::string& uid_name,
923 Fwmark mark,
924 Fwmark mask,
925 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900926 std::vector<std::string> args = {op, chain};
927 if (!iif.empty()) {
928 args.push_back("-i");
929 args.push_back(iif);
930 }
931 if (!uid_name.empty()) {
932 args.push_back("-m");
933 args.push_back("owner");
934 args.push_back("--uid-owner");
935 args.push_back(uid_name);
936 }
937 args.push_back("-j");
938 args.push_back("MARK");
939 args.push_back("--set-mark");
940 args.push_back(mark.ToString() + "/" + mask.ToString());
941 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +0900942
Hugo Benichi58f264a2020-10-16 18:16:05 +0900943 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900944}
945
Hugo Benichid82d8832020-08-14 10:05:03 +0900946bool Datapath::ModifyIpForwarding(IpFamily family,
947 const std::string& op,
948 const std::string& iif,
949 const std::string& oif,
950 bool log_failures) {
951 if (iif.empty() && oif.empty()) {
952 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
953 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +0900954 return false;
955 }
956
Hugo Benichid82d8832020-08-14 10:05:03 +0900957 std::vector<std::string> args = {op, "FORWARD"};
958 if (!iif.empty()) {
959 args.push_back("-i");
960 args.push_back(iif);
961 }
962 if (!oif.empty()) {
963 args.push_back("-o");
964 args.push_back(oif);
965 }
966 args.push_back("-j");
967 args.push_back("ACCEPT");
968 args.push_back("-w");
969
Hugo Benichi58f264a2020-10-16 18:16:05 +0900970 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +0900971}
972
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900973bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
974 const std::string& op,
975 const std::string& iif,
976 Fwmark mark,
977 Fwmark mask) {
978 std::vector<std::string> args = {op, chain};
979 if (!iif.empty()) {
980 args.push_back("-i");
981 args.push_back(iif);
982 }
983 if (mark.Value() != 0 && mask.Value() != 0) {
984 args.push_back("-m");
985 args.push_back("mark");
986 args.push_back("--mark");
987 args.push_back(mark.ToString() + "/" + mask.ToString());
988 }
989 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
990 return ModifyIptables(IpFamily::Dual, "mangle", args);
991}
992
993bool Datapath::ModifyChain(IpFamily family,
994 const std::string& table,
995 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +0900996 const std::string& chain,
997 bool log_failures) {
998 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900999}
1000
1001bool Datapath::ModifyIptables(IpFamily family,
1002 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001003 const std::vector<std::string>& argv,
1004 bool log_failures) {
1005 switch (family) {
1006 case IPv4:
1007 case IPv6:
1008 case Dual:
1009 break;
1010 default:
1011 LOG(ERROR) << "Could not execute iptables command " << table
1012 << base::JoinString(argv, " ") << ": incorrect IP family "
1013 << family;
1014 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001015 }
1016
1017 bool success = true;
1018 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001019 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001020 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001021 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001022 return success;
1023}
1024
Hugo Benichid82d8832020-08-14 10:05:03 +09001025bool Datapath::StartIpForwarding(IpFamily family,
1026 const std::string& iif,
1027 const std::string& oif) {
1028 return ModifyIpForwarding(family, "-A", iif, oif);
1029}
1030
1031bool Datapath::StopIpForwarding(IpFamily family,
1032 const std::string& iif,
1033 const std::string& oif) {
1034 return ModifyIpForwarding(family, "-D", iif, oif);
1035}
1036
1037bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1038 const std::string& ifname2) {
1039 // Only start Ipv6 forwarding if -C returns false and it had not been
1040 // started yet.
1041 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1042 false /*log_failures*/) &&
1043 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1044 return false;
1045 }
1046
1047 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1048 false /*log_failures*/) &&
1049 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001050 RemoveIPv6Forwarding(ifname1, ifname2);
1051 return false;
1052 }
1053
1054 return true;
1055}
1056
1057void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1058 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001059 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1060 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001061}
1062
Garrick Evans3d97a392020-02-21 15:24:37 +09001063bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1064 uint32_t addr,
1065 uint32_t netmask) {
1066 struct rtentry route;
1067 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001068 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1069 SetSockaddrIn(&route.rt_dst, addr & netmask);
1070 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001071 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001072 return ModifyRtentry(SIOCADDRT, &route);
1073}
Garrick Evans3d97a392020-02-21 15:24:37 +09001074
Hugo Benichie8758b52020-04-03 14:49:01 +09001075bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1076 uint32_t addr,
1077 uint32_t netmask) {
1078 struct rtentry route;
1079 memset(&route, 0, sizeof(route));
1080 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1081 SetSockaddrIn(&route.rt_dst, addr & netmask);
1082 SetSockaddrIn(&route.rt_genmask, netmask);
1083 route.rt_flags = RTF_UP | RTF_GATEWAY;
1084 return ModifyRtentry(SIOCDELRT, &route);
1085}
1086
1087bool Datapath::AddIPv4Route(const std::string& ifname,
1088 uint32_t addr,
1089 uint32_t netmask) {
1090 struct rtentry route;
1091 memset(&route, 0, sizeof(route));
1092 SetSockaddrIn(&route.rt_dst, addr & netmask);
1093 SetSockaddrIn(&route.rt_genmask, netmask);
1094 char rt_dev[IFNAMSIZ];
1095 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1096 rt_dev[IFNAMSIZ - 1] = '\0';
1097 route.rt_dev = rt_dev;
1098 route.rt_flags = RTF_UP | RTF_GATEWAY;
1099 return ModifyRtentry(SIOCADDRT, &route);
1100}
1101
1102bool Datapath::DeleteIPv4Route(const std::string& ifname,
1103 uint32_t addr,
1104 uint32_t netmask) {
1105 struct rtentry route;
1106 memset(&route, 0, sizeof(route));
1107 SetSockaddrIn(&route.rt_dst, addr & netmask);
1108 SetSockaddrIn(&route.rt_genmask, netmask);
1109 char rt_dev[IFNAMSIZ];
1110 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1111 rt_dev[IFNAMSIZ - 1] = '\0';
1112 route.rt_dev = rt_dev;
1113 route.rt_flags = RTF_UP | RTF_GATEWAY;
1114 return ModifyRtentry(SIOCDELRT, &route);
1115}
1116
Taoyu Lia0727dc2020-09-24 19:54:59 +09001117bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001118 DCHECK(route);
1119 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001120 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001121 return false;
1122 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001123 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1124 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001125 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001126 return false;
1127 }
1128 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1129 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001130 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001131 return false;
1132 }
1133 return true;
1134}
1135
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001136bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1137 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1138 kArcAddr, kAdbServerPort, ifname,
1139 kLocalhostAddr, kAdbProxyTcpListenPort);
1140}
1141
1142void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1143 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1144 kArcAddr, kAdbServerPort, ifname,
1145 kLocalhostAddr, kAdbProxyTcpListenPort);
1146}
1147
1148bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1149 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1150 kAdbProxyTcpListenPort, ifname);
1151}
1152
1153void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1154 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1155 kAdbProxyTcpListenPort, ifname);
1156}
1157
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001158void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1159 if_nametoindex_[ifname] = ifindex;
1160}
1161
1162int Datapath::FindIfIndex(const std::string& ifname) {
1163 uint32_t ifindex = if_nametoindex(ifname.c_str());
1164 if (ifindex > 0) {
1165 if_nametoindex_[ifname] = ifindex;
1166 return ifindex;
1167 }
1168
1169 const auto it = if_nametoindex_.find(ifname);
1170 if (it != if_nametoindex_.end())
1171 return it->second;
1172
1173 return 0;
1174}
1175
Garrick Evans3388a032020-03-24 11:25:55 +09001176} // namespace patchpanel