blob: 50ed5ba2ef3e7813dd716de78b7dfaeebda02f30 [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
Hugo Benichi58125d32020-09-09 11:25:45 +0900118 // Create a FORWARD ACCEPT rule for connections already established.
119 if (process_runner_->iptables(
120 "filter", {"-A", "FORWARD", "-m", "state", "--state",
121 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900122 LOG(ERROR) << "Failed to install forwarding rule for established"
123 << " connections.";
124
125 // chromium:898210: Drop any locally originated traffic that would exit a
126 // physical interface with a source IPv4 address from the subnet of IPs used
127 // for VMs, containers, and connected namespaces This is needed to prevent
128 // packets leaking with an incorrect src IP when a local process binds to the
129 // wrong interface.
130 for (const auto& oif : kPhysicalIfnamePrefixes) {
131 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
132 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
133 << kGuestIPv4Subnet << " exiting " << oif;
134 }
135
136 if (!AddOutboundIPv4SNATMark("vmtap+"))
137 LOG(ERROR) << "Failed to set up NAT for TAP devices."
138 << " Guest connectivity may be broken.";
139}
140
141void Datapath::Stop() {
142 RemoveOutboundIPv4SNATMark("vmtap+");
Hugo Benichi58125d32020-09-09 11:25:45 +0900143 process_runner_->iptables("filter",
144 {"-D", "FORWARD", "-m", "state", "--state",
145 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"});
Hugo Benichibf811c62020-09-07 17:30:45 +0900146 RemoveSNATMarkRules();
147 for (const auto& oif : kPhysicalIfnamePrefixes)
148 RemoveSourceIPv4DropRule(oif, kGuestIPv4Subnet);
149
150 // Restore original local port range.
151 // TODO(garrick): The original history behind this tweak is gone. Some
152 // investigation is needed to see if it is still applicable.
153 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
154 "32768 61000") != 0)
155 LOG(ERROR) << "Failed to restore local port range";
156
157 // Disable packet forwarding
158 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
159 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
160
161 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
162 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
163}
164
Hugo Benichi33860d72020-07-09 16:34:01 +0900165bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
166 // Try first to delete any netns with name |netns_name| in case patchpanel
167 // did not exit cleanly.
168 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
169 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
170 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
171}
172
173bool Datapath::NetnsDeleteName(const std::string& netns_name) {
174 return process_runner_->ip_netns_delete(netns_name) == 0;
175}
176
Garrick Evans8a949dc2019-07-18 16:17:53 +0900177bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900178 uint32_t ipv4_addr,
179 uint32_t ipv4_prefix_len) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900180 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900181 if (process_runner_->brctl("addbr", {ifname}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900182 return false;
183 }
184
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900185 if (process_runner_->ip(
186 "addr", "add",
187 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
188 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
189 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900190 RemoveBridge(ifname);
191 return false;
192 }
193
194 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900195 RemoveBridge(ifname);
196 return false;
197 }
198
199 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900200 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900201 RemoveBridge(ifname);
202 return false;
203 }
204
205 return true;
206}
207
208void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900209 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900210 process_runner_->ip("link", "set", {ifname, "down"});
Garrick Evans8e8e3472020-01-23 14:03:50 +0900211 process_runner_->brctl("delbr", {ifname});
Garrick Evans8a949dc2019-07-18 16:17:53 +0900212}
213
Garrick Evans621ed262019-11-13 12:28:43 +0900214bool Datapath::AddToBridge(const std::string& br_ifname,
215 const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900216 return (process_runner_->brctl("addif", {br_ifname, ifname}) == 0);
Garrick Evans621ed262019-11-13 12:28:43 +0900217}
218
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900219std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900220 const MacAddress* mac_addr,
221 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900222 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900223 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
224 if (!dev.is_valid()) {
225 PLOG(ERROR) << "Failed to open " << kTunDev;
226 return "";
227 }
228
229 struct ifreq ifr;
230 memset(&ifr, 0, sizeof(ifr));
231 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
232 sizeof(ifr.ifr_name));
233 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
234
235 // If a template was given as the name, ifr_name will be updated with the
236 // actual interface name.
237 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900238 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900239 return "";
240 }
241 const char* ifname = ifr.ifr_name;
242
243 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900244 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900245 return "";
246 }
247
Garrick Evans4f9f5572019-11-26 10:25:16 +0900248 if (!user.empty()) {
249 uid_t uid = -1;
250 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
251 PLOG(ERROR) << "Unable to look up UID for " << user;
252 RemoveTAP(ifname);
253 return "";
254 }
255 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
256 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
257 << ifname;
258 RemoveTAP(ifname);
259 return "";
260 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900261 }
262
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900263 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900264 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
265 if (!sock.is_valid()) {
266 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900267 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900268 RemoveTAP(ifname);
269 return "";
270 }
271
Garrick Evans621ed262019-11-13 12:28:43 +0900272 if (ipv4_addr) {
273 struct sockaddr_in* addr =
274 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
275 addr->sin_family = AF_INET;
276 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
277 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
278 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
279 << " {" << ipv4_addr->ToCidrString() << "}";
280 RemoveTAP(ifname);
281 return "";
282 }
283
284 struct sockaddr_in* netmask =
285 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
286 netmask->sin_family = AF_INET;
287 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
288 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
289 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
290 << " {" << ipv4_addr->ToCidrString() << "}";
291 RemoveTAP(ifname);
292 return "";
293 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900294 }
295
Garrick Evans621ed262019-11-13 12:28:43 +0900296 if (mac_addr) {
297 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
298 hwaddr->sa_family = ARPHRD_ETHER;
299 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
300 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
301 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
302 << " {" << MacAddressToString(*mac_addr) << "}";
303 RemoveTAP(ifname);
304 return "";
305 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900306 }
307
308 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900309 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900310 RemoveTAP(ifname);
311 return "";
312 }
313
314 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
315 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900316 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900317 RemoveTAP(ifname);
318 return "";
319 }
320
321 return ifname;
322}
323
324void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900325 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900326}
327
Hugo Benichi33860d72020-07-09 16:34:01 +0900328bool Datapath::ConnectVethPair(pid_t netns_pid,
329 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900330 const std::string& veth_ifname,
331 const std::string& peer_ifname,
332 const MacAddress& remote_mac_addr,
333 uint32_t remote_ipv4_addr,
334 uint32_t remote_ipv4_prefix_len,
335 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900336 // Set up the virtual pair across the current namespace and |netns_name|.
337 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
338 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
339 << peer_ifname;
340 return false;
341 }
342
343 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900344 {
Hugo Benichi33860d72020-07-09 16:34:01 +0900345 ScopedNS ns(netns_pid);
346 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900347 LOG(ERROR)
348 << "Cannot create virtual link -- invalid container namespace?";
349 return false;
350 }
351
Hugo Benichi76675592020-04-08 14:29:57 +0900352 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
353 remote_ipv4_prefix_len, true /* link up */,
354 remote_multicast_flag)) {
355 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
356 RemoveInterface(peer_ifname);
357 return false;
358 }
359 }
360
Hugo Benichi76675592020-04-08 14:29:57 +0900361 if (!ToggleInterface(veth_ifname, true /*up*/)) {
362 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
363 RemoveInterface(veth_ifname);
364 return false;
365 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900366
Hugo Benichi76675592020-04-08 14:29:57 +0900367 return true;
368}
369
Hugo Benichi33860d72020-07-09 16:34:01 +0900370bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
371 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900372 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900373 return process_runner_->ip("link", "add",
374 {veth_ifname, "type", "veth", "peer", "name",
375 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900376}
Garrick Evans54861622019-07-19 09:05:09 +0900377
Garrick Evans2470caa2020-03-04 14:15:41 +0900378bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
379 const std::string link = up ? "up" : "down";
380 return process_runner_->ip("link", "set", {ifname, link}) == 0;
381}
Garrick Evans54861622019-07-19 09:05:09 +0900382
Garrick Evans2470caa2020-03-04 14:15:41 +0900383bool Datapath::ConfigureInterface(const std::string& ifname,
384 const MacAddress& mac_addr,
385 uint32_t ipv4_addr,
386 uint32_t ipv4_prefix_len,
387 bool up,
388 bool enable_multicast) {
389 const std::string link = up ? "up" : "down";
390 const std::string multicast = enable_multicast ? "on" : "off";
391 return (process_runner_->ip(
392 "addr", "add",
393 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
394 IPv4AddressToString(
395 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
396 "dev", ifname}) == 0) &&
397 (process_runner_->ip("link", "set",
398 {
399 "dev",
400 ifname,
401 link,
402 "addr",
403 MacAddressToString(mac_addr),
404 "multicast",
405 multicast,
406 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900407}
408
409void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900410 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900411}
412
Hugo Benichi321f23b2020-09-25 15:42:05 +0900413bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
414 const std::string& src_ip) {
415 return process_runner_->iptables("filter", {"-I", "OUTPUT", "-o", oif, "-s",
416 src_ip, "-j", "DROP", "-w"}) == 0;
417}
418
419bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
420 const std::string& src_ip) {
421 return process_runner_->iptables("filter", {"-D", "OUTPUT", "-o", oif, "-s",
422 src_ip, "-j", "DROP", "-w"}) == 0;
423}
424
Hugo Benichi7c342672020-09-08 09:18:14 +0900425bool Datapath::StartRoutingNamespace(pid_t pid,
426 const std::string& netns_name,
427 const std::string& host_ifname,
428 const std::string& peer_ifname,
429 uint32_t subnet_ipv4_addr,
430 uint32_t subnet_prefixlen,
431 uint32_t host_ipv4_addr,
432 uint32_t peer_ipv4_addr,
433 const MacAddress& peer_mac_addr) {
434 // Veth interface configuration and client routing configuration:
435 // - attach a name to the client namespace.
436 // - create veth pair across the current namespace and the client namespace.
437 // - configure IPv4 address on remote veth inside client namespace.
438 // - configure IPv4 address on local veth inside host namespace.
439 // - add a default IPv4 /0 route sending traffic to that remote veth.
440 if (!NetnsAttachName(netns_name, pid)) {
441 LOG(ERROR) << "Failed to attach name " << netns_name << " to namespace pid "
442 << pid;
443 return false;
444 }
445
446 if (!ConnectVethPair(pid, netns_name, host_ifname, peer_ifname, peer_mac_addr,
447 peer_ipv4_addr, subnet_prefixlen,
448 false /* enable_multicast */)) {
449 LOG(ERROR) << "Failed to create veth pair for"
450 " namespace pid "
451 << pid;
452 NetnsDeleteName(netns_name);
453 return false;
454 }
455
456 if (!ConfigureInterface(host_ifname, peer_mac_addr, host_ipv4_addr,
457 subnet_prefixlen, true /* link up */,
458 false /* enable_multicast */)) {
459 LOG(ERROR) << "Cannot configure host interface " << host_ifname;
460 RemoveInterface(host_ifname);
461 NetnsDeleteName(netns_name);
462 return false;
463 }
464
465 {
466 ScopedNS ns(pid);
467 if (!ns.IsValid() && pid != kTestPID) {
468 LOG(ERROR) << "Invalid namespace pid " << pid;
469 RemoveInterface(host_ifname);
470 NetnsDeleteName(netns_name);
471 return false;
472 }
473
474 if (!AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY)) {
475 LOG(ERROR) << "Failed to add default /0 route to " << host_ifname
476 << " inside namespace pid " << pid;
477 RemoveInterface(host_ifname);
478 NetnsDeleteName(netns_name);
479 return false;
480 }
481 }
482
483 // Host namespace routing configuration
484 // - ingress: add route to client subnet via |host_ifname|.
485 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
486 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
487 // Note that by default unsolicited ingress traffic is not forwarded to the
488 // client namespace unless the client specifically set port forwarding
489 // through permission_broker DBus APIs.
490 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
491 // both ways between client namespace and other guest containers and VMs.
492 // TODO(b/161507671) If outbound_physical_device is defined, then set strong
493 // routing to that interface routing table.
494 uint32_t netmask = Ipv4Netmask(subnet_prefixlen);
495 if (!AddIPv4Route(host_ipv4_addr, subnet_ipv4_addr, netmask)) {
496 LOG(ERROR) << "Failed to set route to client namespace";
497 RemoveInterface(host_ifname);
498 NetnsDeleteName(netns_name);
499 return false;
500 }
501
Hugo Benichi58125d32020-09-09 11:25:45 +0900502 if (!StartIpForwarding(IpFamily::IPv4, "", host_ifname)) {
503 LOG(ERROR) << "Failed to allow FORWARD for ingress traffic into "
Hugo Benichi7c342672020-09-08 09:18:14 +0900504 << host_ifname;
505 RemoveInterface(host_ifname);
506 DeleteIPv4Route(host_ipv4_addr, subnet_ipv4_addr, netmask);
507 NetnsDeleteName(netns_name);
508 return false;
509 }
510
511 // TODO(b/161508179) Add fwmark source tagging based on client usage.
512 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
513 if (!AddOutboundIPv4SNATMark(host_ifname)) {
514 LOG(ERROR) << "Failed to set SNAT for traffic"
515 " outgoing from "
516 << host_ifname;
517 RemoveInterface(host_ifname);
518 DeleteIPv4Route(host_ipv4_addr, subnet_ipv4_addr, netmask);
Hugo Benichi58125d32020-09-09 11:25:45 +0900519 StopIpForwarding(IpFamily::IPv4, "", host_ifname);
Hugo Benichi7c342672020-09-08 09:18:14 +0900520 NetnsDeleteName(netns_name);
521 return false;
522 }
523
524 return true;
525}
526
527void Datapath::StopRoutingNamespace(const std::string& netns_name,
528 const std::string& host_ifname,
529 uint32_t subnet_ipv4_addr,
530 uint32_t subnet_prefixlen,
531 uint32_t host_ipv4_addr) {
532 RemoveInterface(host_ifname);
Hugo Benichi58125d32020-09-09 11:25:45 +0900533 StopIpForwarding(IpFamily::IPv4, "", host_ifname);
Hugo Benichi7c342672020-09-08 09:18:14 +0900534 RemoveOutboundIPv4SNATMark(host_ifname);
535 DeleteIPv4Route(host_ipv4_addr, subnet_ipv4_addr,
536 Ipv4Netmask(subnet_prefixlen));
537 NetnsDeleteName(netns_name);
538}
539
Hugo Benichi8d622b52020-08-13 15:24:12 +0900540void Datapath::StartRoutingDevice(const std::string& ext_ifname,
541 const std::string& int_ifname,
542 uint32_t int_ipv4_addr,
543 TrafficSource source) {
544 if (!ext_ifname.empty() &&
545 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
546 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
547 << "->" << int_ifname;
548
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900549 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_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 Benichifa97b3b2020-10-06 22:45:26 +0900553 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900554 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
555 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900556
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900557 if (!ext_ifname.empty()) {
558 // If |ext_ifname| is not null, mark egress traffic with the
559 // fwmark routing tag corresponding to |ext_ifname|.
560 if (!ModifyFwmarkRoutingTag("-A", ext_ifname, int_ifname))
561 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
562 << ext_ifname << "<-" << int_ifname;
563 } else {
564 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
565 // PREROUTING to apply any fwmark routing tag saved for the current
566 // connection, and rely on implicit routing to the default logical network
567 // otherwise.
568 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname))
569 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
570 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900571
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900572 // TODO(b/161507671) When a VPN service starts, tag new connections with the
573 // fwmark routing tag for VPNs.
574 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900575
Hugo Benichi9be19b12020-08-14 15:33:40 +0900576 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
577 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
578 << source << " for " << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900579}
580
581void Datapath::StopRoutingDevice(const std::string& ext_ifname,
582 const std::string& int_ifname,
583 uint32_t int_ipv4_addr,
584 TrafficSource source) {
585 if (!ext_ifname.empty())
586 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900587 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
588 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900589 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900590 if (!ext_ifname.empty()) {
591 ModifyFwmarkRoutingTag("-D", ext_ifname, int_ifname);
592 } else {
593 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname);
594 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900595}
596
Garrick Evansf0ab7132019-06-18 14:50:42 +0900597bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
598 const std::string& ipv4_addr) {
599 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900600 if (process_runner_->iptables(
601 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
602 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900603 return false;
604
605 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900606 if (process_runner_->iptables(
607 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
608 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900609 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
610 return false;
611 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900612 if (process_runner_->iptables(
613 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
614 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900615 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
616 return false;
617 }
618
619 return true;
620}
621
622void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
623 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900624 process_runner_->iptables(
625 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
626 "--to-destination", ipv4_addr, "-w"});
627 process_runner_->iptables(
628 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
629 "--to-destination", ipv4_addr, "-w"});
630 process_runner_->iptables(
631 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
632 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900633}
634
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900635// TODO(b/161507671) Stop relying on the traffic fwmark 1/1 once forwarded
636// egress traffic is routed through the fwmark routing tag.
Garrick Evansd291af62020-05-25 10:39:06 +0900637bool Datapath::AddSNATMarkRules() {
Taoyu Li79871c92020-07-02 16:09:39 +0900638 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
639 // need to be explicitly dropped.
640 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900641 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
Taoyu Li79871c92020-07-02 16:09:39 +0900642 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0) {
643 return false;
644 }
Garrick Evansd291af62020-05-25 10:39:06 +0900645 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900646 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900647 "ACCEPT", "-w"}) != 0) {
648 return false;
649 }
650 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900651 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900652 "MASQUERADE", "-w"}) != 0) {
653 RemoveSNATMarkRules();
654 return false;
655 }
656 return true;
657}
658
659void Datapath::RemoveSNATMarkRules() {
660 process_runner_->iptables("nat", {"-D", "POSTROUTING", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900661 "1/1", "-j", "MASQUERADE", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900662 process_runner_->iptables("filter", {"-D", "FORWARD", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900663 "1/1", "-j", "ACCEPT", "-w"});
Taoyu Li79871c92020-07-02 16:09:39 +0900664 process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900665 "filter", {"-D", "FORWARD", "-m", "mark", "--mark", "1/1", "-m", "state",
Taoyu Li79871c92020-07-02 16:09:39 +0900666 "--state", "INVALID", "-j", "DROP", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900667}
668
Hugo Benichie8758b52020-04-03 14:49:01 +0900669bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
670 return process_runner_->iptables(
671 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900672 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900673}
674
675void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
676 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900677 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900678}
679
Garrick Evans664a82f2019-12-17 12:18:05 +0900680bool Datapath::MaskInterfaceFlags(const std::string& ifname,
681 uint16_t on,
682 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900683 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
684 if (!sock.is_valid()) {
685 PLOG(ERROR) << "Failed to create control socket";
686 return false;
687 }
688 ifreq ifr;
689 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
690 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
691 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
692 return false;
693 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900694 ifr.ifr_flags |= on;
695 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900696 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900697 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
698 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900699 return false;
700 }
701 return true;
702}
703
Garrick Evans260ff302019-07-25 11:22:50 +0900704bool Datapath::AddIPv6HostRoute(const std::string& ifname,
705 const std::string& ipv6_addr,
706 int ipv6_prefix_len) {
707 std::string ipv6_addr_cidr =
708 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
709
Garrick Evans8e8e3472020-01-23 14:03:50 +0900710 return process_runner_->ip6("route", "replace",
711 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900712}
713
714void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
715 const std::string& ipv6_addr,
716 int ipv6_prefix_len) {
717 std::string ipv6_addr_cidr =
718 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
719
Garrick Evans8e8e3472020-01-23 14:03:50 +0900720 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900721}
722
Taoyu Lia0727dc2020-09-24 19:54:59 +0900723bool Datapath::AddIPv6Address(const std::string& ifname,
724 const std::string& ipv6_addr) {
725 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900726}
727
Taoyu Lia0727dc2020-09-24 19:54:59 +0900728void Datapath::RemoveIPv6Address(const std::string& ifname,
729 const std::string& ipv6_addr) {
730 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900731}
732
Hugo Benichi76be34a2020-08-26 22:35:54 +0900733void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
734 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
735 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
736}
737
738void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
739 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
740 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
741}
742
743bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
744 const std::string& op,
745 const std::string& oif) {
746 if (oif.empty()) {
Hugo Benichibf811c62020-09-07 17:30:45 +0900747 LOG(ERROR) << "Cannot change POSTROUTING CONNMARK set-mark with no"
748 " interface specified";
Hugo Benichi76be34a2020-08-26 22:35:54 +0900749 return false;
750 }
751
752 if (!IsValidIpFamily(family)) {
753 LOG(ERROR) << "Cannot change POSTROUTING CONNMARK set-mark for " << oif
754 << ": incorrect IP family " << family;
755 return false;
756 }
757
758 int ifindex = FindIfIndex(oif);
759 if (ifindex == 0) {
760 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
761 return false;
762 }
763
764 std::vector<std::string> args = {op,
765 "POSTROUTING",
766 "-o",
767 oif,
768 "-j",
769 "CONNMARK",
770 "--set-mark",
771 Fwmark::FromIfIndex(ifindex).ToString() +
772 "/" + kFwmarkRoutingMask.ToString(),
773 "-w"};
774
775 bool success = true;
776 if (family & IPv4)
777 success &= process_runner_->iptables("mangle", args) == 0;
778 if (family & IPv6)
779 success &= process_runner_->ip6tables("mangle", args) == 0;
780 return false;
781}
782
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900783bool Datapath::ModifyConnmarkRestore(IpFamily family,
784 const std::string& chain,
785 const std::string& op,
786 const std::string& iif) {
787 if (chain != "OUTPUT" && (chain != "PREROUTING" || iif.empty())) {
788 LOG(ERROR) << "Invalid arguments chain=" << chain << " iif=" << iif;
789 return false;
790 }
791
792 if (!IsValidIpFamily(family)) {
793 LOG(ERROR) << "Cannot change " << chain << " -j CONNMARK restore-mark"
794 << " for " << iif << ": incorrect IP family " << family;
795 return false;
796 }
797
798 std::vector<std::string> args = {op, chain};
799 if (!iif.empty()) {
800 args.push_back("-i");
801 args.push_back(iif);
802 }
803 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi7c342672020-09-08 09:18:14 +0900804 kFwmarkRoutingMask.ToString(), "-w"});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900805
806 bool success = true;
807 if (family & IPv4)
808 success &= process_runner_->iptables("mangle", args) == 0;
809 if (family & IPv6)
810 success &= process_runner_->ip6tables("mangle", args) == 0;
811 return success;
812}
813
814bool Datapath::ModifyFwmarkRoutingTag(const std::string& op,
815 const std::string& ext_ifname,
816 const std::string& int_ifname) {
817 int ifindex = FindIfIndex(ext_ifname);
818 if (ifindex == 0) {
819 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
820 return false;
821 }
822
823 return ModifyFwmarkPrerouting(IpFamily::Dual, op, int_ifname,
824 Fwmark::FromIfIndex(ifindex),
825 kFwmarkRoutingMask);
826}
827
Hugo Benichi9be19b12020-08-14 15:33:40 +0900828bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
829 const std::string& iif,
830 TrafficSource source) {
831 return ModifyFwmarkPrerouting(IpFamily::Dual, op, iif,
832 Fwmark::FromSource(source),
833 kFwmarkAllSourcesMask);
834}
835
836bool Datapath::ModifyFwmarkPrerouting(IpFamily family,
837 const std::string& op,
838 const std::string& iif,
839 Fwmark mark,
840 Fwmark mask,
841 bool log_failures) {
842 if (iif.empty()) {
843 LOG(ERROR)
844 << "Cannot change PREROUTING set-fwmark with no interface specified";
845 return false;
846 }
847
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900848 if (!IsValidIpFamily(family)) {
849 LOG(ERROR) << "Cannot change PREROUTING set-fwmark for " << iif
850 << ": incorrect IP family " << family;
851 return false;
Hugo Benichi9be19b12020-08-14 15:33:40 +0900852 }
853
854 std::vector<std::string> args = {
855 op, "PREROUTING", "-i", iif,
856 "-j", "MARK", "--set-mark", mark.ToString() + "/" + mask.ToString(),
857 "-w"};
858
859 bool success = true;
Hugo Benichi5c9c11c2020-09-15 17:25:26 +0900860 if (family & IPv4)
Hugo Benichi9be19b12020-08-14 15:33:40 +0900861 success &= process_runner_->iptables("mangle", args, log_failures) == 0;
Hugo Benichi5c9c11c2020-09-15 17:25:26 +0900862 if (family & IPv6)
Hugo Benichi9be19b12020-08-14 15:33:40 +0900863 success &= process_runner_->ip6tables("mangle", args, log_failures) == 0;
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900864 return success;
Hugo Benichi9be19b12020-08-14 15:33:40 +0900865}
866
Hugo Benichid82d8832020-08-14 10:05:03 +0900867bool Datapath::ModifyIpForwarding(IpFamily family,
868 const std::string& op,
869 const std::string& iif,
870 const std::string& oif,
871 bool log_failures) {
872 if (iif.empty() && oif.empty()) {
873 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
874 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +0900875 return false;
876 }
877
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900878 if (!IsValidIpFamily(family)) {
879 LOG(ERROR) << "Cannot change IP forwarding from \"" << iif << "\" to \""
880 << oif << "\": incorrect IP family " << family;
881 return false;
Hugo Benichid82d8832020-08-14 10:05:03 +0900882 }
883
884 std::vector<std::string> args = {op, "FORWARD"};
885 if (!iif.empty()) {
886 args.push_back("-i");
887 args.push_back(iif);
888 }
889 if (!oif.empty()) {
890 args.push_back("-o");
891 args.push_back(oif);
892 }
893 args.push_back("-j");
894 args.push_back("ACCEPT");
895 args.push_back("-w");
896
897 bool success = true;
898 if (family & IpFamily::IPv4)
899 success &= process_runner_->iptables("filter", args, log_failures) == 0;
900 if (family & IpFamily::IPv6)
901 success &= process_runner_->ip6tables("filter", args, log_failures) == 0;
902 return success;
903}
904
905bool Datapath::StartIpForwarding(IpFamily family,
906 const std::string& iif,
907 const std::string& oif) {
908 return ModifyIpForwarding(family, "-A", iif, oif);
909}
910
911bool Datapath::StopIpForwarding(IpFamily family,
912 const std::string& iif,
913 const std::string& oif) {
914 return ModifyIpForwarding(family, "-D", iif, oif);
915}
916
917bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
918 const std::string& ifname2) {
919 // Only start Ipv6 forwarding if -C returns false and it had not been
920 // started yet.
921 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
922 false /*log_failures*/) &&
923 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
924 return false;
925 }
926
927 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
928 false /*log_failures*/) &&
929 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +0900930 RemoveIPv6Forwarding(ifname1, ifname2);
931 return false;
932 }
933
934 return true;
935}
936
937void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
938 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +0900939 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
940 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +0900941}
942
Garrick Evans3d97a392020-02-21 15:24:37 +0900943bool Datapath::AddIPv4Route(uint32_t gateway_addr,
944 uint32_t addr,
945 uint32_t netmask) {
946 struct rtentry route;
947 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +0900948 SetSockaddrIn(&route.rt_gateway, gateway_addr);
949 SetSockaddrIn(&route.rt_dst, addr & netmask);
950 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +0900951 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +0900952 return ModifyRtentry(SIOCADDRT, &route);
953}
Garrick Evans3d97a392020-02-21 15:24:37 +0900954
Hugo Benichie8758b52020-04-03 14:49:01 +0900955bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
956 uint32_t addr,
957 uint32_t netmask) {
958 struct rtentry route;
959 memset(&route, 0, sizeof(route));
960 SetSockaddrIn(&route.rt_gateway, gateway_addr);
961 SetSockaddrIn(&route.rt_dst, addr & netmask);
962 SetSockaddrIn(&route.rt_genmask, netmask);
963 route.rt_flags = RTF_UP | RTF_GATEWAY;
964 return ModifyRtentry(SIOCDELRT, &route);
965}
966
967bool Datapath::AddIPv4Route(const std::string& ifname,
968 uint32_t addr,
969 uint32_t netmask) {
970 struct rtentry route;
971 memset(&route, 0, sizeof(route));
972 SetSockaddrIn(&route.rt_dst, addr & netmask);
973 SetSockaddrIn(&route.rt_genmask, netmask);
974 char rt_dev[IFNAMSIZ];
975 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
976 rt_dev[IFNAMSIZ - 1] = '\0';
977 route.rt_dev = rt_dev;
978 route.rt_flags = RTF_UP | RTF_GATEWAY;
979 return ModifyRtentry(SIOCADDRT, &route);
980}
981
982bool Datapath::DeleteIPv4Route(const std::string& ifname,
983 uint32_t addr,
984 uint32_t netmask) {
985 struct rtentry route;
986 memset(&route, 0, sizeof(route));
987 SetSockaddrIn(&route.rt_dst, addr & netmask);
988 SetSockaddrIn(&route.rt_genmask, netmask);
989 char rt_dev[IFNAMSIZ];
990 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
991 rt_dev[IFNAMSIZ - 1] = '\0';
992 route.rt_dev = rt_dev;
993 route.rt_flags = RTF_UP | RTF_GATEWAY;
994 return ModifyRtentry(SIOCDELRT, &route);
995}
996
Taoyu Lia0727dc2020-09-24 19:54:59 +0900997bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900998 DCHECK(route);
999 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001000 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001001 return false;
1002 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001003 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1004 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001005 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001006 return false;
1007 }
1008 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1009 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001010 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001011 return false;
1012 }
1013 return true;
1014}
1015
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001016bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1017 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1018 kArcAddr, kAdbServerPort, ifname,
1019 kLocalhostAddr, kAdbProxyTcpListenPort);
1020}
1021
1022void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1023 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1024 kArcAddr, kAdbServerPort, ifname,
1025 kLocalhostAddr, kAdbProxyTcpListenPort);
1026}
1027
1028bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1029 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1030 kAdbProxyTcpListenPort, ifname);
1031}
1032
1033void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1034 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1035 kAdbProxyTcpListenPort, ifname);
1036}
1037
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001038void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1039 if_nametoindex_[ifname] = ifindex;
1040}
1041
1042int Datapath::FindIfIndex(const std::string& ifname) {
1043 uint32_t ifindex = if_nametoindex(ifname.c_str());
1044 if (ifindex > 0) {
1045 if_nametoindex_[ifname] = ifindex;
1046 return ifindex;
1047 }
1048
1049 const auto it = if_nametoindex_.find(ifname);
1050 if (it != if_nametoindex_.end())
1051 return it->second;
1052
1053 return 0;
1054}
1055
Garrick Evans3388a032020-03-24 11:25:55 +09001056} // namespace patchpanel