blob: 8e3b7a038567609e19a85b2953c6b4f5c0807c81 [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
Garrick Evans8a067562020-05-11 12:47:30 +090041std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
42 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090043 if (n.length() < IFNAMSIZ)
44 return n;
Garrick Evans54861622019-07-19 09:05:09 +090045
Garrick Evans2f581a02020-05-11 10:43:35 +090046 // Best effort attempt to preserve the interface number, assuming it's the
47 // last char in the name.
48 auto c = ifname[ifname.length() - 1];
49 n.resize(IFNAMSIZ - 1);
50 n[n.length() - 1] = c;
51 return n;
Garrick Evans54861622019-07-19 09:05:09 +090052}
Garrick Evansf0ab7132019-06-18 14:50:42 +090053
Garrick Evans8a067562020-05-11 12:47:30 +090054} // namespace
55
56std::string ArcVethHostName(const std::string& ifname) {
57 return PrefixIfname("veth", ifname);
58}
59
60std::string ArcBridgeName(const std::string& ifname) {
61 return PrefixIfname("arc_", ifname);
62}
63
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090064Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
65 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090066
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090067Datapath::Datapath(MinijailedProcessRunner* process_runner,
68 Firewall* firewall,
69 ioctl_t ioctl_hook)
70 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +090071 CHECK(process_runner_);
72}
73
Garrick Evans260ff302019-07-25 11:22:50 +090074MinijailedProcessRunner& Datapath::runner() const {
75 return *process_runner_;
76}
77
Hugo Benichi33860d72020-07-09 16:34:01 +090078bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
79 // Try first to delete any netns with name |netns_name| in case patchpanel
80 // did not exit cleanly.
81 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
82 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
83 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
84}
85
86bool Datapath::NetnsDeleteName(const std::string& netns_name) {
87 return process_runner_->ip_netns_delete(netns_name) == 0;
88}
89
Garrick Evans8a949dc2019-07-18 16:17:53 +090090bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +090091 uint32_t ipv4_addr,
92 uint32_t ipv4_prefix_len) {
Garrick Evans8a949dc2019-07-18 16:17:53 +090093 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans8e8e3472020-01-23 14:03:50 +090094 if (process_runner_->brctl("addbr", {ifname}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +090095 return false;
96 }
97
Garrick Evans6f4fa3a2020-02-10 16:15:09 +090098 if (process_runner_->ip(
99 "addr", "add",
100 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
101 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
102 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900103 RemoveBridge(ifname);
104 return false;
105 }
106
107 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900108 RemoveBridge(ifname);
109 return false;
110 }
111
112 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900113 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900114 RemoveBridge(ifname);
115 return false;
116 }
117
118 return true;
119}
120
121void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900122 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900123 process_runner_->ip("link", "set", {ifname, "down"});
Garrick Evans8e8e3472020-01-23 14:03:50 +0900124 process_runner_->brctl("delbr", {ifname});
Garrick Evans8a949dc2019-07-18 16:17:53 +0900125}
126
Garrick Evans621ed262019-11-13 12:28:43 +0900127bool Datapath::AddToBridge(const std::string& br_ifname,
128 const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900129 return (process_runner_->brctl("addif", {br_ifname, ifname}) == 0);
Garrick Evans621ed262019-11-13 12:28:43 +0900130}
131
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900132std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900133 const MacAddress* mac_addr,
134 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900135 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900136 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
137 if (!dev.is_valid()) {
138 PLOG(ERROR) << "Failed to open " << kTunDev;
139 return "";
140 }
141
142 struct ifreq ifr;
143 memset(&ifr, 0, sizeof(ifr));
144 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
145 sizeof(ifr.ifr_name));
146 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
147
148 // If a template was given as the name, ifr_name will be updated with the
149 // actual interface name.
150 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900151 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900152 return "";
153 }
154 const char* ifname = ifr.ifr_name;
155
156 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900157 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900158 return "";
159 }
160
Garrick Evans4f9f5572019-11-26 10:25:16 +0900161 if (!user.empty()) {
162 uid_t uid = -1;
163 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
164 PLOG(ERROR) << "Unable to look up UID for " << user;
165 RemoveTAP(ifname);
166 return "";
167 }
168 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
169 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
170 << ifname;
171 RemoveTAP(ifname);
172 return "";
173 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900174 }
175
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900176 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900177 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
178 if (!sock.is_valid()) {
179 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900180 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900181 RemoveTAP(ifname);
182 return "";
183 }
184
Garrick Evans621ed262019-11-13 12:28:43 +0900185 if (ipv4_addr) {
186 struct sockaddr_in* addr =
187 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
188 addr->sin_family = AF_INET;
189 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
190 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
191 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
192 << " {" << ipv4_addr->ToCidrString() << "}";
193 RemoveTAP(ifname);
194 return "";
195 }
196
197 struct sockaddr_in* netmask =
198 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
199 netmask->sin_family = AF_INET;
200 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
201 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
202 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
203 << " {" << ipv4_addr->ToCidrString() << "}";
204 RemoveTAP(ifname);
205 return "";
206 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900207 }
208
Garrick Evans621ed262019-11-13 12:28:43 +0900209 if (mac_addr) {
210 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
211 hwaddr->sa_family = ARPHRD_ETHER;
212 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
213 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
214 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
215 << " {" << MacAddressToString(*mac_addr) << "}";
216 RemoveTAP(ifname);
217 return "";
218 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900219 }
220
221 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900222 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900223 RemoveTAP(ifname);
224 return "";
225 }
226
227 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
228 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900229 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900230 RemoveTAP(ifname);
231 return "";
232 }
233
234 return ifname;
235}
236
237void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900238 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900239}
240
Hugo Benichi33860d72020-07-09 16:34:01 +0900241bool Datapath::ConnectVethPair(pid_t netns_pid,
242 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900243 const std::string& veth_ifname,
244 const std::string& peer_ifname,
245 const MacAddress& remote_mac_addr,
246 uint32_t remote_ipv4_addr,
247 uint32_t remote_ipv4_prefix_len,
248 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900249 // Set up the virtual pair across the current namespace and |netns_name|.
250 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
251 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
252 << peer_ifname;
253 return false;
254 }
255
256 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900257 {
Hugo Benichi33860d72020-07-09 16:34:01 +0900258 ScopedNS ns(netns_pid);
259 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900260 LOG(ERROR)
261 << "Cannot create virtual link -- invalid container namespace?";
262 return false;
263 }
264
Hugo Benichi76675592020-04-08 14:29:57 +0900265 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
266 remote_ipv4_prefix_len, true /* link up */,
267 remote_multicast_flag)) {
268 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
269 RemoveInterface(peer_ifname);
270 return false;
271 }
272 }
273
Hugo Benichi76675592020-04-08 14:29:57 +0900274 if (!ToggleInterface(veth_ifname, true /*up*/)) {
275 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
276 RemoveInterface(veth_ifname);
277 return false;
278 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900279
Hugo Benichi76675592020-04-08 14:29:57 +0900280 return true;
281}
282
Hugo Benichi33860d72020-07-09 16:34:01 +0900283bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
284 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900285 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900286 return process_runner_->ip("link", "add",
287 {veth_ifname, "type", "veth", "peer", "name",
288 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900289}
Garrick Evans54861622019-07-19 09:05:09 +0900290
Garrick Evans2470caa2020-03-04 14:15:41 +0900291bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
292 const std::string link = up ? "up" : "down";
293 return process_runner_->ip("link", "set", {ifname, link}) == 0;
294}
Garrick Evans54861622019-07-19 09:05:09 +0900295
Garrick Evans2470caa2020-03-04 14:15:41 +0900296bool Datapath::ConfigureInterface(const std::string& ifname,
297 const MacAddress& mac_addr,
298 uint32_t ipv4_addr,
299 uint32_t ipv4_prefix_len,
300 bool up,
301 bool enable_multicast) {
302 const std::string link = up ? "up" : "down";
303 const std::string multicast = enable_multicast ? "on" : "off";
304 return (process_runner_->ip(
305 "addr", "add",
306 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
307 IPv4AddressToString(
308 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
309 "dev", ifname}) == 0) &&
310 (process_runner_->ip("link", "set",
311 {
312 "dev",
313 ifname,
314 link,
315 "addr",
316 MacAddressToString(mac_addr),
317 "multicast",
318 multicast,
319 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900320}
321
322void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900323 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900324}
325
Hugo Benichi8d622b52020-08-13 15:24:12 +0900326void Datapath::StartRoutingDevice(const std::string& ext_ifname,
327 const std::string& int_ifname,
328 uint32_t int_ipv4_addr,
329 TrafficSource source) {
330 if (!ext_ifname.empty() &&
331 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
332 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
333 << "->" << int_ifname;
334
335 // TODO(b/161508179) Explicitly enable IPv4 forwarding for this pair of
336 // interfaces for the ingress direction.
337 if (!AddOutboundIPv4(int_ifname))
338 LOG(ERROR) << "Failed to configure egress traffic rules for " << ext_ifname
339 << "<-" << int_ifname;
340
341 // TODO(b/161508179) Explicitly enable IPv4 forwarding for this pair of
342 // interfaces for the egress direction and stop relying on the traffic fwmark
343 // matching 1/1 once forwarded egress traffic is routed through the fwmark
344 // routing tag.
345
346 // TODO(b/161507671) If ext_ifname is not null, mark egress traffic with the
347 // fwmark routing tag corresponding to |ext_ifname|, and set up strong routing
348 // in ip rule.
349
350 // TODO(b/161507671) If ext_ifname is null, set up connection tracking for the
351 // current default interface.
352
353 // TODO(b/161508179) Start marking egress traffic with the corresponding
354 // source fwmark in mangle PREROUTING.
355}
356
357void Datapath::StopRoutingDevice(const std::string& ext_ifname,
358 const std::string& int_ifname,
359 uint32_t int_ipv4_addr,
360 TrafficSource source) {
361 if (!ext_ifname.empty())
362 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
363 RemoveOutboundIPv4(int_ifname);
364
365 // TODO(b/161508179) Stops IPv4 forwarding for this pair of interfaces.
366 // TODO(b/161508179) Remove source marking for egress traffic.
367 // TODO(b/161507671) Remove routing tag marking for egress traffic.
368}
369
Garrick Evansf0ab7132019-06-18 14:50:42 +0900370bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
371 const std::string& ipv4_addr) {
372 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900373 if (process_runner_->iptables(
374 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
375 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900376 return false;
377
378 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900379 if (process_runner_->iptables(
380 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
381 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900382 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
383 return false;
384 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900385 if (process_runner_->iptables(
386 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
387 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900388 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
389 return false;
390 }
391
392 return true;
393}
394
395void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
396 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900397 process_runner_->iptables(
398 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
399 "--to-destination", ipv4_addr, "-w"});
400 process_runner_->iptables(
401 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
402 "--to-destination", ipv4_addr, "-w"});
403 process_runner_->iptables(
404 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
405 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900406}
407
Hugo Benichi8d622b52020-08-13 15:24:12 +0900408// TODO(hugobenichi) The name incorrectly refers to egress traffic, but this
409// FORWARD rule actually enables forwarding for ingress traffic. Fix the name.
Garrick Evansf0ab7132019-06-18 14:50:42 +0900410bool Datapath::AddOutboundIPv4(const std::string& ifname) {
Hugo Benichid82d8832020-08-14 10:05:03 +0900411 return StartIpForwarding(IpFamily::IPv4, "", ifname);
Garrick Evansf0ab7132019-06-18 14:50:42 +0900412}
413
414void Datapath::RemoveOutboundIPv4(const std::string& ifname) {
Hugo Benichid82d8832020-08-14 10:05:03 +0900415 StopIpForwarding(IpFamily::IPv4, "", ifname);
Garrick Evansf0ab7132019-06-18 14:50:42 +0900416}
417
Garrick Evansd291af62020-05-25 10:39:06 +0900418bool Datapath::AddSNATMarkRules() {
Taoyu Li79871c92020-07-02 16:09:39 +0900419 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
420 // need to be explicitly dropped.
421 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900422 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
Taoyu Li79871c92020-07-02 16:09:39 +0900423 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0) {
424 return false;
425 }
Garrick Evansd291af62020-05-25 10:39:06 +0900426 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900427 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900428 "ACCEPT", "-w"}) != 0) {
429 return false;
430 }
431 if (process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900432 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
Garrick Evansd291af62020-05-25 10:39:06 +0900433 "MASQUERADE", "-w"}) != 0) {
434 RemoveSNATMarkRules();
435 return false;
436 }
437 return true;
438}
439
440void Datapath::RemoveSNATMarkRules() {
441 process_runner_->iptables("nat", {"-D", "POSTROUTING", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900442 "1/1", "-j", "MASQUERADE", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900443 process_runner_->iptables("filter", {"-D", "FORWARD", "-m", "mark", "--mark",
Hugo Benichi6c445322020-08-12 16:46:19 +0900444 "1/1", "-j", "ACCEPT", "-w"});
Taoyu Li79871c92020-07-02 16:09:39 +0900445 process_runner_->iptables(
Hugo Benichi6c445322020-08-12 16:46:19 +0900446 "filter", {"-D", "FORWARD", "-m", "mark", "--mark", "1/1", "-m", "state",
Taoyu Li79871c92020-07-02 16:09:39 +0900447 "--state", "INVALID", "-j", "DROP", "-w"});
Garrick Evansd291af62020-05-25 10:39:06 +0900448}
449
Garrick Evansff6e37f2020-05-25 10:54:47 +0900450bool Datapath::AddInterfaceSNAT(const std::string& ifname) {
451 return process_runner_->iptables("nat", {"-A", "POSTROUTING", "-o", ifname,
452 "-j", "MASQUERADE", "-w"}) == 0;
453}
454
455void Datapath::RemoveInterfaceSNAT(const std::string& ifname) {
456 process_runner_->iptables(
457 "nat", {"-D", "POSTROUTING", "-o", ifname, "-j", "MASQUERADE", "-w"});
458}
459
Hugo Benichie8758b52020-04-03 14:49:01 +0900460bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
461 return process_runner_->iptables(
462 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900463 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900464}
465
466void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
467 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900468 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900469}
470
Garrick Evansd291af62020-05-25 10:39:06 +0900471bool Datapath::AddForwardEstablishedRule() {
472 return process_runner_->iptables(
473 "filter", {"-A", "FORWARD", "-m", "state", "--state",
474 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) == 0;
475}
476
477void Datapath::RemoveForwardEstablishedRule() {
478 process_runner_->iptables("filter",
479 {"-D", "FORWARD", "-m", "state", "--state",
480 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"});
481}
482
Garrick Evans664a82f2019-12-17 12:18:05 +0900483bool Datapath::MaskInterfaceFlags(const std::string& ifname,
484 uint16_t on,
485 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900486 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
487 if (!sock.is_valid()) {
488 PLOG(ERROR) << "Failed to create control socket";
489 return false;
490 }
491 ifreq ifr;
492 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
493 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
494 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
495 return false;
496 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900497 ifr.ifr_flags |= on;
498 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900499 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900500 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
501 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900502 return false;
503 }
504 return true;
505}
506
Garrick Evans260ff302019-07-25 11:22:50 +0900507bool Datapath::AddIPv6HostRoute(const std::string& ifname,
508 const std::string& ipv6_addr,
509 int ipv6_prefix_len) {
510 std::string ipv6_addr_cidr =
511 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
512
Garrick Evans8e8e3472020-01-23 14:03:50 +0900513 return process_runner_->ip6("route", "replace",
514 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900515}
516
517void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
518 const std::string& ipv6_addr,
519 int ipv6_prefix_len) {
520 std::string ipv6_addr_cidr =
521 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
522
Garrick Evans8e8e3472020-01-23 14:03:50 +0900523 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900524}
525
526bool Datapath::AddIPv6Neighbor(const std::string& ifname,
527 const std::string& ipv6_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900528 return process_runner_->ip6("neigh", "add",
529 {"proxy", ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900530}
531
532void Datapath::RemoveIPv6Neighbor(const std::string& ifname,
533 const std::string& ipv6_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900534 process_runner_->ip6("neigh", "del", {"proxy", ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900535}
536
Hugo Benichid82d8832020-08-14 10:05:03 +0900537bool Datapath::ModifyIpForwarding(IpFamily family,
538 const std::string& op,
539 const std::string& iif,
540 const std::string& oif,
541 bool log_failures) {
542 if (iif.empty() && oif.empty()) {
543 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
544 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +0900545 return false;
546 }
547
Hugo Benichid82d8832020-08-14 10:05:03 +0900548 switch (family) {
549 case IPv4:
550 case IPv6:
551 case Dual:
552 break;
553 default:
554
555 LOG(ERROR) << "Cannot change IP forwarding from \"" << iif << "\" to \""
556 << oif << "\": incorrect IP family " << family;
557 return false;
558 }
559
560 std::vector<std::string> args = {op, "FORWARD"};
561 if (!iif.empty()) {
562 args.push_back("-i");
563 args.push_back(iif);
564 }
565 if (!oif.empty()) {
566 args.push_back("-o");
567 args.push_back(oif);
568 }
569 args.push_back("-j");
570 args.push_back("ACCEPT");
571 args.push_back("-w");
572
573 bool success = true;
574 if (family & IpFamily::IPv4)
575 success &= process_runner_->iptables("filter", args, log_failures) == 0;
576 if (family & IpFamily::IPv6)
577 success &= process_runner_->ip6tables("filter", args, log_failures) == 0;
578 return success;
579}
580
581bool Datapath::StartIpForwarding(IpFamily family,
582 const std::string& iif,
583 const std::string& oif) {
584 return ModifyIpForwarding(family, "-A", iif, oif);
585}
586
587bool Datapath::StopIpForwarding(IpFamily family,
588 const std::string& iif,
589 const std::string& oif) {
590 return ModifyIpForwarding(family, "-D", iif, oif);
591}
592
593bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
594 const std::string& ifname2) {
595 // Only start Ipv6 forwarding if -C returns false and it had not been
596 // started yet.
597 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
598 false /*log_failures*/) &&
599 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
600 return false;
601 }
602
603 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
604 false /*log_failures*/) &&
605 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +0900606 RemoveIPv6Forwarding(ifname1, ifname2);
607 return false;
608 }
609
610 return true;
611}
612
613void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
614 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +0900615 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
616 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +0900617}
618
Garrick Evans3d97a392020-02-21 15:24:37 +0900619bool Datapath::AddIPv4Route(uint32_t gateway_addr,
620 uint32_t addr,
621 uint32_t netmask) {
622 struct rtentry route;
623 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +0900624 SetSockaddrIn(&route.rt_gateway, gateway_addr);
625 SetSockaddrIn(&route.rt_dst, addr & netmask);
626 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +0900627 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +0900628 return ModifyRtentry(SIOCADDRT, &route);
629}
Garrick Evans3d97a392020-02-21 15:24:37 +0900630
Hugo Benichie8758b52020-04-03 14:49:01 +0900631bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
632 uint32_t addr,
633 uint32_t netmask) {
634 struct rtentry route;
635 memset(&route, 0, sizeof(route));
636 SetSockaddrIn(&route.rt_gateway, gateway_addr);
637 SetSockaddrIn(&route.rt_dst, addr & netmask);
638 SetSockaddrIn(&route.rt_genmask, netmask);
639 route.rt_flags = RTF_UP | RTF_GATEWAY;
640 return ModifyRtentry(SIOCDELRT, &route);
641}
642
643bool Datapath::AddIPv4Route(const std::string& ifname,
644 uint32_t addr,
645 uint32_t netmask) {
646 struct rtentry route;
647 memset(&route, 0, sizeof(route));
648 SetSockaddrIn(&route.rt_dst, addr & netmask);
649 SetSockaddrIn(&route.rt_genmask, netmask);
650 char rt_dev[IFNAMSIZ];
651 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
652 rt_dev[IFNAMSIZ - 1] = '\0';
653 route.rt_dev = rt_dev;
654 route.rt_flags = RTF_UP | RTF_GATEWAY;
655 return ModifyRtentry(SIOCADDRT, &route);
656}
657
658bool Datapath::DeleteIPv4Route(const std::string& ifname,
659 uint32_t addr,
660 uint32_t netmask) {
661 struct rtentry route;
662 memset(&route, 0, sizeof(route));
663 SetSockaddrIn(&route.rt_dst, addr & netmask);
664 SetSockaddrIn(&route.rt_genmask, netmask);
665 char rt_dev[IFNAMSIZ];
666 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
667 rt_dev[IFNAMSIZ - 1] = '\0';
668 route.rt_dev = rt_dev;
669 route.rt_flags = RTF_UP | RTF_GATEWAY;
670 return ModifyRtentry(SIOCDELRT, &route);
671}
672
673bool Datapath::ModifyRtentry(unsigned long op, struct rtentry* route) {
674 DCHECK(route);
675 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +0200676 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +0900677 return false;
678 }
Hugo Benichie8758b52020-04-03 14:49:01 +0900679 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
680 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +0200681 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +0900682 return false;
683 }
684 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
685 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +0200686 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +0900687 return false;
688 }
689 return true;
690}
691
Jason Jeremy Imana7273a32020-08-04 11:25:31 +0900692bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
693 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
694 kArcAddr, kAdbServerPort, ifname,
695 kLocalhostAddr, kAdbProxyTcpListenPort);
696}
697
698void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
699 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
700 kArcAddr, kAdbServerPort, ifname,
701 kLocalhostAddr, kAdbProxyTcpListenPort);
702}
703
704bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
705 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
706 kAdbProxyTcpListenPort, ifname);
707}
708
709void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
710 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
711 kAdbProxyTcpListenPort, ifname);
712}
713
Garrick Evans3388a032020-03-24 11:25:55 +0900714} // namespace patchpanel