blob: ee1001830fcabc969a59709c69fa5a7a2c3dd8ae [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
Garrick Evans8a067562020-05-11 12:47:30 +090047std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
48 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090049 if (n.length() < IFNAMSIZ)
50 return n;
Garrick Evans54861622019-07-19 09:05:09 +090051
Garrick Evans2f581a02020-05-11 10:43:35 +090052 // Best effort attempt to preserve the interface number, assuming it's the
53 // last char in the name.
54 auto c = ifname[ifname.length() - 1];
55 n.resize(IFNAMSIZ - 1);
56 n[n.length() - 1] = c;
57 return n;
Garrick Evans54861622019-07-19 09:05:09 +090058}
Garrick Evansf0ab7132019-06-18 14:50:42 +090059
Hugo Benichiaf9d8a72020-08-26 13:28:13 +090060bool IsValidIpFamily(IpFamily family) {
61 switch (family) {
62 case IPv4:
63 case IPv6:
64 case Dual:
65 return true;
66 default:
67 return false;
68 }
69}
70
Garrick Evans8a067562020-05-11 12:47:30 +090071} // namespace
72
73std::string ArcVethHostName(const std::string& ifname) {
74 return PrefixIfname("veth", ifname);
75}
76
77std::string ArcBridgeName(const std::string& ifname) {
78 return PrefixIfname("arc_", ifname);
79}
80
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090081Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
82 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090083
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090084Datapath::Datapath(MinijailedProcessRunner* process_runner,
85 Firewall* firewall,
86 ioctl_t ioctl_hook)
87 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +090088 CHECK(process_runner_);
89}
90
Garrick Evans260ff302019-07-25 11:22:50 +090091MinijailedProcessRunner& Datapath::runner() const {
92 return *process_runner_;
93}
94
Hugo Benichibf811c62020-09-07 17:30:45 +090095void Datapath::Start() {
96 // Enable IPv4 packet forwarding
97 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
98 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
99 << " Guest connectivity will not work correctly.";
100
101 // Limit local port range: Android owns 47104-61000.
102 // TODO(garrick): The original history behind this tweak is gone. Some
103 // investigation is needed to see if it is still applicable.
104 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
105 "32768 47103") != 0)
106 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
107 << " apps may not work correctly.";
108
109 // Enable IPv6 packet forwarding
110 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
111 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
112 << " IPv6 functionality may be broken.";
113
114 if (!AddSNATMarkRules())
115 LOG(ERROR) << "Failed to install SNAT mark rules."
116 << " Guest connectivity may be broken.";
117
118 if (!AddForwardEstablishedRule())
119 LOG(ERROR) << "Failed to install forwarding rule for established"
120 << " connections.";
121
122 // chromium:898210: Drop any locally originated traffic that would exit a
123 // physical interface with a source IPv4 address from the subnet of IPs used
124 // for VMs, containers, and connected namespaces This is needed to prevent
125 // packets leaking with an incorrect src IP when a local process binds to the
126 // wrong interface.
127 for (const auto& oif : kPhysicalIfnamePrefixes) {
128 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
129 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
130 << kGuestIPv4Subnet << " exiting " << oif;
131 }
132
133 if (!AddOutboundIPv4SNATMark("vmtap+"))
134 LOG(ERROR) << "Failed to set up NAT for TAP devices."
135 << " Guest connectivity may be broken.";
136}
137
138void Datapath::Stop() {
139 RemoveOutboundIPv4SNATMark("vmtap+");
140 RemoveForwardEstablishedRule();
141 RemoveSNATMarkRules();
142 for (const auto& oif : kPhysicalIfnamePrefixes)
143 RemoveSourceIPv4DropRule(oif, kGuestIPv4Subnet);
144
145 // Restore original local port range.
146 // TODO(garrick): The original history behind this tweak is gone. Some
147 // investigation is needed to see if it is still applicable.
148 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
149 "32768 61000") != 0)
150 LOG(ERROR) << "Failed to restore local port range";
151
152 // Disable packet forwarding
153 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
154 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
155
156 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
157 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
158}
159
Hugo Benichi33860d72020-07-09 16:34:01 +0900160bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
161 // Try first to delete any netns with name |netns_name| in case patchpanel
162 // did not exit cleanly.
163 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
164 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
165 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
166}
167
168bool Datapath::NetnsDeleteName(const std::string& netns_name) {
169 return process_runner_->ip_netns_delete(netns_name) == 0;
170}
171
Garrick Evans8a949dc2019-07-18 16:17:53 +0900172bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900173 uint32_t ipv4_addr,
174 uint32_t ipv4_prefix_len) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900175 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900176 if (process_runner_->brctl("addbr", {ifname}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900177 return false;
178 }
179
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900180 if (process_runner_->ip(
181 "addr", "add",
182 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
183 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
184 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900185 RemoveBridge(ifname);
186 return false;
187 }
188
189 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900190 RemoveBridge(ifname);
191 return false;
192 }
193
194 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900195 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900196 RemoveBridge(ifname);
197 return false;
198 }
199
200 return true;
201}
202
203void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900204 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900205 process_runner_->ip("link", "set", {ifname, "down"});
Garrick Evans8e8e3472020-01-23 14:03:50 +0900206 process_runner_->brctl("delbr", {ifname});
Garrick Evans8a949dc2019-07-18 16:17:53 +0900207}
208
Garrick Evans621ed262019-11-13 12:28:43 +0900209bool Datapath::AddToBridge(const std::string& br_ifname,
210 const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900211 return (process_runner_->brctl("addif", {br_ifname, ifname}) == 0);
Garrick Evans621ed262019-11-13 12:28:43 +0900212}
213
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900214std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900215 const MacAddress* mac_addr,
216 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900217 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900218 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
219 if (!dev.is_valid()) {
220 PLOG(ERROR) << "Failed to open " << kTunDev;
221 return "";
222 }
223
224 struct ifreq ifr;
225 memset(&ifr, 0, sizeof(ifr));
226 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
227 sizeof(ifr.ifr_name));
228 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
229
230 // If a template was given as the name, ifr_name will be updated with the
231 // actual interface name.
232 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900233 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900234 return "";
235 }
236 const char* ifname = ifr.ifr_name;
237
238 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900239 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900240 return "";
241 }
242
Garrick Evans4f9f5572019-11-26 10:25:16 +0900243 if (!user.empty()) {
244 uid_t uid = -1;
245 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
246 PLOG(ERROR) << "Unable to look up UID for " << user;
247 RemoveTAP(ifname);
248 return "";
249 }
250 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
251 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
252 << ifname;
253 RemoveTAP(ifname);
254 return "";
255 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900256 }
257
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900258 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900259 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
260 if (!sock.is_valid()) {
261 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900262 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900263 RemoveTAP(ifname);
264 return "";
265 }
266
Garrick Evans621ed262019-11-13 12:28:43 +0900267 if (ipv4_addr) {
268 struct sockaddr_in* addr =
269 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
270 addr->sin_family = AF_INET;
271 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
272 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
273 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
274 << " {" << ipv4_addr->ToCidrString() << "}";
275 RemoveTAP(ifname);
276 return "";
277 }
278
279 struct sockaddr_in* netmask =
280 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
281 netmask->sin_family = AF_INET;
282 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
283 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
284 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
285 << " {" << ipv4_addr->ToCidrString() << "}";
286 RemoveTAP(ifname);
287 return "";
288 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900289 }
290
Garrick Evans621ed262019-11-13 12:28:43 +0900291 if (mac_addr) {
292 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
293 hwaddr->sa_family = ARPHRD_ETHER;
294 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
295 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
296 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
297 << " {" << MacAddressToString(*mac_addr) << "}";
298 RemoveTAP(ifname);
299 return "";
300 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900301 }
302
303 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900304 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900305 RemoveTAP(ifname);
306 return "";
307 }
308
309 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
310 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900311 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900312 RemoveTAP(ifname);
313 return "";
314 }
315
316 return ifname;
317}
318
319void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900320 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900321}
322
Hugo Benichi33860d72020-07-09 16:34:01 +0900323bool Datapath::ConnectVethPair(pid_t netns_pid,
324 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900325 const std::string& veth_ifname,
326 const std::string& peer_ifname,
327 const MacAddress& remote_mac_addr,
328 uint32_t remote_ipv4_addr,
329 uint32_t remote_ipv4_prefix_len,
330 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900331 // Set up the virtual pair across the current namespace and |netns_name|.
332 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
333 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
334 << peer_ifname;
335 return false;
336 }
337
338 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900339 {
Hugo Benichi33860d72020-07-09 16:34:01 +0900340 ScopedNS ns(netns_pid);
341 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900342 LOG(ERROR)
343 << "Cannot create virtual link -- invalid container namespace?";
344 return false;
345 }
346
Hugo Benichi76675592020-04-08 14:29:57 +0900347 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
348 remote_ipv4_prefix_len, true /* link up */,
349 remote_multicast_flag)) {
350 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
351 RemoveInterface(peer_ifname);
352 return false;
353 }
354 }
355
Hugo Benichi76675592020-04-08 14:29:57 +0900356 if (!ToggleInterface(veth_ifname, true /*up*/)) {
357 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
358 RemoveInterface(veth_ifname);
359 return false;
360 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900361
Hugo Benichi76675592020-04-08 14:29:57 +0900362 return true;
363}
364
Hugo Benichi33860d72020-07-09 16:34:01 +0900365bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
366 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900367 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900368 return process_runner_->ip("link", "add",
369 {veth_ifname, "type", "veth", "peer", "name",
370 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900371}
Garrick Evans54861622019-07-19 09:05:09 +0900372
Garrick Evans2470caa2020-03-04 14:15:41 +0900373bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
374 const std::string link = up ? "up" : "down";
375 return process_runner_->ip("link", "set", {ifname, link}) == 0;
376}
Garrick Evans54861622019-07-19 09:05:09 +0900377
Garrick Evans2470caa2020-03-04 14:15:41 +0900378bool Datapath::ConfigureInterface(const std::string& ifname,
379 const MacAddress& mac_addr,
380 uint32_t ipv4_addr,
381 uint32_t ipv4_prefix_len,
382 bool up,
383 bool enable_multicast) {
384 const std::string link = up ? "up" : "down";
385 const std::string multicast = enable_multicast ? "on" : "off";
386 return (process_runner_->ip(
387 "addr", "add",
388 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
389 IPv4AddressToString(
390 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
391 "dev", ifname}) == 0) &&
392 (process_runner_->ip("link", "set",
393 {
394 "dev",
395 ifname,
396 link,
397 "addr",
398 MacAddressToString(mac_addr),
399 "multicast",
400 multicast,
401 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900402}
403
404void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900405 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900406}
407
Hugo Benichi321f23b2020-09-25 15:42:05 +0900408bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
409 const std::string& src_ip) {
410 return process_runner_->iptables("filter", {"-I", "OUTPUT", "-o", oif, "-s",
411 src_ip, "-j", "DROP", "-w"}) == 0;
412}
413
414bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
415 const std::string& src_ip) {
416 return process_runner_->iptables("filter", {"-D", "OUTPUT", "-o", oif, "-s",
417 src_ip, "-j", "DROP", "-w"}) == 0;
418}
419
Hugo Benichi7c342672020-09-08 09:18:14 +0900420bool Datapath::StartRoutingNamespace(pid_t pid,
421 const std::string& netns_name,
422 const std::string& host_ifname,
423 const std::string& peer_ifname,
424 uint32_t subnet_ipv4_addr,
425 uint32_t subnet_prefixlen,
426 uint32_t host_ipv4_addr,
427 uint32_t peer_ipv4_addr,
428 const MacAddress& peer_mac_addr) {
429 // Veth interface configuration and client routing configuration:
430 // - attach a name to the client namespace.
431 // - create veth pair across the current namespace and the client namespace.
432 // - configure IPv4 address on remote veth inside client namespace.
433 // - configure IPv4 address on local veth inside host namespace.
434 // - add a default IPv4 /0 route sending traffic to that remote veth.
435 if (!NetnsAttachName(netns_name, pid)) {
436 LOG(ERROR) << "Failed to attach name " << netns_name << " to namespace pid "
437 << pid;
438 return false;
439 }
440
441 if (!ConnectVethPair(pid, netns_name, host_ifname, peer_ifname, peer_mac_addr,
442 peer_ipv4_addr, subnet_prefixlen,
443 false /* enable_multicast */)) {
444 LOG(ERROR) << "Failed to create veth pair for"
445 " namespace pid "
446 << pid;
447 NetnsDeleteName(netns_name);
448 return false;
449 }
450
451 if (!ConfigureInterface(host_ifname, peer_mac_addr, host_ipv4_addr,
452 subnet_prefixlen, true /* link up */,
453 false /* enable_multicast */)) {
454 LOG(ERROR) << "Cannot configure host interface " << host_ifname;
455 RemoveInterface(host_ifname);
456 NetnsDeleteName(netns_name);
457 return false;
458 }
459
460 {
461 ScopedNS ns(pid);
462 if (!ns.IsValid() && pid != kTestPID) {
463 LOG(ERROR) << "Invalid namespace pid " << pid;
464 RemoveInterface(host_ifname);
465 NetnsDeleteName(netns_name);
466 return false;
467 }
468
469 if (!AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY)) {
470 LOG(ERROR) << "Failed to add default /0 route to " << host_ifname
471 << " inside namespace pid " << pid;
472 RemoveInterface(host_ifname);
473 NetnsDeleteName(netns_name);
474 return false;
475 }
476 }
477
478 // Host namespace routing configuration
479 // - ingress: add route to client subnet via |host_ifname|.
480 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
481 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
482 // Note that by default unsolicited ingress traffic is not forwarded to the
483 // client namespace unless the client specifically set port forwarding
484 // through permission_broker DBus APIs.
485 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
486 // both ways between client namespace and other guest containers and VMs.
487 // TODO(b/161507671) If outbound_physical_device is defined, then set strong
488 // routing to that interface routing table.
489 uint32_t netmask = Ipv4Netmask(subnet_prefixlen);
490 if (!AddIPv4Route(host_ipv4_addr, subnet_ipv4_addr, netmask)) {
491 LOG(ERROR) << "Failed to set route to client namespace";
492 RemoveInterface(host_ifname);
493 NetnsDeleteName(netns_name);
494 return false;
495 }
496
497 if (!AddOutboundIPv4(host_ifname)) {
498 LOG(ERROR) << "Failed to allow FORWARD for"
499 " traffic outgoing from "
500 << host_ifname;
501 RemoveInterface(host_ifname);
502 DeleteIPv4Route(host_ipv4_addr, subnet_ipv4_addr, netmask);
503 NetnsDeleteName(netns_name);
504 return false;
505 }
506
507 // TODO(b/161508179) Add fwmark source tagging based on client usage.
508 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
509 if (!AddOutboundIPv4SNATMark(host_ifname)) {
510 LOG(ERROR) << "Failed to set SNAT for traffic"
511 " outgoing from "
512 << host_ifname;
513 RemoveInterface(host_ifname);
514 DeleteIPv4Route(host_ipv4_addr, subnet_ipv4_addr, netmask);
515 RemoveOutboundIPv4(host_ifname);
516 NetnsDeleteName(netns_name);
517 return false;
518 }
519
520 return true;
521}
522
523void Datapath::StopRoutingNamespace(const std::string& netns_name,
524 const std::string& host_ifname,
525 uint32_t subnet_ipv4_addr,
526 uint32_t subnet_prefixlen,
527 uint32_t host_ipv4_addr) {
528 RemoveInterface(host_ifname);
529 RemoveOutboundIPv4(host_ifname);
530 RemoveOutboundIPv4SNATMark(host_ifname);
531 DeleteIPv4Route(host_ipv4_addr, subnet_ipv4_addr,
532 Ipv4Netmask(subnet_prefixlen));
533 NetnsDeleteName(netns_name);
534}
535
Hugo Benichi8d622b52020-08-13 15:24:12 +0900536void Datapath::StartRoutingDevice(const std::string& ext_ifname,
537 const std::string& int_ifname,
538 uint32_t int_ipv4_addr,
539 TrafficSource source) {
540 if (!ext_ifname.empty() &&
541 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
542 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
543 << "->" << int_ifname;
544
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900545 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900546 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
547 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900548
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900549 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900550 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
551 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900552
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900553 if (!ext_ifname.empty()) {
554 // If |ext_ifname| is not null, mark egress traffic with the
555 // fwmark routing tag corresponding to |ext_ifname|.
556 if (!ModifyFwmarkRoutingTag("-A", ext_ifname, int_ifname))
557 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
558 << ext_ifname << "<-" << int_ifname;
559 } else {
560 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
561 // PREROUTING to apply any fwmark routing tag saved for the current
562 // connection, and rely on implicit routing to the default logical network
563 // otherwise.
564 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname))
565 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
566 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900567
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900568 // TODO(b/161507671) When a VPN service starts, tag new connections with the
569 // fwmark routing tag for VPNs.
570 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900571
Hugo Benichi9be19b12020-08-14 15:33:40 +0900572 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
573 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
574 << source << " for " << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900575}
576
577void Datapath::StopRoutingDevice(const std::string& ext_ifname,
578 const std::string& int_ifname,
579 uint32_t int_ipv4_addr,
580 TrafficSource source) {
581 if (!ext_ifname.empty())
582 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900583 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
584 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900585 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900586 if (!ext_ifname.empty()) {
587 ModifyFwmarkRoutingTag("-D", ext_ifname, int_ifname);
588 } else {
589 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname);
590 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900591}
592
Garrick Evansf0ab7132019-06-18 14:50:42 +0900593bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
594 const std::string& ipv4_addr) {
595 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900596 if (process_runner_->iptables(
597 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
598 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900599 return false;
600
601 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900602 if (process_runner_->iptables(
603 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
604 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900605 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
606 return false;
607 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900608 if (process_runner_->iptables(
609 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
610 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900611 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
612 return false;
613 }
614
615 return true;
616}
617
618void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
619 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900620 process_runner_->iptables(
621 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
622 "--to-destination", ipv4_addr, "-w"});
623 process_runner_->iptables(
624 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
625 "--to-destination", ipv4_addr, "-w"});
626 process_runner_->iptables(
627 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
628 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900629}
630
Hugo Benichi8d622b52020-08-13 15:24:12 +0900631// TODO(hugobenichi) The name incorrectly refers to egress traffic, but this
632// FORWARD rule actually enables forwarding for ingress traffic. Fix the name.
Garrick Evansf0ab7132019-06-18 14:50:42 +0900633bool Datapath::AddOutboundIPv4(const std::string& ifname) {
Hugo Benichid82d8832020-08-14 10:05:03 +0900634 return StartIpForwarding(IpFamily::IPv4, "", ifname);
Garrick Evansf0ab7132019-06-18 14:50:42 +0900635}
636
637void Datapath::RemoveOutboundIPv4(const std::string& ifname) {
Hugo Benichid82d8832020-08-14 10:05:03 +0900638 StopIpForwarding(IpFamily::IPv4, "", ifname);
Garrick Evansf0ab7132019-06-18 14:50:42 +0900639}
640
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900641// TODO(b/161507671) Stop relying on the traffic fwmark 1/1 once forwarded
642// egress traffic is routed through the fwmark routing tag.
Garrick Evansd291af62020-05-25 10:39:06 +0900643bool Datapath::AddSNATMarkRules() {
Taoyu Li79871c92020-07-02 16:09:39 +0900644 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
645 // need to be explicitly dropped.
646 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900647 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
Taoyu Li79871c92020-07-02 16:09:39 +0900648 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0) {
649 return false;
650 }
Garrick Evansd291af62020-05-25 10:39:06 +0900651 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900652 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900653 "ACCEPT", "-w"}) != 0) {
654 return false;
655 }
656 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900657 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900658 "MASQUERADE", "-w"}) != 0) {
659 RemoveSNATMarkRules();
660 return false;
661 }
662 return true;
663}
664
665void Datapath::RemoveSNATMarkRules() {
666 process_runner_->iptables("nat", {"-D", "POSTROUTING", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900667 "1/1", "-j", "MASQUERADE", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900668 process_runner_->iptables("filter", {"-D", "FORWARD", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900669 "1/1", "-j", "ACCEPT", "-w"});
Taoyu Li79871c92020-07-02 16:09:39 +0900670 process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900671 "filter", {"-D", "FORWARD", "-m", "mark", "--mark", "1/1", "-m", "state",
Taoyu Li79871c92020-07-02 16:09:39 +0900672 "--state", "INVALID", "-j", "DROP", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900673}
674
Garrick Evansff6e37f2020-05-25 10:54:47 +0900675bool Datapath::AddInterfaceSNAT(const std::string& ifname) {
676 return process_runner_->iptables("nat", {"-A", "POSTROUTING", "-o", ifname,
677 "-j", "MASQUERADE", "-w"}) == 0;
678}
679
680void Datapath::RemoveInterfaceSNAT(const std::string& ifname) {
681 process_runner_->iptables(
682 "nat", {"-D", "POSTROUTING", "-o", ifname, "-j", "MASQUERADE", "-w"});
683}
684
Hugo Benichie8758b52020-04-03 14:49:01 +0900685bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
686 return process_runner_->iptables(
687 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900688 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900689}
690
691void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
692 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900693 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900694}
695
Garrick Evansd291af62020-05-25 10:39:06 +0900696bool Datapath::AddForwardEstablishedRule() {
697 return process_runner_->iptables(
698 "filter", {"-A", "FORWARD", "-m", "state", "--state",
699 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) == 0;
700}
701
702void Datapath::RemoveForwardEstablishedRule() {
703 process_runner_->iptables("filter",
704 {"-D", "FORWARD", "-m", "state", "--state",
705 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"});
706}
707
Garrick Evans664a82f2019-12-17 12:18:05 +0900708bool Datapath::MaskInterfaceFlags(const std::string& ifname,
709 uint16_t on,
710 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900711 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
712 if (!sock.is_valid()) {
713 PLOG(ERROR) << "Failed to create control socket";
714 return false;
715 }
716 ifreq ifr;
717 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
718 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
719 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
720 return false;
721 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900722 ifr.ifr_flags |= on;
723 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900724 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900725 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
726 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900727 return false;
728 }
729 return true;
730}
731
Garrick Evans260ff302019-07-25 11:22:50 +0900732bool Datapath::AddIPv6HostRoute(const std::string& ifname,
733 const std::string& ipv6_addr,
734 int ipv6_prefix_len) {
735 std::string ipv6_addr_cidr =
736 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
737
Garrick Evans8e8e3472020-01-23 14:03:50 +0900738 return process_runner_->ip6("route", "replace",
739 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900740}
741
742void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
743 const std::string& ipv6_addr,
744 int ipv6_prefix_len) {
745 std::string ipv6_addr_cidr =
746 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
747
Garrick Evans8e8e3472020-01-23 14:03:50 +0900748 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900749}
750
Taoyu Lia0727dc2020-09-24 19:54:59 +0900751bool Datapath::AddIPv6Address(const std::string& ifname,
752 const std::string& ipv6_addr) {
753 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900754}
755
Taoyu Lia0727dc2020-09-24 19:54:59 +0900756void Datapath::RemoveIPv6Address(const std::string& ifname,
757 const std::string& ipv6_addr) {
758 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900759}
760
Hugo Benichi76be34a2020-08-26 22:35:54 +0900761void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
762 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
763 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
764}
765
766void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
767 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
768 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
769}
770
771bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
772 const std::string& op,
773 const std::string& oif) {
774 if (oif.empty()) {
Hugo Benichibf811c62020-09-07 17:30:45 +0900775 LOG(ERROR) << "Cannot change POSTROUTING CONNMARK set-mark with no"
776 " interface specified";
Hugo Benichi76be34a2020-08-26 22:35:54 +0900777 return false;
778 }
779
780 if (!IsValidIpFamily(family)) {
781 LOG(ERROR) << "Cannot change POSTROUTING CONNMARK set-mark for " << oif
782 << ": incorrect IP family " << family;
783 return false;
784 }
785
786 int ifindex = FindIfIndex(oif);
787 if (ifindex == 0) {
788 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
789 return false;
790 }
791
792 std::vector<std::string> args = {op,
793 "POSTROUTING",
794 "-o",
795 oif,
796 "-j",
797 "CONNMARK",
798 "--set-mark",
799 Fwmark::FromIfIndex(ifindex).ToString() +
800 "/" + kFwmarkRoutingMask.ToString(),
801 "-w"};
802
803 bool success = true;
804 if (family & IPv4)
805 success &= process_runner_->iptables("mangle", args) == 0;
806 if (family & IPv6)
807 success &= process_runner_->ip6tables("mangle", args) == 0;
808 return false;
809}
810
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900811bool Datapath::ModifyConnmarkRestore(IpFamily family,
812 const std::string& chain,
813 const std::string& op,
814 const std::string& iif) {
815 if (chain != "OUTPUT" && (chain != "PREROUTING" || iif.empty())) {
816 LOG(ERROR) << "Invalid arguments chain=" << chain << " iif=" << iif;
817 return false;
818 }
819
820 if (!IsValidIpFamily(family)) {
821 LOG(ERROR) << "Cannot change " << chain << " -j CONNMARK restore-mark"
822 << " for " << iif << ": incorrect IP family " << family;
823 return false;
824 }
825
826 std::vector<std::string> args = {op, chain};
827 if (!iif.empty()) {
828 args.push_back("-i");
829 args.push_back(iif);
830 }
831 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi7c342672020-09-08 09:18:14 +0900832 kFwmarkRoutingMask.ToString(), "-w"});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900833
834 bool success = true;
835 if (family & IPv4)
836 success &= process_runner_->iptables("mangle", args) == 0;
837 if (family & IPv6)
838 success &= process_runner_->ip6tables("mangle", args) == 0;
839 return success;
840}
841
842bool Datapath::ModifyFwmarkRoutingTag(const std::string& op,
843 const std::string& ext_ifname,
844 const std::string& int_ifname) {
845 int ifindex = FindIfIndex(ext_ifname);
846 if (ifindex == 0) {
847 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
848 return false;
849 }
850
851 return ModifyFwmarkPrerouting(IpFamily::Dual, op, int_ifname,
852 Fwmark::FromIfIndex(ifindex),
853 kFwmarkRoutingMask);
854}
855
Hugo Benichi9be19b12020-08-14 15:33:40 +0900856bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
857 const std::string& iif,
858 TrafficSource source) {
859 return ModifyFwmarkPrerouting(IpFamily::Dual, op, iif,
860 Fwmark::FromSource(source),
861 kFwmarkAllSourcesMask);
862}
863
864bool Datapath::ModifyFwmarkPrerouting(IpFamily family,
865 const std::string& op,
866 const std::string& iif,
867 Fwmark mark,
868 Fwmark mask,
869 bool log_failures) {
870 if (iif.empty()) {
871 LOG(ERROR)
872 << "Cannot change PREROUTING set-fwmark with no interface specified";
873 return false;
874 }
875
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900876 if (!IsValidIpFamily(family)) {
877 LOG(ERROR) << "Cannot change PREROUTING set-fwmark for " << iif
878 << ": incorrect IP family " << family;
879 return false;
Hugo Benichi9be19b12020-08-14 15:33:40 +0900880 }
881
882 std::vector<std::string> args = {
883 op, "PREROUTING", "-i", iif,
884 "-j", "MARK", "--set-mark", mark.ToString() + "/" + mask.ToString(),
885 "-w"};
886
887 bool success = true;
Hugo Benichi5c9c11c2020-09-15 17:25:26 +0900888 if (family & IPv4)
Hugo Benichi9be19b12020-08-14 15:33:40 +0900889 success &= process_runner_->iptables("mangle", args, log_failures) == 0;
Hugo Benichi5c9c11c2020-09-15 17:25:26 +0900890 if (family & IPv6)
Hugo Benichi9be19b12020-08-14 15:33:40 +0900891 success &= process_runner_->ip6tables("mangle", args, log_failures) == 0;
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900892 return success;
Hugo Benichi9be19b12020-08-14 15:33:40 +0900893}
894
Hugo Benichid82d8832020-08-14 10:05:03 +0900895bool Datapath::ModifyIpForwarding(IpFamily family,
896 const std::string& op,
897 const std::string& iif,
898 const std::string& oif,
899 bool log_failures) {
900 if (iif.empty() && oif.empty()) {
901 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
902 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +0900903 return false;
904 }
905
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900906 if (!IsValidIpFamily(family)) {
907 LOG(ERROR) << "Cannot change IP forwarding from \"" << iif << "\" to \""
908 << oif << "\": incorrect IP family " << family;
909 return false;
Hugo Benichid82d8832020-08-14 10:05:03 +0900910 }
911
912 std::vector<std::string> args = {op, "FORWARD"};
913 if (!iif.empty()) {
914 args.push_back("-i");
915 args.push_back(iif);
916 }
917 if (!oif.empty()) {
918 args.push_back("-o");
919 args.push_back(oif);
920 }
921 args.push_back("-j");
922 args.push_back("ACCEPT");
923 args.push_back("-w");
924
925 bool success = true;
926 if (family & IpFamily::IPv4)
927 success &= process_runner_->iptables("filter", args, log_failures) == 0;
928 if (family & IpFamily::IPv6)
929 success &= process_runner_->ip6tables("filter", args, log_failures) == 0;
930 return success;
931}
932
933bool Datapath::StartIpForwarding(IpFamily family,
934 const std::string& iif,
935 const std::string& oif) {
936 return ModifyIpForwarding(family, "-A", iif, oif);
937}
938
939bool Datapath::StopIpForwarding(IpFamily family,
940 const std::string& iif,
941 const std::string& oif) {
942 return ModifyIpForwarding(family, "-D", iif, oif);
943}
944
945bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
946 const std::string& ifname2) {
947 // Only start Ipv6 forwarding if -C returns false and it had not been
948 // started yet.
949 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
950 false /*log_failures*/) &&
951 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
952 return false;
953 }
954
955 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
956 false /*log_failures*/) &&
957 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +0900958 RemoveIPv6Forwarding(ifname1, ifname2);
959 return false;
960 }
961
962 return true;
963}
964
965void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
966 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +0900967 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
968 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +0900969}
970
Garrick Evans3d97a392020-02-21 15:24:37 +0900971bool Datapath::AddIPv4Route(uint32_t gateway_addr,
972 uint32_t addr,
973 uint32_t netmask) {
974 struct rtentry route;
975 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +0900976 SetSockaddrIn(&route.rt_gateway, gateway_addr);
977 SetSockaddrIn(&route.rt_dst, addr & netmask);
978 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +0900979 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +0900980 return ModifyRtentry(SIOCADDRT, &route);
981}
Garrick Evans3d97a392020-02-21 15:24:37 +0900982
Hugo Benichie8758b52020-04-03 14:49:01 +0900983bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
984 uint32_t addr,
985 uint32_t netmask) {
986 struct rtentry route;
987 memset(&route, 0, sizeof(route));
988 SetSockaddrIn(&route.rt_gateway, gateway_addr);
989 SetSockaddrIn(&route.rt_dst, addr & netmask);
990 SetSockaddrIn(&route.rt_genmask, netmask);
991 route.rt_flags = RTF_UP | RTF_GATEWAY;
992 return ModifyRtentry(SIOCDELRT, &route);
993}
994
995bool Datapath::AddIPv4Route(const std::string& ifname,
996 uint32_t addr,
997 uint32_t netmask) {
998 struct rtentry route;
999 memset(&route, 0, sizeof(route));
1000 SetSockaddrIn(&route.rt_dst, addr & netmask);
1001 SetSockaddrIn(&route.rt_genmask, netmask);
1002 char rt_dev[IFNAMSIZ];
1003 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1004 rt_dev[IFNAMSIZ - 1] = '\0';
1005 route.rt_dev = rt_dev;
1006 route.rt_flags = RTF_UP | RTF_GATEWAY;
1007 return ModifyRtentry(SIOCADDRT, &route);
1008}
1009
1010bool Datapath::DeleteIPv4Route(const std::string& ifname,
1011 uint32_t addr,
1012 uint32_t netmask) {
1013 struct rtentry route;
1014 memset(&route, 0, sizeof(route));
1015 SetSockaddrIn(&route.rt_dst, addr & netmask);
1016 SetSockaddrIn(&route.rt_genmask, netmask);
1017 char rt_dev[IFNAMSIZ];
1018 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1019 rt_dev[IFNAMSIZ - 1] = '\0';
1020 route.rt_dev = rt_dev;
1021 route.rt_flags = RTF_UP | RTF_GATEWAY;
1022 return ModifyRtentry(SIOCDELRT, &route);
1023}
1024
Taoyu Lia0727dc2020-09-24 19:54:59 +09001025bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001026 DCHECK(route);
1027 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001028 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001029 return false;
1030 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001031 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1032 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001033 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001034 return false;
1035 }
1036 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1037 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001038 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001039 return false;
1040 }
1041 return true;
1042}
1043
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001044bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1045 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1046 kArcAddr, kAdbServerPort, ifname,
1047 kLocalhostAddr, kAdbProxyTcpListenPort);
1048}
1049
1050void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1051 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1052 kArcAddr, kAdbServerPort, ifname,
1053 kLocalhostAddr, kAdbProxyTcpListenPort);
1054}
1055
1056bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1057 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1058 kAdbProxyTcpListenPort, ifname);
1059}
1060
1061void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1062 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1063 kAdbProxyTcpListenPort, ifname);
1064}
1065
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001066void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1067 if_nametoindex_[ifname] = ifindex;
1068}
1069
1070int Datapath::FindIfIndex(const std::string& ifname) {
1071 uint32_t ifindex = if_nametoindex(ifname.c_str());
1072 if (ifindex > 0) {
1073 if_nametoindex_[ifname] = ifindex;
1074 return ifindex;
1075 }
1076
1077 const auto it = if_nametoindex_.find(ifname);
1078 if (it != if_nametoindex_.end())
1079 return it->second;
1080
1081 return 0;
1082}
1083
Garrick Evans3388a032020-03-24 11:25:55 +09001084} // namespace patchpanel