blob: 5c0517ef46f94ed67b098041b0d35bb8d2727272 [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 Benichi2a940542020-10-26 18:50:49 +090018#include <algorithm>
Hugo Benichid82d8832020-08-14 10:05:03 +090019
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>
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +090024#include <base/strings/string_util.h>
25#include <base/strings/stringprintf.h>
Garrick Evans4f9f5572019-11-26 10:25:16 +090026#include <brillo/userdb_utils.h>
Garrick Evans54861622019-07-19 09:05:09 +090027
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090028#include "patchpanel/adb_proxy.h"
Hugo Benichibfc49112020-12-14 12:54:44 +090029#include "patchpanel/arc_service.h"
Garrick Evans3388a032020-03-24 11:25:55 +090030#include "patchpanel/net_util.h"
31#include "patchpanel/scoped_ns.h"
Garrick Evansc7ae82c2019-09-04 16:25:10 +090032
Garrick Evans3388a032020-03-24 11:25:55 +090033namespace patchpanel {
Garrick Evans54861622019-07-19 09:05:09 +090034
Garrick Evansc7ae82c2019-09-04 16:25:10 +090035namespace {
Hugo Benichi76675592020-04-08 14:29:57 +090036// TODO(hugobenichi) Consolidate this constant definition in a single place.
37constexpr pid_t kTestPID = -2;
Garrick Evansc7ae82c2019-09-04 16:25:10 +090038constexpr char kDefaultIfname[] = "vmtap%d";
39constexpr char kTunDev[] = "/dev/net/tun";
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090040constexpr char kArcAddr[] = "100.115.92.2";
41constexpr char kLocalhostAddr[] = "127.0.0.1";
42constexpr uint16_t kAdbServerPort = 5555;
Hugo Benichie8758b52020-04-03 14:49:01 +090043
Hugo Benichibf811c62020-09-07 17:30:45 +090044// Constants used for dropping locally originated traffic bound to an incorrect
45// source IPv4 address.
46constexpr char kGuestIPv4Subnet[] = "100.115.92.0/23";
47constexpr std::array<const char*, 6> kPhysicalIfnamePrefixes{
48 {"eth+", "wlan+", "mlan+", "usb+", "wwan+", "rmnet+"}};
49
Hugo Benichi3a9162b2020-09-09 15:47:40 +090050constexpr char kApplyLocalSourceMarkChain[] = "apply_local_source_mark";
Hugo Benichi3ef370b2020-11-16 19:07:17 +090051constexpr char kApplyVpnMarkChain[] = "apply_vpn_mark";
Hugo Benichi155de002021-01-19 16:45:46 +090052constexpr char kCheckRoutingMarkChain[] = "check_routing_mark";
Hugo Benichi3ef370b2020-11-16 19:07:17 +090053
Hugo Benichi2a940542020-10-26 18:50:49 +090054// Constant fwmark mask for matching local socket traffic that should be routed
55// through a VPN connection. The traffic must not be part of an existing
56// connection and must match exactly the VPN routing intent policy bit.
57const Fwmark kFwmarkVpnMatchingMask = kFwmarkRoutingMask | kFwmarkVpnMask;
58
Garrick Evans8a067562020-05-11 12:47:30 +090059std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
60 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090061 if (n.length() < IFNAMSIZ)
62 return n;
Garrick Evans54861622019-07-19 09:05:09 +090063
Garrick Evans2f581a02020-05-11 10:43:35 +090064 // Best effort attempt to preserve the interface number, assuming it's the
65 // last char in the name.
66 auto c = ifname[ifname.length() - 1];
67 n.resize(IFNAMSIZ - 1);
68 n[n.length() - 1] = c;
69 return n;
Garrick Evans54861622019-07-19 09:05:09 +090070}
Garrick Evansf0ab7132019-06-18 14:50:42 +090071
Garrick Evans8a067562020-05-11 12:47:30 +090072} // namespace
73
74std::string ArcVethHostName(const std::string& ifname) {
75 return PrefixIfname("veth", ifname);
76}
77
78std::string ArcBridgeName(const std::string& ifname) {
79 return PrefixIfname("arc_", ifname);
80}
81
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090082Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
83 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090084
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090085Datapath::Datapath(MinijailedProcessRunner* process_runner,
86 Firewall* firewall,
87 ioctl_t ioctl_hook)
88 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +090089 CHECK(process_runner_);
90}
91
Garrick Evans260ff302019-07-25 11:22:50 +090092MinijailedProcessRunner& Datapath::runner() const {
93 return *process_runner_;
94}
95
Hugo Benichibf811c62020-09-07 17:30:45 +090096void Datapath::Start() {
97 // Enable IPv4 packet forwarding
98 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
99 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
100 << " Guest connectivity will not work correctly.";
101
102 // Limit local port range: Android owns 47104-61000.
103 // TODO(garrick): The original history behind this tweak is gone. Some
104 // investigation is needed to see if it is still applicable.
105 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
106 "32768 47103") != 0)
107 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
108 << " apps may not work correctly.";
109
110 // Enable IPv6 packet forwarding
111 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
112 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
113 << " IPv6 functionality may be broken.";
114
Hugo Benichi58125d32020-09-09 11:25:45 +0900115 // Create a FORWARD ACCEPT rule for connections already established.
116 if (process_runner_->iptables(
117 "filter", {"-A", "FORWARD", "-m", "state", "--state",
118 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900119 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
Hugo Benichi561fae42021-01-22 15:28:40 +0900133 // Set static SNAT rules for any IPv4 traffic originated from a guest (ARC,
134 // Crostini, ...) or a connected namespace.
135 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
136 // need to be explicitly dropped as SNAT cannot be applied to them.
137 if (process_runner_->iptables(
138 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
139 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0)
140 LOG(ERROR) << "Failed to install SNAT mark rules.";
141 if (process_runner_->iptables(
142 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
143 "MASQUERADE", "-w"}) != 0)
144 LOG(ERROR) << "Failed to install SNAT mark rules.";
Hugo Benichibf811c62020-09-07 17:30:45 +0900145 if (!AddOutboundIPv4SNATMark("vmtap+"))
Hugo Benichi561fae42021-01-22 15:28:40 +0900146 LOG(ERROR) << "Failed to set up NAT for TAP devices.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900147
Taoyu Li78f0c9a2020-12-25 22:58:26 +0900148 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
149 // wrongly cause neighbor discovery icmpv6 packets to be dropped. Add these
150 // rules to bypass connmark rule for those packets.
151 for (const auto& type : kNeighborDiscoveryTypes) {
152 if (!ModifyIptables(IpFamily::IPv6, "mangle",
153 {"-A", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
154 "-j", "ACCEPT", "-w"}))
155 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
156 << " packets";
157 }
158
Hugo Benichi2a940542020-10-26 18:50:49 +0900159 // Applies the routing tag saved in conntrack for any established connection
160 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900161 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
162 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900163 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
Hugo Benichi155de002021-01-19 16:45:46 +0900164 // b/177787823 Also restore the routing tag after routing has taken place so
165 // that packets pre-tagged with the VPN routing tag are in sync with their
166 // associated CONNMARK routing tag. This is necessary to correctly identify
167 // packets exiting through the wrong interface.
168 if (!ModifyConnmarkRestore(IpFamily::Dual, "POSTROUTING", "-A", "" /*iif*/,
169 kFwmarkRoutingMask))
170 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK restore rule";
Hugo Benichi2a940542020-10-26 18:50:49 +0900171
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900172 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
173 // tag and tagging the local traffic that should be routed through a VPN.
174 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyLocalSourceMarkChain))
175 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
176 << " mangle chain";
177 // Ensure that the chain is empty if patchpanel is restarting after a crash.
178 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyLocalSourceMarkChain))
179 LOG(ERROR) << "Failed to flush " << kApplyLocalSourceMarkChain
180 << " mangle chain";
181 if (!ModifyIptables(IpFamily::Dual, "mangle",
182 {"-A", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
183 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
184 << " to mangle OUTPUT";
185 // Create rules for tagging local sources with the source tag and the vpn
186 // policy tag.
187 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900188 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900189 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
190 << " in " << kApplyLocalSourceMarkChain;
191 }
192 // Finally add a catch-all rule for tagging any remaining local sources with
193 // the SYSTEM source tag
194 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
195 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
196
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900197 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
198 // traffic that should be routed through a VPN.
199 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyVpnMarkChain))
200 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
201 // Ensure that the chain is empty if patchpanel is restarting after a crash.
202 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyVpnMarkChain))
203 LOG(ERROR) << "Failed to flush " << kApplyVpnMarkChain << " mangle chain";
204 // All local outgoing traffic eligible to VPN routing should traverse the VPN
205 // marking chain.
206 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", "" /*iif*/, kFwmarkRouteOnVpn,
207 kFwmarkVpnMask))
208 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
209 // Any traffic that already has a routing tag applied is accepted.
210 if (!ModifyIptables(
211 IpFamily::Dual, "mangle",
212 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
213 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
214 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
215 "connections";
Hugo Benichi155de002021-01-19 16:45:46 +0900216
217 // Sets up a mangle chain used in POSTROUTING for checking consistency between
218 // the routing tag and the output interface.
219 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kCheckRoutingMarkChain))
220 LOG(ERROR) << "Failed to set up " << kCheckRoutingMarkChain
221 << " mangle chain";
222 // Ensure that the chain is empty if patchpanel is restarting after a crash.
223 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kCheckRoutingMarkChain))
224 LOG(ERROR) << "Failed to flush " << kCheckRoutingMarkChain
225 << " mangle chain";
226
227 // b/177787823 If it already exists, the routing tag of any traffic exiting an
228 // interface (physical or VPN) must match the routing tag of that interface.
229 if (!ModifyIptables(IpFamily::Dual, "mangle",
230 {"-A", "POSTROUTING", "-m", "mark", "!", "--mark",
231 "0x0/" + kFwmarkRoutingMask.ToString(), "-j",
232 kCheckRoutingMarkChain, "-w"}))
233 LOG(ERROR) << "Failed to add POSTROUTING jump rule to "
234 << kCheckRoutingMarkChain;
Hugo Benichibf811c62020-09-07 17:30:45 +0900235}
236
237void Datapath::Stop() {
Hugo Benichi561fae42021-01-22 15:28:40 +0900238 // Remove static IPv4 SNAT rules.
Hugo Benichibf811c62020-09-07 17:30:45 +0900239 RemoveOutboundIPv4SNATMark("vmtap+");
Hugo Benichi58125d32020-09-09 11:25:45 +0900240 process_runner_->iptables("filter",
241 {"-D", "FORWARD", "-m", "state", "--state",
242 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"});
Hugo Benichi561fae42021-01-22 15:28:40 +0900243 process_runner_->iptables("nat", {"-D", "POSTROUTING", "-m", "mark", "--mark",
244 "1/1", "-j", "MASQUERADE", "-w"});
245 process_runner_->iptables(
246 "filter", {"-D", "FORWARD", "-m", "mark", "--mark", "1/1", "-m", "state",
247 "--state", "INVALID", "-j", "DROP", "-w"});
248
Hugo Benichibf811c62020-09-07 17:30:45 +0900249 for (const auto& oif : kPhysicalIfnamePrefixes)
250 RemoveSourceIPv4DropRule(oif, kGuestIPv4Subnet);
251
252 // Restore original local port range.
253 // TODO(garrick): The original history behind this tweak is gone. Some
254 // investigation is needed to see if it is still applicable.
255 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
256 "32768 61000") != 0)
257 LOG(ERROR) << "Failed to restore local port range";
258
259 // Disable packet forwarding
260 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
261 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
262
263 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
264 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900265
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900266 // Detach the VPN marking mangle chain
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900267 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-D", "" /*iif*/, kFwmarkRouteOnVpn,
268 kFwmarkVpnMask))
269 LOG(ERROR)
270 << "Failed to remove from mangle OUTPUT chain jump rule to VPN chain";
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900271
272 // Detach apply_local_source_mark from mangle PREROUTING
273 if (!ModifyIptables(IpFamily::Dual, "mangle",
274 {"-D", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
275 LOG(ERROR) << "Failed to detach " << kApplyLocalSourceMarkChain
276 << " from mangle OUTPUT";
277
Hugo Benichi2a940542020-10-26 18:50:49 +0900278 // Stops applying routing tags saved in conntrack for sockets created in the
279 // host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900280 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-D", "" /*iif*/,
281 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900282 LOG(ERROR) << "Failed to remove OUTPUT CONNMARK restore rule";
Hugo Benichi155de002021-01-19 16:45:46 +0900283 if (!ModifyConnmarkRestore(IpFamily::Dual, "POSTROUTING", "-D", "",
284 kFwmarkRoutingMask))
285 LOG(ERROR) << "Failed to remove POSTROUTING CONNMARK restore rule";
286
287 // Delete the POSTROUTING jump rule to check_routing_mark chain holding
288 // routing tag filter rules.
289 if (!ModifyIptables(IpFamily::Dual, "mangle",
290 {"-D", "POSTROUTING", "-m", "mark", "!", "--mark",
291 "0x0/" + kFwmarkRoutingMask.ToString(), "-j",
292 kCheckRoutingMarkChain, "-w"}))
293 LOG(ERROR) << "Failed to remove POSTROUTING jump rule to "
294 << kCheckRoutingMarkChain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900295
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900296 // Delete the mangle chains
Hugo Benichi155de002021-01-19 16:45:46 +0900297 for (const auto* chain : {kApplyLocalSourceMarkChain, kApplyVpnMarkChain,
298 kCheckRoutingMarkChain}) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900299 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", chain))
300 LOG(ERROR) << "Failed to flush " << chain << " mangle chain";
301
302 if (!ModifyChain(IpFamily::Dual, "mangle", "-X", chain))
303 LOG(ERROR) << "Failed to delete " << chain << " mangle chain";
304 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900305}
306
Hugo Benichi33860d72020-07-09 16:34:01 +0900307bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
308 // Try first to delete any netns with name |netns_name| in case patchpanel
309 // did not exit cleanly.
310 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
311 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
312 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
313}
314
315bool Datapath::NetnsDeleteName(const std::string& netns_name) {
316 return process_runner_->ip_netns_delete(netns_name) == 0;
317}
318
Garrick Evans8a949dc2019-07-18 16:17:53 +0900319bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900320 uint32_t ipv4_addr,
321 uint32_t ipv4_prefix_len) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900322 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900323 if (process_runner_->brctl("addbr", {ifname}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900324 return false;
325 }
326
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900327 if (process_runner_->ip(
328 "addr", "add",
329 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
330 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
331 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900332 RemoveBridge(ifname);
333 return false;
334 }
335
336 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900337 RemoveBridge(ifname);
338 return false;
339 }
340
341 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900342 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900343 RemoveBridge(ifname);
344 return false;
345 }
346
347 return true;
348}
349
350void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900351 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900352 process_runner_->ip("link", "set", {ifname, "down"});
Garrick Evans8e8e3472020-01-23 14:03:50 +0900353 process_runner_->brctl("delbr", {ifname});
Garrick Evans8a949dc2019-07-18 16:17:53 +0900354}
355
Garrick Evans621ed262019-11-13 12:28:43 +0900356bool Datapath::AddToBridge(const std::string& br_ifname,
357 const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900358 return (process_runner_->brctl("addif", {br_ifname, ifname}) == 0);
Garrick Evans621ed262019-11-13 12:28:43 +0900359}
360
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900361std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900362 const MacAddress* mac_addr,
363 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900364 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900365 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
366 if (!dev.is_valid()) {
367 PLOG(ERROR) << "Failed to open " << kTunDev;
368 return "";
369 }
370
371 struct ifreq ifr;
372 memset(&ifr, 0, sizeof(ifr));
373 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
374 sizeof(ifr.ifr_name));
375 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
376
377 // If a template was given as the name, ifr_name will be updated with the
378 // actual interface name.
379 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900380 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900381 return "";
382 }
383 const char* ifname = ifr.ifr_name;
384
385 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900386 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900387 return "";
388 }
389
Garrick Evans4f9f5572019-11-26 10:25:16 +0900390 if (!user.empty()) {
391 uid_t uid = -1;
392 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
393 PLOG(ERROR) << "Unable to look up UID for " << user;
394 RemoveTAP(ifname);
395 return "";
396 }
397 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
398 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
399 << ifname;
400 RemoveTAP(ifname);
401 return "";
402 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900403 }
404
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900405 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900406 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
407 if (!sock.is_valid()) {
408 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900409 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900410 RemoveTAP(ifname);
411 return "";
412 }
413
Garrick Evans621ed262019-11-13 12:28:43 +0900414 if (ipv4_addr) {
415 struct sockaddr_in* addr =
416 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
417 addr->sin_family = AF_INET;
418 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
419 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
420 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
421 << " {" << ipv4_addr->ToCidrString() << "}";
422 RemoveTAP(ifname);
423 return "";
424 }
425
426 struct sockaddr_in* netmask =
427 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
428 netmask->sin_family = AF_INET;
429 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
430 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
431 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
432 << " {" << ipv4_addr->ToCidrString() << "}";
433 RemoveTAP(ifname);
434 return "";
435 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900436 }
437
Garrick Evans621ed262019-11-13 12:28:43 +0900438 if (mac_addr) {
439 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
440 hwaddr->sa_family = ARPHRD_ETHER;
441 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
442 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
443 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
444 << " {" << MacAddressToString(*mac_addr) << "}";
445 RemoveTAP(ifname);
446 return "";
447 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900448 }
449
450 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900451 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900452 RemoveTAP(ifname);
453 return "";
454 }
455
456 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
457 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900458 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900459 RemoveTAP(ifname);
460 return "";
461 }
462
463 return ifname;
464}
465
466void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900467 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900468}
469
Hugo Benichi33860d72020-07-09 16:34:01 +0900470bool Datapath::ConnectVethPair(pid_t netns_pid,
471 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900472 const std::string& veth_ifname,
473 const std::string& peer_ifname,
474 const MacAddress& remote_mac_addr,
475 uint32_t remote_ipv4_addr,
476 uint32_t remote_ipv4_prefix_len,
477 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900478 // Set up the virtual pair across the current namespace and |netns_name|.
479 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
480 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
481 << peer_ifname;
482 return false;
483 }
484
485 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900486 {
Hugo Benichi33860d72020-07-09 16:34:01 +0900487 ScopedNS ns(netns_pid);
488 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900489 LOG(ERROR)
490 << "Cannot create virtual link -- invalid container namespace?";
491 return false;
492 }
493
Hugo Benichi76675592020-04-08 14:29:57 +0900494 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
495 remote_ipv4_prefix_len, true /* link up */,
496 remote_multicast_flag)) {
497 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
498 RemoveInterface(peer_ifname);
499 return false;
500 }
501 }
502
Hugo Benichi76675592020-04-08 14:29:57 +0900503 if (!ToggleInterface(veth_ifname, true /*up*/)) {
504 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
505 RemoveInterface(veth_ifname);
506 return false;
507 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900508
Hugo Benichi76675592020-04-08 14:29:57 +0900509 return true;
510}
511
Hugo Benichi33860d72020-07-09 16:34:01 +0900512bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
513 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900514 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900515 return process_runner_->ip("link", "add",
516 {veth_ifname, "type", "veth", "peer", "name",
517 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900518}
Garrick Evans54861622019-07-19 09:05:09 +0900519
Garrick Evans2470caa2020-03-04 14:15:41 +0900520bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
521 const std::string link = up ? "up" : "down";
522 return process_runner_->ip("link", "set", {ifname, link}) == 0;
523}
Garrick Evans54861622019-07-19 09:05:09 +0900524
Garrick Evans2470caa2020-03-04 14:15:41 +0900525bool Datapath::ConfigureInterface(const std::string& ifname,
526 const MacAddress& mac_addr,
527 uint32_t ipv4_addr,
528 uint32_t ipv4_prefix_len,
529 bool up,
530 bool enable_multicast) {
531 const std::string link = up ? "up" : "down";
532 const std::string multicast = enable_multicast ? "on" : "off";
533 return (process_runner_->ip(
534 "addr", "add",
535 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
536 IPv4AddressToString(
537 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
538 "dev", ifname}) == 0) &&
539 (process_runner_->ip("link", "set",
540 {
541 "dev",
542 ifname,
543 link,
544 "addr",
545 MacAddressToString(mac_addr),
546 "multicast",
547 multicast,
548 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900549}
550
551void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900552 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900553}
554
Hugo Benichi321f23b2020-09-25 15:42:05 +0900555bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
556 const std::string& src_ip) {
557 return process_runner_->iptables("filter", {"-I", "OUTPUT", "-o", oif, "-s",
558 src_ip, "-j", "DROP", "-w"}) == 0;
559}
560
561bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
562 const std::string& src_ip) {
563 return process_runner_->iptables("filter", {"-D", "OUTPUT", "-o", oif, "-s",
564 src_ip, "-j", "DROP", "-w"}) == 0;
565}
566
Hugo Benichifcf81022020-12-04 11:01:37 +0900567bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900568 // Veth interface configuration and client routing configuration:
569 // - attach a name to the client namespace.
570 // - create veth pair across the current namespace and the client namespace.
571 // - configure IPv4 address on remote veth inside client namespace.
572 // - configure IPv4 address on local veth inside host namespace.
573 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900574 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
575 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
576 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900577 return false;
578 }
579
Hugo Benichifcf81022020-12-04 11:01:37 +0900580 if (!ConnectVethPair(
581 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
582 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
583 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900584 LOG(ERROR) << "Failed to create veth pair for"
585 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900586 << nsinfo.pid;
587 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900588 return false;
589 }
590
Hugo Benichifcf81022020-12-04 11:01:37 +0900591 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
592 nsinfo.peer_subnet->AddressAtOffset(0),
593 nsinfo.peer_subnet->PrefixLength(),
594 true /* link up */, false /* enable_multicast */)) {
595 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
596 RemoveInterface(nsinfo.host_ifname);
597 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900598 return false;
599 }
600
601 {
Hugo Benichifcf81022020-12-04 11:01:37 +0900602 ScopedNS ns(nsinfo.pid);
603 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
604 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
605 RemoveInterface(nsinfo.host_ifname);
606 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900607 return false;
608 }
609
Hugo Benichifcf81022020-12-04 11:01:37 +0900610 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
611 INADDR_ANY)) {
612 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
613 << " inside namespace pid " << nsinfo.pid;
614 RemoveInterface(nsinfo.host_ifname);
615 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900616 return false;
617 }
618 }
619
620 // Host namespace routing configuration
621 // - ingress: add route to client subnet via |host_ifname|.
622 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
623 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
624 // Note that by default unsolicited ingress traffic is not forwarded to the
625 // client namespace unless the client specifically set port forwarding
626 // through permission_broker DBus APIs.
627 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
628 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900629 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
630 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
631 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900632 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900633 RemoveInterface(nsinfo.host_ifname);
634 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900635 return false;
636 }
637
Hugo Benichi7c342672020-09-08 09:18:14 +0900638 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900639 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900640 LOG(ERROR) << "Failed to set SNAT for traffic"
641 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900642 << nsinfo.host_ifname;
643 RemoveInterface(nsinfo.host_ifname);
644 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
645 nsinfo.peer_subnet->BaseAddress(), netmask);
646 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
647 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900648 return false;
649 }
650
Hugo Benichi93306e52020-12-04 16:08:00 +0900651 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
652 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
653 nsinfo.route_on_vpn);
654
Hugo Benichi7c342672020-09-08 09:18:14 +0900655 return true;
656}
657
Hugo Benichifcf81022020-12-04 11:01:37 +0900658void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900659 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
660 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
661 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900662 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900663 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
664 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
665 nsinfo.peer_subnet->BaseAddress(),
666 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
667 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900668}
669
Hugo Benichi8d622b52020-08-13 15:24:12 +0900670void Datapath::StartRoutingDevice(const std::string& ext_ifname,
671 const std::string& int_ifname,
672 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900673 TrafficSource source,
674 bool route_on_vpn) {
675 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900676 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900677 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
678 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
679 << "->" << int_ifname;
680
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900681 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900682 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
683 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900684
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900685 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900686 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
687 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900688
Hugo Benichi2a940542020-10-26 18:50:49 +0900689 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
690 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
691 << source << " for " << int_ifname;
692
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900693 if (!ext_ifname.empty()) {
694 // If |ext_ifname| is not null, mark egress traffic with the
695 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi2a940542020-10-26 18:50:49 +0900696 if (!ModifyFwmarkRoutingTag("PREROUTING", "-A", ext_ifname, int_ifname))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900697 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
698 << ext_ifname << "<-" << int_ifname;
699 } else {
700 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
701 // PREROUTING to apply any fwmark routing tag saved for the current
702 // connection, and rely on implicit routing to the default logical network
703 // otherwise.
Hugo Benichi1af52392020-11-27 18:09:32 +0900704 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname,
705 kFwmarkRoutingMask))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900706 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
707 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900708
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900709 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900710 // default network is eligible to be routed through a VPN if |route_on_vpn|
711 // is true.
712 if (route_on_vpn &&
713 !ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900714 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900715 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900716}
717
718void Datapath::StopRoutingDevice(const std::string& ext_ifname,
719 const std::string& int_ifname,
720 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900721 TrafficSource source,
722 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900723 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900724 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900725 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
726 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900727 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900728 if (!ext_ifname.empty()) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900729 ModifyFwmarkRoutingTag("PREROUTING", "-D", ext_ifname, int_ifname);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900730 } else {
Hugo Benichi1af52392020-11-27 18:09:32 +0900731 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname,
732 kFwmarkRoutingMask);
Hugo Benichi93306e52020-12-04 16:08:00 +0900733 if (route_on_vpn)
734 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900735 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900736}
737
Garrick Evansf0ab7132019-06-18 14:50:42 +0900738bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
739 const std::string& ipv4_addr) {
740 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900741 if (process_runner_->iptables(
742 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
743 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900744 return false;
745
746 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900747 if (process_runner_->iptables(
748 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
749 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900750 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
751 return false;
752 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900753 if (process_runner_->iptables(
754 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
755 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900756 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
757 return false;
758 }
759
760 return true;
761}
762
763void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
764 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900765 process_runner_->iptables(
766 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
767 "--to-destination", ipv4_addr, "-w"});
768 process_runner_->iptables(
769 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
770 "--to-destination", ipv4_addr, "-w"});
771 process_runner_->iptables(
772 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
773 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900774}
775
Hugo Benichie8758b52020-04-03 14:49:01 +0900776bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
777 return process_runner_->iptables(
778 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900779 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900780}
781
782void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
783 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900784 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900785}
786
Garrick Evans664a82f2019-12-17 12:18:05 +0900787bool Datapath::MaskInterfaceFlags(const std::string& ifname,
788 uint16_t on,
789 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900790 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
791 if (!sock.is_valid()) {
792 PLOG(ERROR) << "Failed to create control socket";
793 return false;
794 }
795 ifreq ifr;
796 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
797 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
798 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
799 return false;
800 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900801 ifr.ifr_flags |= on;
802 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900803 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900804 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
805 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900806 return false;
807 }
808 return true;
809}
810
Garrick Evans260ff302019-07-25 11:22:50 +0900811bool Datapath::AddIPv6HostRoute(const std::string& ifname,
812 const std::string& ipv6_addr,
813 int ipv6_prefix_len) {
814 std::string ipv6_addr_cidr =
815 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
816
Garrick Evans8e8e3472020-01-23 14:03:50 +0900817 return process_runner_->ip6("route", "replace",
818 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900819}
820
821void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
822 const std::string& ipv6_addr,
823 int ipv6_prefix_len) {
824 std::string ipv6_addr_cidr =
825 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
826
Garrick Evans8e8e3472020-01-23 14:03:50 +0900827 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900828}
829
Taoyu Lia0727dc2020-09-24 19:54:59 +0900830bool Datapath::AddIPv6Address(const std::string& ifname,
831 const std::string& ipv6_addr) {
832 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900833}
834
Taoyu Lia0727dc2020-09-24 19:54:59 +0900835void Datapath::RemoveIPv6Address(const std::string& ifname,
836 const std::string& ipv6_addr) {
837 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900838}
839
Hugo Benichi76be34a2020-08-26 22:35:54 +0900840void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900841 int ifindex = FindIfIndex(ext_ifname);
842 if (ifindex != 0 && !ModifyIptables(IpFamily::Dual, "mangle",
843 {"-A", kCheckRoutingMarkChain, "-o",
844 ext_ifname, "-m", "mark", "!", "--mark",
845 Fwmark::FromIfIndex(ifindex).ToString() +
846 "/" + kFwmarkRoutingMask.ToString(),
847 "-j", "DROP", "-w"}))
848 LOG(ERROR) << "Could not set fwmark routing filter rule for " << ext_ifname;
849
Hugo Benichi1af52392020-11-27 18:09:32 +0900850 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi76be34a2020-08-26 22:35:54 +0900851 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
852 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900853 // Save in CONNMARK the source tag for egress traffic of this connection.
854 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
855 kFwmarkAllSourcesMask))
856 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
857 "source tag on "
858 << ext_ifname;
859 // Restore from CONNMARK the source tag for ingress traffic of this connection
860 // (returned traffic).
861 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
862 kFwmarkAllSourcesMask))
863 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
864 "traffic received on "
865 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900866}
867
868void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900869 int ifindex = FindIfIndex(ext_ifname);
870 if (ifindex != 0 && !ModifyIptables(IpFamily::Dual, "mangle",
871 {"-D", kCheckRoutingMarkChain, "-o",
872 ext_ifname, "-m", "mark", "!", "--mark",
873 Fwmark::FromIfIndex(ifindex).ToString() +
874 "/" + kFwmarkRoutingMask.ToString(),
875 "-j", "DROP", "-w"}))
876 LOG(ERROR) << "Could not remove fwmark routing filter rule for "
877 << ext_ifname;
878
Hugo Benichi76be34a2020-08-26 22:35:54 +0900879 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
880 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900881 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
882 kFwmarkAllSourcesMask))
883 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
884 "fwmark source tag on "
885 << ext_ifname;
886 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
887 kFwmarkAllSourcesMask))
888 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
889 "traffic received on "
890 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900891}
892
Hugo Benichi2a940542020-10-26 18:50:49 +0900893void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi891275e2020-12-16 10:35:34 +0900894 if (process_runner_->iptables("nat", {"-A", "POSTROUTING", "-o", vpn_ifname,
895 "-j", "MASQUERADE", "-w"}) != 0)
896 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900897 StartConnectionPinning(vpn_ifname);
898 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", vpn_ifname, ""))
899 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +0900900 if (vpn_ifname != kArcBridge)
901 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
902 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi2a940542020-10-26 18:50:49 +0900903}
904
905void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900906 if (vpn_ifname != kArcBridge)
907 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
908 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi2a940542020-10-26 18:50:49 +0900909 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", vpn_ifname, ""))
910 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
911 StopConnectionPinning(vpn_ifname);
Hugo Benichi891275e2020-12-16 10:35:34 +0900912 if (process_runner_->iptables("nat", {"-D", "POSTROUTING", "-o", vpn_ifname,
913 "-j", "MASQUERADE", "-w"}) != 0)
914 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900915}
916
Hugo Benichi76be34a2020-08-26 22:35:54 +0900917bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
918 const std::string& op,
919 const std::string& oif) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900920 int ifindex = FindIfIndex(oif);
921 if (ifindex == 0) {
922 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
923 return false;
924 }
925
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900926 return ModifyConnmarkSet(family, "POSTROUTING", op, oif,
927 Fwmark::FromIfIndex(ifindex), kFwmarkRoutingMask);
928}
929
930bool Datapath::ModifyConnmarkSet(IpFamily family,
931 const std::string& chain,
932 const std::string& op,
933 const std::string& oif,
934 Fwmark mark,
935 Fwmark mask) {
936 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
937 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
938 return false;
939 }
940
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900941 std::vector<std::string> args = {op, chain};
942 if (!oif.empty()) {
943 args.push_back("-o");
944 args.push_back(oif);
945 }
946 args.push_back("-j");
947 args.push_back("CONNMARK");
948 args.push_back("--set-mark");
949 args.push_back(mark.ToString() + "/" + mask.ToString());
950 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +0900951
Hugo Benichi58f264a2020-10-16 18:16:05 +0900952 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +0900953}
954
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900955bool Datapath::ModifyConnmarkRestore(IpFamily family,
956 const std::string& chain,
957 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +0900958 const std::string& iif,
959 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900960 std::vector<std::string> args = {op, chain};
961 if (!iif.empty()) {
962 args.push_back("-i");
963 args.push_back(iif);
964 }
965 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +0900966 mask.ToString(), "-w"});
967 return ModifyIptables(family, "mangle", args);
968}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900969
Hugo Benichi1af52392020-11-27 18:09:32 +0900970bool Datapath::ModifyConnmarkSave(IpFamily family,
971 const std::string& chain,
972 const std::string& op,
973 const std::string& oif,
974 Fwmark mask) {
975 std::vector<std::string> args = {op, chain};
976 if (!oif.empty()) {
977 args.push_back("-o");
978 args.push_back(oif);
979 }
980 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
981 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +0900982 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900983}
984
Hugo Benichi2a940542020-10-26 18:50:49 +0900985bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
986 const std::string& op,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900987 const std::string& ext_ifname,
988 const std::string& int_ifname) {
989 int ifindex = FindIfIndex(ext_ifname);
990 if (ifindex == 0) {
991 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
992 return false;
993 }
994
Hugo Benichi2a940542020-10-26 18:50:49 +0900995 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +0900996 0 /*classid*/, Fwmark::FromIfIndex(ifindex),
997 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900998}
999
Hugo Benichi9be19b12020-08-14 15:33:40 +09001000bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
1001 const std::string& iif,
1002 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001003 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001004 0 /*classid*/, Fwmark::FromSource(source),
1005 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001006}
1007
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001008bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1009 TrafficSource source) {
1010 std::vector<std::string> args = {"-A",
1011 kApplyLocalSourceMarkChain,
1012 "-m",
1013 "mark",
1014 "--mark",
1015 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1016 "-j",
1017 "MARK",
1018 "--set-mark",
1019 Fwmark::FromSource(source).ToString() + "/" +
1020 kFwmarkAllSourcesMask.ToString(),
1021 "-w"};
1022 return ModifyIptables(IpFamily::Dual, "mangle", args);
1023}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001024
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001025bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1026 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001027 if (std::string(source.uid_name).empty() && source.classid == 0)
1028 return false;
1029
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001030 Fwmark mark = Fwmark::FromSource(source.source_type);
1031 if (source.is_on_vpn)
1032 mark = mark | kFwmarkRouteOnVpn;
1033
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001034 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1035 "" /*iif*/, source.uid_name, source.classid, mark,
1036 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001037}
1038
1039bool Datapath::ModifyFwmark(IpFamily family,
1040 const std::string& chain,
1041 const std::string& op,
1042 const std::string& iif,
1043 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001044 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001045 Fwmark mark,
1046 Fwmark mask,
1047 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001048 std::vector<std::string> args = {op, chain};
1049 if (!iif.empty()) {
1050 args.push_back("-i");
1051 args.push_back(iif);
1052 }
1053 if (!uid_name.empty()) {
1054 args.push_back("-m");
1055 args.push_back("owner");
1056 args.push_back("--uid-owner");
1057 args.push_back(uid_name);
1058 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001059 if (classid != 0) {
1060 args.push_back("-m");
1061 args.push_back("cgroup");
1062 args.push_back("--cgroup");
1063 args.push_back(base::StringPrintf("0x%08x", classid));
1064 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001065 args.push_back("-j");
1066 args.push_back("MARK");
1067 args.push_back("--set-mark");
1068 args.push_back(mark.ToString() + "/" + mask.ToString());
1069 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001070
Hugo Benichi58f264a2020-10-16 18:16:05 +09001071 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001072}
1073
Hugo Benichid82d8832020-08-14 10:05:03 +09001074bool Datapath::ModifyIpForwarding(IpFamily family,
1075 const std::string& op,
1076 const std::string& iif,
1077 const std::string& oif,
1078 bool log_failures) {
1079 if (iif.empty() && oif.empty()) {
1080 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1081 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001082 return false;
1083 }
1084
Hugo Benichid82d8832020-08-14 10:05:03 +09001085 std::vector<std::string> args = {op, "FORWARD"};
1086 if (!iif.empty()) {
1087 args.push_back("-i");
1088 args.push_back(iif);
1089 }
1090 if (!oif.empty()) {
1091 args.push_back("-o");
1092 args.push_back(oif);
1093 }
1094 args.push_back("-j");
1095 args.push_back("ACCEPT");
1096 args.push_back("-w");
1097
Hugo Benichi58f264a2020-10-16 18:16:05 +09001098 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001099}
1100
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001101bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1102 const std::string& op,
1103 const std::string& iif,
1104 Fwmark mark,
1105 Fwmark mask) {
1106 std::vector<std::string> args = {op, chain};
1107 if (!iif.empty()) {
1108 args.push_back("-i");
1109 args.push_back(iif);
1110 }
1111 if (mark.Value() != 0 && mask.Value() != 0) {
1112 args.push_back("-m");
1113 args.push_back("mark");
1114 args.push_back("--mark");
1115 args.push_back(mark.ToString() + "/" + mask.ToString());
1116 }
1117 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1118 return ModifyIptables(IpFamily::Dual, "mangle", args);
1119}
1120
1121bool Datapath::ModifyChain(IpFamily family,
1122 const std::string& table,
1123 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001124 const std::string& chain,
1125 bool log_failures) {
1126 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001127}
1128
1129bool Datapath::ModifyIptables(IpFamily family,
1130 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001131 const std::vector<std::string>& argv,
1132 bool log_failures) {
1133 switch (family) {
1134 case IPv4:
1135 case IPv6:
1136 case Dual:
1137 break;
1138 default:
1139 LOG(ERROR) << "Could not execute iptables command " << table
1140 << base::JoinString(argv, " ") << ": incorrect IP family "
1141 << family;
1142 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001143 }
1144
1145 bool success = true;
1146 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001147 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001148 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001149 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001150 return success;
1151}
1152
Hugo Benichid82d8832020-08-14 10:05:03 +09001153bool Datapath::StartIpForwarding(IpFamily family,
1154 const std::string& iif,
1155 const std::string& oif) {
1156 return ModifyIpForwarding(family, "-A", iif, oif);
1157}
1158
1159bool Datapath::StopIpForwarding(IpFamily family,
1160 const std::string& iif,
1161 const std::string& oif) {
1162 return ModifyIpForwarding(family, "-D", iif, oif);
1163}
1164
1165bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1166 const std::string& ifname2) {
1167 // Only start Ipv6 forwarding if -C returns false and it had not been
1168 // started yet.
1169 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1170 false /*log_failures*/) &&
1171 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1172 return false;
1173 }
1174
1175 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1176 false /*log_failures*/) &&
1177 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001178 RemoveIPv6Forwarding(ifname1, ifname2);
1179 return false;
1180 }
1181
1182 return true;
1183}
1184
1185void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1186 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001187 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1188 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001189}
1190
Garrick Evans3d97a392020-02-21 15:24:37 +09001191bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1192 uint32_t addr,
1193 uint32_t netmask) {
1194 struct rtentry route;
1195 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001196 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1197 SetSockaddrIn(&route.rt_dst, addr & netmask);
1198 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001199 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001200 return ModifyRtentry(SIOCADDRT, &route);
1201}
Garrick Evans3d97a392020-02-21 15:24:37 +09001202
Hugo Benichie8758b52020-04-03 14:49:01 +09001203bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1204 uint32_t addr,
1205 uint32_t netmask) {
1206 struct rtentry route;
1207 memset(&route, 0, sizeof(route));
1208 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1209 SetSockaddrIn(&route.rt_dst, addr & netmask);
1210 SetSockaddrIn(&route.rt_genmask, netmask);
1211 route.rt_flags = RTF_UP | RTF_GATEWAY;
1212 return ModifyRtentry(SIOCDELRT, &route);
1213}
1214
1215bool Datapath::AddIPv4Route(const std::string& ifname,
1216 uint32_t addr,
1217 uint32_t netmask) {
1218 struct rtentry route;
1219 memset(&route, 0, sizeof(route));
1220 SetSockaddrIn(&route.rt_dst, addr & netmask);
1221 SetSockaddrIn(&route.rt_genmask, netmask);
1222 char rt_dev[IFNAMSIZ];
1223 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1224 rt_dev[IFNAMSIZ - 1] = '\0';
1225 route.rt_dev = rt_dev;
1226 route.rt_flags = RTF_UP | RTF_GATEWAY;
1227 return ModifyRtentry(SIOCADDRT, &route);
1228}
1229
1230bool Datapath::DeleteIPv4Route(const std::string& ifname,
1231 uint32_t addr,
1232 uint32_t netmask) {
1233 struct rtentry route;
1234 memset(&route, 0, sizeof(route));
1235 SetSockaddrIn(&route.rt_dst, addr & netmask);
1236 SetSockaddrIn(&route.rt_genmask, netmask);
1237 char rt_dev[IFNAMSIZ];
1238 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1239 rt_dev[IFNAMSIZ - 1] = '\0';
1240 route.rt_dev = rt_dev;
1241 route.rt_flags = RTF_UP | RTF_GATEWAY;
1242 return ModifyRtentry(SIOCDELRT, &route);
1243}
1244
Taoyu Lia0727dc2020-09-24 19:54:59 +09001245bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001246 DCHECK(route);
1247 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001248 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001249 return false;
1250 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001251 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1252 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001253 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001254 return false;
1255 }
1256 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1257 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001258 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001259 return false;
1260 }
1261 return true;
1262}
1263
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001264bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1265 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1266 kArcAddr, kAdbServerPort, ifname,
1267 kLocalhostAddr, kAdbProxyTcpListenPort);
1268}
1269
1270void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1271 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1272 kArcAddr, kAdbServerPort, ifname,
1273 kLocalhostAddr, kAdbProxyTcpListenPort);
1274}
1275
1276bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1277 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1278 kAdbProxyTcpListenPort, ifname);
1279}
1280
1281void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1282 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1283 kAdbProxyTcpListenPort, ifname);
1284}
1285
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001286void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1287 if_nametoindex_[ifname] = ifindex;
1288}
1289
1290int Datapath::FindIfIndex(const std::string& ifname) {
1291 uint32_t ifindex = if_nametoindex(ifname.c_str());
1292 if (ifindex > 0) {
1293 if_nametoindex_[ifname] = ifindex;
1294 return ifindex;
1295 }
1296
1297 const auto it = if_nametoindex_.find(ifname);
1298 if (it != if_nametoindex_.end())
1299 return it->second;
1300
1301 return 0;
1302}
1303
Hugo Benichifcf81022020-12-04 11:01:37 +09001304std::ostream& operator<<(std::ostream& stream,
1305 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001306 stream << "{ pid: " << nsinfo.pid
1307 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001308 if (!nsinfo.outbound_ifname.empty()) {
1309 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1310 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001311 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1312 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001313 << ", peer_ifname: " << nsinfo.peer_ifname
1314 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1315 return stream;
1316}
1317
Garrick Evans3388a032020-03-24 11:25:55 +09001318} // namespace patchpanel