blob: 1a7052754a836e74e809c6b112816ed4395adca0 [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>
Garrick Evans54861622019-07-19 09:05:09 +090023#include <base/strings/string_number_conversions.h>
Garrick Evans4f9f5572019-11-26 10:25:16 +090024#include <brillo/userdb_utils.h>
Garrick Evans54861622019-07-19 09:05:09 +090025
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090026#include "patchpanel/adb_proxy.h"
Garrick Evans3388a032020-03-24 11:25:55 +090027#include "patchpanel/net_util.h"
28#include "patchpanel/scoped_ns.h"
Garrick Evansc7ae82c2019-09-04 16:25:10 +090029
Garrick Evans3388a032020-03-24 11:25:55 +090030namespace patchpanel {
Garrick Evans54861622019-07-19 09:05:09 +090031
Garrick Evansc7ae82c2019-09-04 16:25:10 +090032namespace {
Hugo Benichi76675592020-04-08 14:29:57 +090033// TODO(hugobenichi) Consolidate this constant definition in a single place.
34constexpr pid_t kTestPID = -2;
Garrick Evansc7ae82c2019-09-04 16:25:10 +090035constexpr char kDefaultIfname[] = "vmtap%d";
36constexpr char kTunDev[] = "/dev/net/tun";
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090037constexpr char kArcAddr[] = "100.115.92.2";
38constexpr char kLocalhostAddr[] = "127.0.0.1";
39constexpr uint16_t kAdbServerPort = 5555;
Hugo Benichie8758b52020-04-03 14:49:01 +090040
Hugo Benichibf811c62020-09-07 17:30:45 +090041// Constants used for dropping locally originated traffic bound to an incorrect
42// source IPv4 address.
43constexpr char kGuestIPv4Subnet[] = "100.115.92.0/23";
44constexpr std::array<const char*, 6> kPhysicalIfnamePrefixes{
45 {"eth+", "wlan+", "mlan+", "usb+", "wwan+", "rmnet+"}};
46
Hugo Benichi3ef370b2020-11-16 19:07:17 +090047constexpr char kApplyVpnMarkChain[] = "apply_vpn_mark";
48
Garrick Evans8a067562020-05-11 12:47:30 +090049std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
50 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090051 if (n.length() < IFNAMSIZ)
52 return n;
Garrick Evans54861622019-07-19 09:05:09 +090053
Garrick Evans2f581a02020-05-11 10:43:35 +090054 // Best effort attempt to preserve the interface number, assuming it's the
55 // last char in the name.
56 auto c = ifname[ifname.length() - 1];
57 n.resize(IFNAMSIZ - 1);
58 n[n.length() - 1] = c;
59 return n;
Garrick Evans54861622019-07-19 09:05:09 +090060}
Garrick Evansf0ab7132019-06-18 14:50:42 +090061
Hugo Benichiaf9d8a72020-08-26 13:28:13 +090062bool IsValidIpFamily(IpFamily family) {
63 switch (family) {
64 case IPv4:
65 case IPv6:
66 case Dual:
67 return true;
68 default:
69 return false;
70 }
71}
72
Garrick Evans8a067562020-05-11 12:47:30 +090073} // namespace
74
75std::string ArcVethHostName(const std::string& ifname) {
76 return PrefixIfname("veth", ifname);
77}
78
79std::string ArcBridgeName(const std::string& ifname) {
80 return PrefixIfname("arc_", ifname);
81}
82
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090083Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
84 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090085
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090086Datapath::Datapath(MinijailedProcessRunner* process_runner,
87 Firewall* firewall,
88 ioctl_t ioctl_hook)
89 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +090090 CHECK(process_runner_);
91}
92
Garrick Evans260ff302019-07-25 11:22:50 +090093MinijailedProcessRunner& Datapath::runner() const {
94 return *process_runner_;
95}
96
Hugo Benichibf811c62020-09-07 17:30:45 +090097void Datapath::Start() {
98 // Enable IPv4 packet forwarding
99 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
100 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
101 << " Guest connectivity will not work correctly.";
102
103 // Limit local port range: Android owns 47104-61000.
104 // TODO(garrick): The original history behind this tweak is gone. Some
105 // investigation is needed to see if it is still applicable.
106 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
107 "32768 47103") != 0)
108 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
109 << " apps may not work correctly.";
110
111 // Enable IPv6 packet forwarding
112 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
113 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
114 << " IPv6 functionality may be broken.";
115
116 if (!AddSNATMarkRules())
117 LOG(ERROR) << "Failed to install SNAT mark rules."
118 << " Guest connectivity may be broken.";
119
Hugo Benichi58125d32020-09-09 11:25:45 +0900120 // Create a FORWARD ACCEPT rule for connections already established.
121 if (process_runner_->iptables(
122 "filter", {"-A", "FORWARD", "-m", "state", "--state",
123 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900124 LOG(ERROR) << "Failed to install forwarding rule for established"
125 << " connections.";
126
127 // chromium:898210: Drop any locally originated traffic that would exit a
128 // physical interface with a source IPv4 address from the subnet of IPs used
129 // for VMs, containers, and connected namespaces This is needed to prevent
130 // packets leaking with an incorrect src IP when a local process binds to the
131 // wrong interface.
132 for (const auto& oif : kPhysicalIfnamePrefixes) {
133 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
134 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
135 << kGuestIPv4Subnet << " exiting " << oif;
136 }
137
138 if (!AddOutboundIPv4SNATMark("vmtap+"))
139 LOG(ERROR) << "Failed to set up NAT for TAP devices."
140 << " Guest connectivity may be broken.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900141
142 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
143 // traffic that should be routed through a VPN.
144 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyVpnMarkChain))
145 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
146 // Ensure that the chain is empty if patchpanel is restarting after a crash.
147 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyVpnMarkChain))
148 LOG(ERROR) << "Failed to flush " << kApplyVpnMarkChain << " mangle chain";
149 // All local outgoing traffic eligible to VPN routing should traverse the VPN
150 // marking chain.
151 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", "" /*iif*/, kFwmarkRouteOnVpn,
152 kFwmarkVpnMask))
153 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
154 // Any traffic that already has a routing tag applied is accepted.
155 if (!ModifyIptables(
156 IpFamily::Dual, "mangle",
157 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
158 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
159 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
160 "connections";
161 // TODO(b/161507671) Dynamically add fwmark routing tagging rules based on
162 // the VPN tunnel interface.
Hugo Benichibf811c62020-09-07 17:30:45 +0900163}
164
165void Datapath::Stop() {
166 RemoveOutboundIPv4SNATMark("vmtap+");
Hugo Benichi58125d32020-09-09 11:25:45 +0900167 process_runner_->iptables("filter",
168 {"-D", "FORWARD", "-m", "state", "--state",
169 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"});
Hugo Benichibf811c62020-09-07 17:30:45 +0900170 RemoveSNATMarkRules();
171 for (const auto& oif : kPhysicalIfnamePrefixes)
172 RemoveSourceIPv4DropRule(oif, kGuestIPv4Subnet);
173
174 // Restore original local port range.
175 // TODO(garrick): The original history behind this tweak is gone. Some
176 // investigation is needed to see if it is still applicable.
177 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
178 "32768 61000") != 0)
179 LOG(ERROR) << "Failed to restore local port range";
180
181 // Disable packet forwarding
182 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
183 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
184
185 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
186 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900187
188 // Delete the VPN marking mangle chain
189 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-D", "" /*iif*/, kFwmarkRouteOnVpn,
190 kFwmarkVpnMask))
191 LOG(ERROR)
192 << "Failed to remove from mangle OUTPUT chain jump rule to VPN chain";
193 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyVpnMarkChain))
194 LOG(ERROR) << "Failed to flush " << kApplyVpnMarkChain << " mangle chain";
195 if (!ModifyChain(IpFamily::Dual, "mangle", "-X", kApplyVpnMarkChain))
196 LOG(ERROR) << "Failed to delete " << kApplyVpnMarkChain << " mangle chain";
Hugo Benichibf811c62020-09-07 17:30:45 +0900197}
198
Hugo Benichi33860d72020-07-09 16:34:01 +0900199bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
200 // Try first to delete any netns with name |netns_name| in case patchpanel
201 // did not exit cleanly.
202 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
203 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
204 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
205}
206
207bool Datapath::NetnsDeleteName(const std::string& netns_name) {
208 return process_runner_->ip_netns_delete(netns_name) == 0;
209}
210
Garrick Evans8a949dc2019-07-18 16:17:53 +0900211bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900212 uint32_t ipv4_addr,
213 uint32_t ipv4_prefix_len) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900214 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900215 if (process_runner_->brctl("addbr", {ifname}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900216 return false;
217 }
218
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900219 if (process_runner_->ip(
220 "addr", "add",
221 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
222 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
223 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900224 RemoveBridge(ifname);
225 return false;
226 }
227
228 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900229 RemoveBridge(ifname);
230 return false;
231 }
232
233 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900234 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900235 RemoveBridge(ifname);
236 return false;
237 }
238
239 return true;
240}
241
242void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900243 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900244 process_runner_->ip("link", "set", {ifname, "down"});
Garrick Evans8e8e3472020-01-23 14:03:50 +0900245 process_runner_->brctl("delbr", {ifname});
Garrick Evans8a949dc2019-07-18 16:17:53 +0900246}
247
Garrick Evans621ed262019-11-13 12:28:43 +0900248bool Datapath::AddToBridge(const std::string& br_ifname,
249 const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900250 return (process_runner_->brctl("addif", {br_ifname, ifname}) == 0);
Garrick Evans621ed262019-11-13 12:28:43 +0900251}
252
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900253std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900254 const MacAddress* mac_addr,
255 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900256 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900257 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
258 if (!dev.is_valid()) {
259 PLOG(ERROR) << "Failed to open " << kTunDev;
260 return "";
261 }
262
263 struct ifreq ifr;
264 memset(&ifr, 0, sizeof(ifr));
265 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
266 sizeof(ifr.ifr_name));
267 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
268
269 // If a template was given as the name, ifr_name will be updated with the
270 // actual interface name.
271 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900272 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900273 return "";
274 }
275 const char* ifname = ifr.ifr_name;
276
277 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900278 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900279 return "";
280 }
281
Garrick Evans4f9f5572019-11-26 10:25:16 +0900282 if (!user.empty()) {
283 uid_t uid = -1;
284 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
285 PLOG(ERROR) << "Unable to look up UID for " << user;
286 RemoveTAP(ifname);
287 return "";
288 }
289 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
290 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
291 << ifname;
292 RemoveTAP(ifname);
293 return "";
294 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900295 }
296
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900297 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900298 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
299 if (!sock.is_valid()) {
300 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900301 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900302 RemoveTAP(ifname);
303 return "";
304 }
305
Garrick Evans621ed262019-11-13 12:28:43 +0900306 if (ipv4_addr) {
307 struct sockaddr_in* addr =
308 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
309 addr->sin_family = AF_INET;
310 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
311 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
312 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
313 << " {" << ipv4_addr->ToCidrString() << "}";
314 RemoveTAP(ifname);
315 return "";
316 }
317
318 struct sockaddr_in* netmask =
319 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
320 netmask->sin_family = AF_INET;
321 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
322 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
323 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
324 << " {" << ipv4_addr->ToCidrString() << "}";
325 RemoveTAP(ifname);
326 return "";
327 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900328 }
329
Garrick Evans621ed262019-11-13 12:28:43 +0900330 if (mac_addr) {
331 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
332 hwaddr->sa_family = ARPHRD_ETHER;
333 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
334 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
335 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
336 << " {" << MacAddressToString(*mac_addr) << "}";
337 RemoveTAP(ifname);
338 return "";
339 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900340 }
341
342 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900343 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900344 RemoveTAP(ifname);
345 return "";
346 }
347
348 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
349 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900350 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900351 RemoveTAP(ifname);
352 return "";
353 }
354
355 return ifname;
356}
357
358void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900359 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900360}
361
Hugo Benichi33860d72020-07-09 16:34:01 +0900362bool Datapath::ConnectVethPair(pid_t netns_pid,
363 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900364 const std::string& veth_ifname,
365 const std::string& peer_ifname,
366 const MacAddress& remote_mac_addr,
367 uint32_t remote_ipv4_addr,
368 uint32_t remote_ipv4_prefix_len,
369 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900370 // Set up the virtual pair across the current namespace and |netns_name|.
371 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
372 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
373 << peer_ifname;
374 return false;
375 }
376
377 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900378 {
Hugo Benichi33860d72020-07-09 16:34:01 +0900379 ScopedNS ns(netns_pid);
380 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900381 LOG(ERROR)
382 << "Cannot create virtual link -- invalid container namespace?";
383 return false;
384 }
385
Hugo Benichi76675592020-04-08 14:29:57 +0900386 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
387 remote_ipv4_prefix_len, true /* link up */,
388 remote_multicast_flag)) {
389 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
390 RemoveInterface(peer_ifname);
391 return false;
392 }
393 }
394
Hugo Benichi76675592020-04-08 14:29:57 +0900395 if (!ToggleInterface(veth_ifname, true /*up*/)) {
396 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
397 RemoveInterface(veth_ifname);
398 return false;
399 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900400
Hugo Benichi76675592020-04-08 14:29:57 +0900401 return true;
402}
403
Hugo Benichi33860d72020-07-09 16:34:01 +0900404bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
405 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900406 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900407 return process_runner_->ip("link", "add",
408 {veth_ifname, "type", "veth", "peer", "name",
409 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900410}
Garrick Evans54861622019-07-19 09:05:09 +0900411
Garrick Evans2470caa2020-03-04 14:15:41 +0900412bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
413 const std::string link = up ? "up" : "down";
414 return process_runner_->ip("link", "set", {ifname, link}) == 0;
415}
Garrick Evans54861622019-07-19 09:05:09 +0900416
Garrick Evans2470caa2020-03-04 14:15:41 +0900417bool Datapath::ConfigureInterface(const std::string& ifname,
418 const MacAddress& mac_addr,
419 uint32_t ipv4_addr,
420 uint32_t ipv4_prefix_len,
421 bool up,
422 bool enable_multicast) {
423 const std::string link = up ? "up" : "down";
424 const std::string multicast = enable_multicast ? "on" : "off";
425 return (process_runner_->ip(
426 "addr", "add",
427 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
428 IPv4AddressToString(
429 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
430 "dev", ifname}) == 0) &&
431 (process_runner_->ip("link", "set",
432 {
433 "dev",
434 ifname,
435 link,
436 "addr",
437 MacAddressToString(mac_addr),
438 "multicast",
439 multicast,
440 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900441}
442
443void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900444 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900445}
446
Hugo Benichi321f23b2020-09-25 15:42:05 +0900447bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
448 const std::string& src_ip) {
449 return process_runner_->iptables("filter", {"-I", "OUTPUT", "-o", oif, "-s",
450 src_ip, "-j", "DROP", "-w"}) == 0;
451}
452
453bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
454 const std::string& src_ip) {
455 return process_runner_->iptables("filter", {"-D", "OUTPUT", "-o", oif, "-s",
456 src_ip, "-j", "DROP", "-w"}) == 0;
457}
458
Hugo Benichi7c342672020-09-08 09:18:14 +0900459bool Datapath::StartRoutingNamespace(pid_t pid,
460 const std::string& netns_name,
461 const std::string& host_ifname,
462 const std::string& peer_ifname,
463 uint32_t subnet_ipv4_addr,
464 uint32_t subnet_prefixlen,
465 uint32_t host_ipv4_addr,
466 uint32_t peer_ipv4_addr,
467 const MacAddress& peer_mac_addr) {
468 // Veth interface configuration and client routing configuration:
469 // - attach a name to the client namespace.
470 // - create veth pair across the current namespace and the client namespace.
471 // - configure IPv4 address on remote veth inside client namespace.
472 // - configure IPv4 address on local veth inside host namespace.
473 // - add a default IPv4 /0 route sending traffic to that remote veth.
474 if (!NetnsAttachName(netns_name, pid)) {
475 LOG(ERROR) << "Failed to attach name " << netns_name << " to namespace pid "
476 << pid;
477 return false;
478 }
479
480 if (!ConnectVethPair(pid, netns_name, host_ifname, peer_ifname, peer_mac_addr,
481 peer_ipv4_addr, subnet_prefixlen,
482 false /* enable_multicast */)) {
483 LOG(ERROR) << "Failed to create veth pair for"
484 " namespace pid "
485 << pid;
486 NetnsDeleteName(netns_name);
487 return false;
488 }
489
490 if (!ConfigureInterface(host_ifname, peer_mac_addr, host_ipv4_addr,
491 subnet_prefixlen, true /* link up */,
492 false /* enable_multicast */)) {
493 LOG(ERROR) << "Cannot configure host interface " << host_ifname;
494 RemoveInterface(host_ifname);
495 NetnsDeleteName(netns_name);
496 return false;
497 }
498
499 {
500 ScopedNS ns(pid);
501 if (!ns.IsValid() && pid != kTestPID) {
502 LOG(ERROR) << "Invalid namespace pid " << pid;
503 RemoveInterface(host_ifname);
504 NetnsDeleteName(netns_name);
505 return false;
506 }
507
508 if (!AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY)) {
509 LOG(ERROR) << "Failed to add default /0 route to " << host_ifname
510 << " inside namespace pid " << pid;
511 RemoveInterface(host_ifname);
512 NetnsDeleteName(netns_name);
513 return false;
514 }
515 }
516
517 // Host namespace routing configuration
518 // - ingress: add route to client subnet via |host_ifname|.
519 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
520 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
521 // Note that by default unsolicited ingress traffic is not forwarded to the
522 // client namespace unless the client specifically set port forwarding
523 // through permission_broker DBus APIs.
524 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
525 // both ways between client namespace and other guest containers and VMs.
526 // TODO(b/161507671) If outbound_physical_device is defined, then set strong
527 // routing to that interface routing table.
528 uint32_t netmask = Ipv4Netmask(subnet_prefixlen);
529 if (!AddIPv4Route(host_ipv4_addr, subnet_ipv4_addr, netmask)) {
530 LOG(ERROR) << "Failed to set route to client namespace";
531 RemoveInterface(host_ifname);
532 NetnsDeleteName(netns_name);
533 return false;
534 }
535
Hugo Benichi58125d32020-09-09 11:25:45 +0900536 if (!StartIpForwarding(IpFamily::IPv4, "", host_ifname)) {
537 LOG(ERROR) << "Failed to allow FORWARD for ingress traffic into "
Hugo Benichi7c342672020-09-08 09:18:14 +0900538 << host_ifname;
539 RemoveInterface(host_ifname);
540 DeleteIPv4Route(host_ipv4_addr, subnet_ipv4_addr, netmask);
541 NetnsDeleteName(netns_name);
542 return false;
543 }
544
545 // TODO(b/161508179) Add fwmark source tagging based on client usage.
546 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
547 if (!AddOutboundIPv4SNATMark(host_ifname)) {
548 LOG(ERROR) << "Failed to set SNAT for traffic"
549 " outgoing from "
550 << host_ifname;
551 RemoveInterface(host_ifname);
552 DeleteIPv4Route(host_ipv4_addr, subnet_ipv4_addr, netmask);
Hugo Benichi58125d32020-09-09 11:25:45 +0900553 StopIpForwarding(IpFamily::IPv4, "", host_ifname);
Hugo Benichi7c342672020-09-08 09:18:14 +0900554 NetnsDeleteName(netns_name);
555 return false;
556 }
557
558 return true;
559}
560
561void Datapath::StopRoutingNamespace(const std::string& netns_name,
562 const std::string& host_ifname,
563 uint32_t subnet_ipv4_addr,
564 uint32_t subnet_prefixlen,
565 uint32_t host_ipv4_addr) {
566 RemoveInterface(host_ifname);
Hugo Benichi58125d32020-09-09 11:25:45 +0900567 StopIpForwarding(IpFamily::IPv4, "", host_ifname);
Hugo Benichi7c342672020-09-08 09:18:14 +0900568 RemoveOutboundIPv4SNATMark(host_ifname);
569 DeleteIPv4Route(host_ipv4_addr, subnet_ipv4_addr,
570 Ipv4Netmask(subnet_prefixlen));
571 NetnsDeleteName(netns_name);
572}
573
Hugo Benichi8d622b52020-08-13 15:24:12 +0900574void Datapath::StartRoutingDevice(const std::string& ext_ifname,
575 const std::string& int_ifname,
576 uint32_t int_ipv4_addr,
577 TrafficSource source) {
578 if (!ext_ifname.empty() &&
579 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
580 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
581 << "->" << int_ifname;
582
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900583 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900584 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
585 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900586
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900587 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900588 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
589 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900590
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900591 if (!ext_ifname.empty()) {
592 // If |ext_ifname| is not null, mark egress traffic with the
593 // fwmark routing tag corresponding to |ext_ifname|.
594 if (!ModifyFwmarkRoutingTag("-A", ext_ifname, int_ifname))
595 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
596 << ext_ifname << "<-" << int_ifname;
597 } else {
598 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
599 // PREROUTING to apply any fwmark routing tag saved for the current
600 // connection, and rely on implicit routing to the default logical network
601 // otherwise.
602 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname))
603 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
604 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900605
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900606 // Forwarded traffic from downstream virtual devices routed to the system
607 // logical default network is always eligible to be routed through a VPN.
608 if (!ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
609 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900610 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900611
Hugo Benichi9be19b12020-08-14 15:33:40 +0900612 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
613 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
614 << source << " for " << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900615}
616
617void Datapath::StopRoutingDevice(const std::string& ext_ifname,
618 const std::string& int_ifname,
619 uint32_t int_ipv4_addr,
620 TrafficSource source) {
621 if (!ext_ifname.empty())
622 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900623 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
624 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900625 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900626 if (!ext_ifname.empty()) {
627 ModifyFwmarkRoutingTag("-D", ext_ifname, int_ifname);
628 } else {
629 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname);
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900630 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900631 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900632}
633
Garrick Evansf0ab7132019-06-18 14:50:42 +0900634bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
635 const std::string& ipv4_addr) {
636 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900637 if (process_runner_->iptables(
638 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
639 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900640 return false;
641
642 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900643 if (process_runner_->iptables(
644 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
645 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900646 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
647 return false;
648 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900649 if (process_runner_->iptables(
650 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
651 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900652 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
653 return false;
654 }
655
656 return true;
657}
658
659void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
660 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900661 process_runner_->iptables(
662 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
663 "--to-destination", ipv4_addr, "-w"});
664 process_runner_->iptables(
665 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
666 "--to-destination", ipv4_addr, "-w"});
667 process_runner_->iptables(
668 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
669 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900670}
671
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900672// TODO(b/161507671) Stop relying on the traffic fwmark 1/1 once forwarded
673// egress traffic is routed through the fwmark routing tag.
Garrick Evansd291af62020-05-25 10:39:06 +0900674bool Datapath::AddSNATMarkRules() {
Taoyu Li79871c92020-07-02 16:09:39 +0900675 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
676 // need to be explicitly dropped.
677 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900678 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
Taoyu Li79871c92020-07-02 16:09:39 +0900679 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0) {
680 return false;
681 }
Garrick Evansd291af62020-05-25 10:39:06 +0900682 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900683 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900684 "ACCEPT", "-w"}) != 0) {
685 return false;
686 }
687 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900688 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900689 "MASQUERADE", "-w"}) != 0) {
690 RemoveSNATMarkRules();
691 return false;
692 }
693 return true;
694}
695
696void Datapath::RemoveSNATMarkRules() {
697 process_runner_->iptables("nat", {"-D", "POSTROUTING", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900698 "1/1", "-j", "MASQUERADE", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900699 process_runner_->iptables("filter", {"-D", "FORWARD", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900700 "1/1", "-j", "ACCEPT", "-w"});
Taoyu Li79871c92020-07-02 16:09:39 +0900701 process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900702 "filter", {"-D", "FORWARD", "-m", "mark", "--mark", "1/1", "-m", "state",
Taoyu Li79871c92020-07-02 16:09:39 +0900703 "--state", "INVALID", "-j", "DROP", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900704}
705
Hugo Benichie8758b52020-04-03 14:49:01 +0900706bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
707 return process_runner_->iptables(
708 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900709 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900710}
711
712void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
713 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900714 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900715}
716
Garrick Evans664a82f2019-12-17 12:18:05 +0900717bool Datapath::MaskInterfaceFlags(const std::string& ifname,
718 uint16_t on,
719 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900720 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
721 if (!sock.is_valid()) {
722 PLOG(ERROR) << "Failed to create control socket";
723 return false;
724 }
725 ifreq ifr;
726 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
727 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
728 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
729 return false;
730 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900731 ifr.ifr_flags |= on;
732 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900733 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900734 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
735 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900736 return false;
737 }
738 return true;
739}
740
Garrick Evans260ff302019-07-25 11:22:50 +0900741bool Datapath::AddIPv6HostRoute(const std::string& ifname,
742 const std::string& ipv6_addr,
743 int ipv6_prefix_len) {
744 std::string ipv6_addr_cidr =
745 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
746
Garrick Evans8e8e3472020-01-23 14:03:50 +0900747 return process_runner_->ip6("route", "replace",
748 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900749}
750
751void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
752 const std::string& ipv6_addr,
753 int ipv6_prefix_len) {
754 std::string ipv6_addr_cidr =
755 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
756
Garrick Evans8e8e3472020-01-23 14:03:50 +0900757 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900758}
759
Taoyu Lia0727dc2020-09-24 19:54:59 +0900760bool Datapath::AddIPv6Address(const std::string& ifname,
761 const std::string& ipv6_addr) {
762 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900763}
764
Taoyu Lia0727dc2020-09-24 19:54:59 +0900765void Datapath::RemoveIPv6Address(const std::string& ifname,
766 const std::string& ipv6_addr) {
767 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900768}
769
Hugo Benichi76be34a2020-08-26 22:35:54 +0900770void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
771 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
772 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
773}
774
775void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
776 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
777 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
778}
779
780bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
781 const std::string& op,
782 const std::string& oif) {
783 if (oif.empty()) {
Hugo Benichibf811c62020-09-07 17:30:45 +0900784 LOG(ERROR) << "Cannot change POSTROUTING CONNMARK set-mark with no"
785 " interface specified";
Hugo Benichi76be34a2020-08-26 22:35:54 +0900786 return false;
787 }
788
789 if (!IsValidIpFamily(family)) {
790 LOG(ERROR) << "Cannot change POSTROUTING CONNMARK set-mark for " << oif
791 << ": incorrect IP family " << family;
792 return false;
793 }
794
795 int ifindex = FindIfIndex(oif);
796 if (ifindex == 0) {
797 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
798 return false;
799 }
800
801 std::vector<std::string> args = {op,
802 "POSTROUTING",
803 "-o",
804 oif,
805 "-j",
806 "CONNMARK",
807 "--set-mark",
808 Fwmark::FromIfIndex(ifindex).ToString() +
809 "/" + kFwmarkRoutingMask.ToString(),
810 "-w"};
811
812 bool success = true;
813 if (family & IPv4)
814 success &= process_runner_->iptables("mangle", args) == 0;
815 if (family & IPv6)
816 success &= process_runner_->ip6tables("mangle", args) == 0;
817 return false;
818}
819
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900820bool Datapath::ModifyConnmarkRestore(IpFamily family,
821 const std::string& chain,
822 const std::string& op,
823 const std::string& iif) {
824 if (chain != "OUTPUT" && (chain != "PREROUTING" || iif.empty())) {
825 LOG(ERROR) << "Invalid arguments chain=" << chain << " iif=" << iif;
826 return false;
827 }
828
829 if (!IsValidIpFamily(family)) {
830 LOG(ERROR) << "Cannot change " << chain << " -j CONNMARK restore-mark"
831 << " for " << iif << ": incorrect IP family " << family;
832 return false;
833 }
834
835 std::vector<std::string> args = {op, chain};
836 if (!iif.empty()) {
837 args.push_back("-i");
838 args.push_back(iif);
839 }
840 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi7c342672020-09-08 09:18:14 +0900841 kFwmarkRoutingMask.ToString(), "-w"});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900842
843 bool success = true;
844 if (family & IPv4)
845 success &= process_runner_->iptables("mangle", args) == 0;
846 if (family & IPv6)
847 success &= process_runner_->ip6tables("mangle", args) == 0;
848 return success;
849}
850
851bool Datapath::ModifyFwmarkRoutingTag(const std::string& op,
852 const std::string& ext_ifname,
853 const std::string& int_ifname) {
854 int ifindex = FindIfIndex(ext_ifname);
855 if (ifindex == 0) {
856 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
857 return false;
858 }
859
860 return ModifyFwmarkPrerouting(IpFamily::Dual, op, int_ifname,
861 Fwmark::FromIfIndex(ifindex),
862 kFwmarkRoutingMask);
863}
864
Hugo Benichi9be19b12020-08-14 15:33:40 +0900865bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
866 const std::string& iif,
867 TrafficSource source) {
868 return ModifyFwmarkPrerouting(IpFamily::Dual, op, iif,
869 Fwmark::FromSource(source),
870 kFwmarkAllSourcesMask);
871}
872
873bool Datapath::ModifyFwmarkPrerouting(IpFamily family,
874 const std::string& op,
875 const std::string& iif,
876 Fwmark mark,
877 Fwmark mask,
878 bool log_failures) {
879 if (iif.empty()) {
880 LOG(ERROR)
881 << "Cannot change PREROUTING set-fwmark with no interface specified";
882 return false;
883 }
884
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900885 if (!IsValidIpFamily(family)) {
886 LOG(ERROR) << "Cannot change PREROUTING set-fwmark for " << iif
887 << ": incorrect IP family " << family;
888 return false;
Hugo Benichi9be19b12020-08-14 15:33:40 +0900889 }
890
891 std::vector<std::string> args = {
892 op, "PREROUTING", "-i", iif,
893 "-j", "MARK", "--set-mark", mark.ToString() + "/" + mask.ToString(),
894 "-w"};
895
896 bool success = true;
Hugo Benichi5c9c11c2020-09-15 17:25:26 +0900897 if (family & IPv4)
Hugo Benichi9be19b12020-08-14 15:33:40 +0900898 success &= process_runner_->iptables("mangle", args, log_failures) == 0;
Hugo Benichi5c9c11c2020-09-15 17:25:26 +0900899 if (family & IPv6)
Hugo Benichi9be19b12020-08-14 15:33:40 +0900900 success &= process_runner_->ip6tables("mangle", args, log_failures) == 0;
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900901 return success;
Hugo Benichi9be19b12020-08-14 15:33:40 +0900902}
903
Hugo Benichid82d8832020-08-14 10:05:03 +0900904bool Datapath::ModifyIpForwarding(IpFamily family,
905 const std::string& op,
906 const std::string& iif,
907 const std::string& oif,
908 bool log_failures) {
909 if (iif.empty() && oif.empty()) {
910 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
911 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +0900912 return false;
913 }
914
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900915 if (!IsValidIpFamily(family)) {
916 LOG(ERROR) << "Cannot change IP forwarding from \"" << iif << "\" to \""
917 << oif << "\": incorrect IP family " << family;
918 return false;
Hugo Benichid82d8832020-08-14 10:05:03 +0900919 }
920
921 std::vector<std::string> args = {op, "FORWARD"};
922 if (!iif.empty()) {
923 args.push_back("-i");
924 args.push_back(iif);
925 }
926 if (!oif.empty()) {
927 args.push_back("-o");
928 args.push_back(oif);
929 }
930 args.push_back("-j");
931 args.push_back("ACCEPT");
932 args.push_back("-w");
933
934 bool success = true;
935 if (family & IpFamily::IPv4)
936 success &= process_runner_->iptables("filter", args, log_failures) == 0;
937 if (family & IpFamily::IPv6)
938 success &= process_runner_->ip6tables("filter", args, log_failures) == 0;
939 return success;
940}
941
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900942bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
943 const std::string& op,
944 const std::string& iif,
945 Fwmark mark,
946 Fwmark mask) {
947 std::vector<std::string> args = {op, chain};
948 if (!iif.empty()) {
949 args.push_back("-i");
950 args.push_back(iif);
951 }
952 if (mark.Value() != 0 && mask.Value() != 0) {
953 args.push_back("-m");
954 args.push_back("mark");
955 args.push_back("--mark");
956 args.push_back(mark.ToString() + "/" + mask.ToString());
957 }
958 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
959 return ModifyIptables(IpFamily::Dual, "mangle", args);
960}
961
962bool Datapath::ModifyChain(IpFamily family,
963 const std::string& table,
964 const std::string& op,
965 const std::string& chain) {
966 return ModifyIptables(family, table, {op, chain, "-w"});
967}
968
969bool Datapath::ModifyIptables(IpFamily family,
970 const std::string& table,
971 const std::vector<std::string>& argv) {
972 if (!IsValidIpFamily(family)) {
973 LOG(ERROR) << "Incorrect IP family " << family;
974 return false;
975 }
976
977 bool success = true;
978 if (family & IpFamily::IPv4)
979 success &= process_runner_->iptables(table, argv) == 0;
980 if (family & IpFamily::IPv6)
981 success &= process_runner_->ip6tables(table, argv) == 0;
982 return success;
983}
984
Hugo Benichid82d8832020-08-14 10:05:03 +0900985bool Datapath::StartIpForwarding(IpFamily family,
986 const std::string& iif,
987 const std::string& oif) {
988 return ModifyIpForwarding(family, "-A", iif, oif);
989}
990
991bool Datapath::StopIpForwarding(IpFamily family,
992 const std::string& iif,
993 const std::string& oif) {
994 return ModifyIpForwarding(family, "-D", iif, oif);
995}
996
997bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
998 const std::string& ifname2) {
999 // Only start Ipv6 forwarding if -C returns false and it had not been
1000 // started yet.
1001 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1002 false /*log_failures*/) &&
1003 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1004 return false;
1005 }
1006
1007 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1008 false /*log_failures*/) &&
1009 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001010 RemoveIPv6Forwarding(ifname1, ifname2);
1011 return false;
1012 }
1013
1014 return true;
1015}
1016
1017void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1018 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001019 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1020 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001021}
1022
Garrick Evans3d97a392020-02-21 15:24:37 +09001023bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1024 uint32_t addr,
1025 uint32_t netmask) {
1026 struct rtentry route;
1027 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001028 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1029 SetSockaddrIn(&route.rt_dst, addr & netmask);
1030 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001031 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001032 return ModifyRtentry(SIOCADDRT, &route);
1033}
Garrick Evans3d97a392020-02-21 15:24:37 +09001034
Hugo Benichie8758b52020-04-03 14:49:01 +09001035bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1036 uint32_t addr,
1037 uint32_t netmask) {
1038 struct rtentry route;
1039 memset(&route, 0, sizeof(route));
1040 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1041 SetSockaddrIn(&route.rt_dst, addr & netmask);
1042 SetSockaddrIn(&route.rt_genmask, netmask);
1043 route.rt_flags = RTF_UP | RTF_GATEWAY;
1044 return ModifyRtentry(SIOCDELRT, &route);
1045}
1046
1047bool Datapath::AddIPv4Route(const std::string& ifname,
1048 uint32_t addr,
1049 uint32_t netmask) {
1050 struct rtentry route;
1051 memset(&route, 0, sizeof(route));
1052 SetSockaddrIn(&route.rt_dst, addr & netmask);
1053 SetSockaddrIn(&route.rt_genmask, netmask);
1054 char rt_dev[IFNAMSIZ];
1055 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1056 rt_dev[IFNAMSIZ - 1] = '\0';
1057 route.rt_dev = rt_dev;
1058 route.rt_flags = RTF_UP | RTF_GATEWAY;
1059 return ModifyRtentry(SIOCADDRT, &route);
1060}
1061
1062bool Datapath::DeleteIPv4Route(const std::string& ifname,
1063 uint32_t addr,
1064 uint32_t netmask) {
1065 struct rtentry route;
1066 memset(&route, 0, sizeof(route));
1067 SetSockaddrIn(&route.rt_dst, addr & netmask);
1068 SetSockaddrIn(&route.rt_genmask, netmask);
1069 char rt_dev[IFNAMSIZ];
1070 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1071 rt_dev[IFNAMSIZ - 1] = '\0';
1072 route.rt_dev = rt_dev;
1073 route.rt_flags = RTF_UP | RTF_GATEWAY;
1074 return ModifyRtentry(SIOCDELRT, &route);
1075}
1076
Taoyu Lia0727dc2020-09-24 19:54:59 +09001077bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001078 DCHECK(route);
1079 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001080 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001081 return false;
1082 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001083 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1084 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001085 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001086 return false;
1087 }
1088 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1089 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001090 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001091 return false;
1092 }
1093 return true;
1094}
1095
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001096bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1097 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1098 kArcAddr, kAdbServerPort, ifname,
1099 kLocalhostAddr, kAdbProxyTcpListenPort);
1100}
1101
1102void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1103 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1104 kArcAddr, kAdbServerPort, ifname,
1105 kLocalhostAddr, kAdbProxyTcpListenPort);
1106}
1107
1108bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1109 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1110 kAdbProxyTcpListenPort, ifname);
1111}
1112
1113void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1114 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1115 kAdbProxyTcpListenPort, ifname);
1116}
1117
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001118void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1119 if_nametoindex_[ifname] = ifindex;
1120}
1121
1122int Datapath::FindIfIndex(const std::string& ifname) {
1123 uint32_t ifindex = if_nametoindex(ifname.c_str());
1124 if (ifindex > 0) {
1125 if_nametoindex_[ifname] = ifindex;
1126 return ifindex;
1127 }
1128
1129 const auto it = if_nametoindex_.find(ifname);
1130 if (it != if_nametoindex_.end())
1131 return it->second;
1132
1133 return 0;
1134}
1135
Garrick Evans3388a032020-03-24 11:25:55 +09001136} // namespace patchpanel