blob: eb2e4fafc29865afb85b96ec488bde148e812cef [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 Benichi8d622b52020-08-13 15:24:12 +0900420void Datapath::StartRoutingDevice(const std::string& ext_ifname,
421 const std::string& int_ifname,
422 uint32_t int_ipv4_addr,
423 TrafficSource source) {
424 if (!ext_ifname.empty() &&
425 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
426 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
427 << "->" << int_ifname;
428
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900429 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900430 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
431 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900432
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900433 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900434 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
435 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900436
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900437 if (!ext_ifname.empty()) {
438 // If |ext_ifname| is not null, mark egress traffic with the
439 // fwmark routing tag corresponding to |ext_ifname|.
440 if (!ModifyFwmarkRoutingTag("-A", ext_ifname, int_ifname))
441 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
442 << ext_ifname << "<-" << int_ifname;
443 } else {
444 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
445 // PREROUTING to apply any fwmark routing tag saved for the current
446 // connection, and rely on implicit routing to the default logical network
447 // otherwise.
448 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname))
449 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
450 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900451
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900452 // TODO(b/161507671) When a VPN service starts, tag new connections with the
453 // fwmark routing tag for VPNs.
454 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900455
Hugo Benichi9be19b12020-08-14 15:33:40 +0900456 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
457 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
458 << source << " for " << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900459}
460
461void Datapath::StopRoutingDevice(const std::string& ext_ifname,
462 const std::string& int_ifname,
463 uint32_t int_ipv4_addr,
464 TrafficSource source) {
465 if (!ext_ifname.empty())
466 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900467 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
468 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900469 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900470 if (!ext_ifname.empty()) {
471 ModifyFwmarkRoutingTag("-D", ext_ifname, int_ifname);
472 } else {
473 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname);
474 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900475}
476
Garrick Evansf0ab7132019-06-18 14:50:42 +0900477bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
478 const std::string& ipv4_addr) {
479 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900480 if (process_runner_->iptables(
481 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
482 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900483 return false;
484
485 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900486 if (process_runner_->iptables(
487 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
488 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900489 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
490 return false;
491 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900492 if (process_runner_->iptables(
493 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
494 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900495 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
496 return false;
497 }
498
499 return true;
500}
501
502void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
503 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900504 process_runner_->iptables(
505 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
506 "--to-destination", ipv4_addr, "-w"});
507 process_runner_->iptables(
508 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
509 "--to-destination", ipv4_addr, "-w"});
510 process_runner_->iptables(
511 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
512 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900513}
514
Hugo Benichi8d622b52020-08-13 15:24:12 +0900515// TODO(hugobenichi) The name incorrectly refers to egress traffic, but this
516// FORWARD rule actually enables forwarding for ingress traffic. Fix the name.
Garrick Evansf0ab7132019-06-18 14:50:42 +0900517bool Datapath::AddOutboundIPv4(const std::string& ifname) {
Hugo Benichid82d8832020-08-14 10:05:03 +0900518 return StartIpForwarding(IpFamily::IPv4, "", ifname);
Garrick Evansf0ab7132019-06-18 14:50:42 +0900519}
520
521void Datapath::RemoveOutboundIPv4(const std::string& ifname) {
Hugo Benichid82d8832020-08-14 10:05:03 +0900522 StopIpForwarding(IpFamily::IPv4, "", ifname);
Garrick Evansf0ab7132019-06-18 14:50:42 +0900523}
524
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900525// TODO(b/161507671) Stop relying on the traffic fwmark 1/1 once forwarded
526// egress traffic is routed through the fwmark routing tag.
Garrick Evansd291af62020-05-25 10:39:06 +0900527bool Datapath::AddSNATMarkRules() {
Taoyu Li79871c92020-07-02 16:09:39 +0900528 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
529 // need to be explicitly dropped.
530 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900531 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
Taoyu Li79871c92020-07-02 16:09:39 +0900532 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0) {
533 return false;
534 }
Garrick Evansd291af62020-05-25 10:39:06 +0900535 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900536 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900537 "ACCEPT", "-w"}) != 0) {
538 return false;
539 }
540 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900541 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900542 "MASQUERADE", "-w"}) != 0) {
543 RemoveSNATMarkRules();
544 return false;
545 }
546 return true;
547}
548
549void Datapath::RemoveSNATMarkRules() {
550 process_runner_->iptables("nat", {"-D", "POSTROUTING", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900551 "1/1", "-j", "MASQUERADE", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900552 process_runner_->iptables("filter", {"-D", "FORWARD", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900553 "1/1", "-j", "ACCEPT", "-w"});
Taoyu Li79871c92020-07-02 16:09:39 +0900554 process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900555 "filter", {"-D", "FORWARD", "-m", "mark", "--mark", "1/1", "-m", "state",
Taoyu Li79871c92020-07-02 16:09:39 +0900556 "--state", "INVALID", "-j", "DROP", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900557}
558
Garrick Evansff6e37f2020-05-25 10:54:47 +0900559bool Datapath::AddInterfaceSNAT(const std::string& ifname) {
560 return process_runner_->iptables("nat", {"-A", "POSTROUTING", "-o", ifname,
561 "-j", "MASQUERADE", "-w"}) == 0;
562}
563
564void Datapath::RemoveInterfaceSNAT(const std::string& ifname) {
565 process_runner_->iptables(
566 "nat", {"-D", "POSTROUTING", "-o", ifname, "-j", "MASQUERADE", "-w"});
567}
568
Hugo Benichie8758b52020-04-03 14:49:01 +0900569bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
570 return process_runner_->iptables(
571 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900572 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900573}
574
575void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
576 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900577 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900578}
579
Garrick Evansd291af62020-05-25 10:39:06 +0900580bool Datapath::AddForwardEstablishedRule() {
581 return process_runner_->iptables(
582 "filter", {"-A", "FORWARD", "-m", "state", "--state",
583 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) == 0;
584}
585
586void Datapath::RemoveForwardEstablishedRule() {
587 process_runner_->iptables("filter",
588 {"-D", "FORWARD", "-m", "state", "--state",
589 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"});
590}
591
Garrick Evans664a82f2019-12-17 12:18:05 +0900592bool Datapath::MaskInterfaceFlags(const std::string& ifname,
593 uint16_t on,
594 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900595 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
596 if (!sock.is_valid()) {
597 PLOG(ERROR) << "Failed to create control socket";
598 return false;
599 }
600 ifreq ifr;
601 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
602 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
603 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
604 return false;
605 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900606 ifr.ifr_flags |= on;
607 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900608 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900609 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
610 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900611 return false;
612 }
613 return true;
614}
615
Garrick Evans260ff302019-07-25 11:22:50 +0900616bool Datapath::AddIPv6HostRoute(const std::string& ifname,
617 const std::string& ipv6_addr,
618 int ipv6_prefix_len) {
619 std::string ipv6_addr_cidr =
620 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
621
Garrick Evans8e8e3472020-01-23 14:03:50 +0900622 return process_runner_->ip6("route", "replace",
623 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900624}
625
626void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
627 const std::string& ipv6_addr,
628 int ipv6_prefix_len) {
629 std::string ipv6_addr_cidr =
630 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
631
Garrick Evans8e8e3472020-01-23 14:03:50 +0900632 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900633}
634
Taoyu Lia0727dc2020-09-24 19:54:59 +0900635bool Datapath::AddIPv6Address(const std::string& ifname,
636 const std::string& ipv6_addr) {
637 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900638}
639
Taoyu Lia0727dc2020-09-24 19:54:59 +0900640void Datapath::RemoveIPv6Address(const std::string& ifname,
641 const std::string& ipv6_addr) {
642 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900643}
644
Hugo Benichi76be34a2020-08-26 22:35:54 +0900645void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
646 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
647 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
648}
649
650void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
651 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
652 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
653}
654
655bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
656 const std::string& op,
657 const std::string& oif) {
658 if (oif.empty()) {
Hugo Benichibf811c62020-09-07 17:30:45 +0900659 LOG(ERROR) << "Cannot change POSTROUTING CONNMARK set-mark with no"
660 " interface specified";
Hugo Benichi76be34a2020-08-26 22:35:54 +0900661 return false;
662 }
663
664 if (!IsValidIpFamily(family)) {
665 LOG(ERROR) << "Cannot change POSTROUTING CONNMARK set-mark for " << oif
666 << ": incorrect IP family " << family;
667 return false;
668 }
669
670 int ifindex = FindIfIndex(oif);
671 if (ifindex == 0) {
672 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
673 return false;
674 }
675
676 std::vector<std::string> args = {op,
677 "POSTROUTING",
678 "-o",
679 oif,
680 "-j",
681 "CONNMARK",
682 "--set-mark",
683 Fwmark::FromIfIndex(ifindex).ToString() +
684 "/" + kFwmarkRoutingMask.ToString(),
685 "-w"};
686
687 bool success = true;
688 if (family & IPv4)
689 success &= process_runner_->iptables("mangle", args) == 0;
690 if (family & IPv6)
691 success &= process_runner_->ip6tables("mangle", args) == 0;
692 return false;
693}
694
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900695bool Datapath::ModifyConnmarkRestore(IpFamily family,
696 const std::string& chain,
697 const std::string& op,
698 const std::string& iif) {
699 if (chain != "OUTPUT" && (chain != "PREROUTING" || iif.empty())) {
700 LOG(ERROR) << "Invalid arguments chain=" << chain << " iif=" << iif;
701 return false;
702 }
703
704 if (!IsValidIpFamily(family)) {
705 LOG(ERROR) << "Cannot change " << chain << " -j CONNMARK restore-mark"
706 << " for " << iif << ": incorrect IP family " << family;
707 return false;
708 }
709
710 std::vector<std::string> args = {op, chain};
711 if (!iif.empty()) {
712 args.push_back("-i");
713 args.push_back(iif);
714 }
715 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
716 kFwmarkRoutingMask.ToString(), "-w"});
717
718 bool success = true;
719 if (family & IPv4)
720 success &= process_runner_->iptables("mangle", args) == 0;
721 if (family & IPv6)
722 success &= process_runner_->ip6tables("mangle", args) == 0;
723 return success;
724}
725
726bool Datapath::ModifyFwmarkRoutingTag(const std::string& op,
727 const std::string& ext_ifname,
728 const std::string& int_ifname) {
729 int ifindex = FindIfIndex(ext_ifname);
730 if (ifindex == 0) {
731 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
732 return false;
733 }
734
735 return ModifyFwmarkPrerouting(IpFamily::Dual, op, int_ifname,
736 Fwmark::FromIfIndex(ifindex),
737 kFwmarkRoutingMask);
738}
739
Hugo Benichi9be19b12020-08-14 15:33:40 +0900740bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
741 const std::string& iif,
742 TrafficSource source) {
743 return ModifyFwmarkPrerouting(IpFamily::Dual, op, iif,
744 Fwmark::FromSource(source),
745 kFwmarkAllSourcesMask);
746}
747
748bool Datapath::ModifyFwmarkPrerouting(IpFamily family,
749 const std::string& op,
750 const std::string& iif,
751 Fwmark mark,
752 Fwmark mask,
753 bool log_failures) {
754 if (iif.empty()) {
755 LOG(ERROR)
756 << "Cannot change PREROUTING set-fwmark with no interface specified";
757 return false;
758 }
759
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900760 if (!IsValidIpFamily(family)) {
761 LOG(ERROR) << "Cannot change PREROUTING set-fwmark for " << iif
762 << ": incorrect IP family " << family;
763 return false;
Hugo Benichi9be19b12020-08-14 15:33:40 +0900764 }
765
766 std::vector<std::string> args = {
767 op, "PREROUTING", "-i", iif,
768 "-j", "MARK", "--set-mark", mark.ToString() + "/" + mask.ToString(),
769 "-w"};
770
771 bool success = true;
Hugo Benichi5c9c11c2020-09-15 17:25:26 +0900772 if (family & IPv4)
Hugo Benichi9be19b12020-08-14 15:33:40 +0900773 success &= process_runner_->iptables("mangle", args, log_failures) == 0;
Hugo Benichi5c9c11c2020-09-15 17:25:26 +0900774 if (family & IPv6)
Hugo Benichi9be19b12020-08-14 15:33:40 +0900775 success &= process_runner_->ip6tables("mangle", args, log_failures) == 0;
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900776 return success;
Hugo Benichi9be19b12020-08-14 15:33:40 +0900777}
778
Hugo Benichid82d8832020-08-14 10:05:03 +0900779bool Datapath::ModifyIpForwarding(IpFamily family,
780 const std::string& op,
781 const std::string& iif,
782 const std::string& oif,
783 bool log_failures) {
784 if (iif.empty() && oif.empty()) {
785 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
786 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +0900787 return false;
788 }
789
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900790 if (!IsValidIpFamily(family)) {
791 LOG(ERROR) << "Cannot change IP forwarding from \"" << iif << "\" to \""
792 << oif << "\": incorrect IP family " << family;
793 return false;
Hugo Benichid82d8832020-08-14 10:05:03 +0900794 }
795
796 std::vector<std::string> args = {op, "FORWARD"};
797 if (!iif.empty()) {
798 args.push_back("-i");
799 args.push_back(iif);
800 }
801 if (!oif.empty()) {
802 args.push_back("-o");
803 args.push_back(oif);
804 }
805 args.push_back("-j");
806 args.push_back("ACCEPT");
807 args.push_back("-w");
808
809 bool success = true;
810 if (family & IpFamily::IPv4)
811 success &= process_runner_->iptables("filter", args, log_failures) == 0;
812 if (family & IpFamily::IPv6)
813 success &= process_runner_->ip6tables("filter", args, log_failures) == 0;
814 return success;
815}
816
817bool Datapath::StartIpForwarding(IpFamily family,
818 const std::string& iif,
819 const std::string& oif) {
820 return ModifyIpForwarding(family, "-A", iif, oif);
821}
822
823bool Datapath::StopIpForwarding(IpFamily family,
824 const std::string& iif,
825 const std::string& oif) {
826 return ModifyIpForwarding(family, "-D", iif, oif);
827}
828
829bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
830 const std::string& ifname2) {
831 // Only start Ipv6 forwarding if -C returns false and it had not been
832 // started yet.
833 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
834 false /*log_failures*/) &&
835 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
836 return false;
837 }
838
839 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
840 false /*log_failures*/) &&
841 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +0900842 RemoveIPv6Forwarding(ifname1, ifname2);
843 return false;
844 }
845
846 return true;
847}
848
849void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
850 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +0900851 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
852 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +0900853}
854
Garrick Evans3d97a392020-02-21 15:24:37 +0900855bool Datapath::AddIPv4Route(uint32_t gateway_addr,
856 uint32_t addr,
857 uint32_t netmask) {
858 struct rtentry route;
859 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +0900860 SetSockaddrIn(&route.rt_gateway, gateway_addr);
861 SetSockaddrIn(&route.rt_dst, addr & netmask);
862 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +0900863 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +0900864 return ModifyRtentry(SIOCADDRT, &route);
865}
Garrick Evans3d97a392020-02-21 15:24:37 +0900866
Hugo Benichie8758b52020-04-03 14:49:01 +0900867bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
868 uint32_t addr,
869 uint32_t netmask) {
870 struct rtentry route;
871 memset(&route, 0, sizeof(route));
872 SetSockaddrIn(&route.rt_gateway, gateway_addr);
873 SetSockaddrIn(&route.rt_dst, addr & netmask);
874 SetSockaddrIn(&route.rt_genmask, netmask);
875 route.rt_flags = RTF_UP | RTF_GATEWAY;
876 return ModifyRtentry(SIOCDELRT, &route);
877}
878
879bool Datapath::AddIPv4Route(const std::string& ifname,
880 uint32_t addr,
881 uint32_t netmask) {
882 struct rtentry route;
883 memset(&route, 0, sizeof(route));
884 SetSockaddrIn(&route.rt_dst, addr & netmask);
885 SetSockaddrIn(&route.rt_genmask, netmask);
886 char rt_dev[IFNAMSIZ];
887 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
888 rt_dev[IFNAMSIZ - 1] = '\0';
889 route.rt_dev = rt_dev;
890 route.rt_flags = RTF_UP | RTF_GATEWAY;
891 return ModifyRtentry(SIOCADDRT, &route);
892}
893
894bool Datapath::DeleteIPv4Route(const std::string& ifname,
895 uint32_t addr,
896 uint32_t netmask) {
897 struct rtentry route;
898 memset(&route, 0, sizeof(route));
899 SetSockaddrIn(&route.rt_dst, addr & netmask);
900 SetSockaddrIn(&route.rt_genmask, netmask);
901 char rt_dev[IFNAMSIZ];
902 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
903 rt_dev[IFNAMSIZ - 1] = '\0';
904 route.rt_dev = rt_dev;
905 route.rt_flags = RTF_UP | RTF_GATEWAY;
906 return ModifyRtentry(SIOCDELRT, &route);
907}
908
Taoyu Lia0727dc2020-09-24 19:54:59 +0900909bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900910 DCHECK(route);
911 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +0200912 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +0900913 return false;
914 }
Hugo Benichie8758b52020-04-03 14:49:01 +0900915 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
916 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +0200917 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +0900918 return false;
919 }
920 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
921 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +0200922 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +0900923 return false;
924 }
925 return true;
926}
927
Jason Jeremy Imana7273a32020-08-04 11:25:31 +0900928bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
929 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
930 kArcAddr, kAdbServerPort, ifname,
931 kLocalhostAddr, kAdbProxyTcpListenPort);
932}
933
934void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
935 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
936 kArcAddr, kAdbServerPort, ifname,
937 kLocalhostAddr, kAdbProxyTcpListenPort);
938}
939
940bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
941 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
942 kAdbProxyTcpListenPort, ifname);
943}
944
945void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
946 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
947 kAdbProxyTcpListenPort, ifname);
948}
949
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900950void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
951 if_nametoindex_[ifname] = ifindex;
952}
953
954int Datapath::FindIfIndex(const std::string& ifname) {
955 uint32_t ifindex = if_nametoindex(ifname.c_str());
956 if (ifindex > 0) {
957 if_nametoindex_[ifname] = ifindex;
958 return ifindex;
959 }
960
961 const auto it = if_nametoindex_.find(ifname);
962 if (it != if_nametoindex_.end())
963 return it->second;
964
965 return 0;
966}
967
Garrick Evans3388a032020-03-24 11:25:55 +0900968} // namespace patchpanel