blob: 683fbc142c2007a23e8850f69498fe0cffe86495 [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
Hugo Benichi2a940542020-10-26 18:50:49 +0900148 // Applies the routing tag saved in conntrack for any established connection
149 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900150 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
151 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900152 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
Hugo Benichi155de002021-01-19 16:45:46 +0900153 // b/177787823 Also restore the routing tag after routing has taken place so
154 // that packets pre-tagged with the VPN routing tag are in sync with their
155 // associated CONNMARK routing tag. This is necessary to correctly identify
156 // packets exiting through the wrong interface.
157 if (!ModifyConnmarkRestore(IpFamily::Dual, "POSTROUTING", "-A", "" /*iif*/,
158 kFwmarkRoutingMask))
159 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK restore rule";
Hugo Benichi2a940542020-10-26 18:50:49 +0900160
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900161 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
162 // tag and tagging the local traffic that should be routed through a VPN.
163 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyLocalSourceMarkChain))
164 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
165 << " mangle chain";
166 // Ensure that the chain is empty if patchpanel is restarting after a crash.
167 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyLocalSourceMarkChain))
168 LOG(ERROR) << "Failed to flush " << kApplyLocalSourceMarkChain
169 << " mangle chain";
170 if (!ModifyIptables(IpFamily::Dual, "mangle",
171 {"-A", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
172 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
173 << " to mangle OUTPUT";
174 // Create rules for tagging local sources with the source tag and the vpn
175 // policy tag.
176 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900177 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900178 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
179 << " in " << kApplyLocalSourceMarkChain;
180 }
181 // Finally add a catch-all rule for tagging any remaining local sources with
182 // the SYSTEM source tag
183 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
184 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
185
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900186 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
187 // traffic that should be routed through a VPN.
188 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyVpnMarkChain))
189 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
190 // Ensure that the chain is empty if patchpanel is restarting after a crash.
191 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kApplyVpnMarkChain))
192 LOG(ERROR) << "Failed to flush " << kApplyVpnMarkChain << " mangle chain";
193 // All local outgoing traffic eligible to VPN routing should traverse the VPN
194 // marking chain.
195 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", "" /*iif*/, kFwmarkRouteOnVpn,
196 kFwmarkVpnMask))
197 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
198 // Any traffic that already has a routing tag applied is accepted.
199 if (!ModifyIptables(
200 IpFamily::Dual, "mangle",
201 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
202 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
203 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
204 "connections";
Hugo Benichi155de002021-01-19 16:45:46 +0900205
206 // Sets up a mangle chain used in POSTROUTING for checking consistency between
207 // the routing tag and the output interface.
208 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kCheckRoutingMarkChain))
209 LOG(ERROR) << "Failed to set up " << kCheckRoutingMarkChain
210 << " mangle chain";
211 // Ensure that the chain is empty if patchpanel is restarting after a crash.
212 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", kCheckRoutingMarkChain))
213 LOG(ERROR) << "Failed to flush " << kCheckRoutingMarkChain
214 << " mangle chain";
215
216 // b/177787823 If it already exists, the routing tag of any traffic exiting an
217 // interface (physical or VPN) must match the routing tag of that interface.
218 if (!ModifyIptables(IpFamily::Dual, "mangle",
219 {"-A", "POSTROUTING", "-m", "mark", "!", "--mark",
220 "0x0/" + kFwmarkRoutingMask.ToString(), "-j",
221 kCheckRoutingMarkChain, "-w"}))
222 LOG(ERROR) << "Failed to add POSTROUTING jump rule to "
223 << kCheckRoutingMarkChain;
Hugo Benichi52a64992021-01-28 17:47:33 +0900224
225 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
226 // incorrectly cause neighbor discovery icmpv6 packets to be dropped. Add
227 // these rules to bypass connmark rule for those packets.
228 for (const auto& type : kNeighborDiscoveryTypes) {
229 if (!ModifyIptables(IpFamily::IPv6, "mangle",
230 {"-I", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
231 "-j", "ACCEPT", "-w"}))
232 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
233 << " packets in OUTPUT";
234 if (!ModifyIptables(IpFamily::IPv6, "mangle",
235 {"-I", kCheckRoutingMarkChain, "-p", "icmpv6",
236 "--icmpv6-type", type, "-j", "RETURN", "-w"}))
237 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
238 << " packets in " << kCheckRoutingMarkChain;
239 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900240}
241
242void Datapath::Stop() {
Hugo Benichi561fae42021-01-22 15:28:40 +0900243 // Remove static IPv4 SNAT rules.
Hugo Benichibf811c62020-09-07 17:30:45 +0900244 RemoveOutboundIPv4SNATMark("vmtap+");
Hugo Benichi58125d32020-09-09 11:25:45 +0900245 process_runner_->iptables("filter",
246 {"-D", "FORWARD", "-m", "state", "--state",
247 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"});
Hugo Benichi561fae42021-01-22 15:28:40 +0900248 process_runner_->iptables("nat", {"-D", "POSTROUTING", "-m", "mark", "--mark",
249 "1/1", "-j", "MASQUERADE", "-w"});
250 process_runner_->iptables(
251 "filter", {"-D", "FORWARD", "-m", "mark", "--mark", "1/1", "-m", "state",
252 "--state", "INVALID", "-j", "DROP", "-w"});
253
Hugo Benichibf811c62020-09-07 17:30:45 +0900254 for (const auto& oif : kPhysicalIfnamePrefixes)
255 RemoveSourceIPv4DropRule(oif, kGuestIPv4Subnet);
256
257 // Restore original local port range.
258 // TODO(garrick): The original history behind this tweak is gone. Some
259 // investigation is needed to see if it is still applicable.
260 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
261 "32768 61000") != 0)
262 LOG(ERROR) << "Failed to restore local port range";
263
264 // Disable packet forwarding
265 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
266 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
267
268 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
269 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900270
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900271 // Detach the VPN marking mangle chain
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900272 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-D", "" /*iif*/, kFwmarkRouteOnVpn,
273 kFwmarkVpnMask))
274 LOG(ERROR)
275 << "Failed to remove from mangle OUTPUT chain jump rule to VPN chain";
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900276
277 // Detach apply_local_source_mark from mangle PREROUTING
278 if (!ModifyIptables(IpFamily::Dual, "mangle",
279 {"-D", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
280 LOG(ERROR) << "Failed to detach " << kApplyLocalSourceMarkChain
281 << " from mangle OUTPUT";
282
Hugo Benichi2a940542020-10-26 18:50:49 +0900283 // Stops applying routing tags saved in conntrack for sockets created in the
284 // host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900285 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-D", "" /*iif*/,
286 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900287 LOG(ERROR) << "Failed to remove OUTPUT CONNMARK restore rule";
Hugo Benichi155de002021-01-19 16:45:46 +0900288 if (!ModifyConnmarkRestore(IpFamily::Dual, "POSTROUTING", "-D", "",
289 kFwmarkRoutingMask))
290 LOG(ERROR) << "Failed to remove POSTROUTING CONNMARK restore rule";
291
292 // Delete the POSTROUTING jump rule to check_routing_mark chain holding
293 // routing tag filter rules.
294 if (!ModifyIptables(IpFamily::Dual, "mangle",
295 {"-D", "POSTROUTING", "-m", "mark", "!", "--mark",
296 "0x0/" + kFwmarkRoutingMask.ToString(), "-j",
297 kCheckRoutingMarkChain, "-w"}))
298 LOG(ERROR) << "Failed to remove POSTROUTING jump rule to "
299 << kCheckRoutingMarkChain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900300
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900301 // Delete the mangle chains
Hugo Benichi155de002021-01-19 16:45:46 +0900302 for (const auto* chain : {kApplyLocalSourceMarkChain, kApplyVpnMarkChain,
303 kCheckRoutingMarkChain}) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900304 if (!ModifyChain(IpFamily::Dual, "mangle", "-F", chain))
305 LOG(ERROR) << "Failed to flush " << chain << " mangle chain";
306
307 if (!ModifyChain(IpFamily::Dual, "mangle", "-X", chain))
308 LOG(ERROR) << "Failed to delete " << chain << " mangle chain";
309 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900310}
311
Hugo Benichi33860d72020-07-09 16:34:01 +0900312bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
313 // Try first to delete any netns with name |netns_name| in case patchpanel
314 // did not exit cleanly.
315 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
316 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
317 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
318}
319
320bool Datapath::NetnsDeleteName(const std::string& netns_name) {
321 return process_runner_->ip_netns_delete(netns_name) == 0;
322}
323
Garrick Evans8a949dc2019-07-18 16:17:53 +0900324bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900325 uint32_t ipv4_addr,
326 uint32_t ipv4_prefix_len) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900327 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900328 if (process_runner_->brctl("addbr", {ifname}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900329 return false;
330 }
331
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900332 if (process_runner_->ip(
333 "addr", "add",
334 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
335 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
336 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900337 RemoveBridge(ifname);
338 return false;
339 }
340
341 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900342 RemoveBridge(ifname);
343 return false;
344 }
345
346 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900347 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900348 RemoveBridge(ifname);
349 return false;
350 }
351
352 return true;
353}
354
355void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900356 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900357 process_runner_->ip("link", "set", {ifname, "down"});
Garrick Evans8e8e3472020-01-23 14:03:50 +0900358 process_runner_->brctl("delbr", {ifname});
Garrick Evans8a949dc2019-07-18 16:17:53 +0900359}
360
Garrick Evans621ed262019-11-13 12:28:43 +0900361bool Datapath::AddToBridge(const std::string& br_ifname,
362 const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900363 return (process_runner_->brctl("addif", {br_ifname, ifname}) == 0);
Garrick Evans621ed262019-11-13 12:28:43 +0900364}
365
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900366std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900367 const MacAddress* mac_addr,
368 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900369 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900370 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
371 if (!dev.is_valid()) {
372 PLOG(ERROR) << "Failed to open " << kTunDev;
373 return "";
374 }
375
376 struct ifreq ifr;
377 memset(&ifr, 0, sizeof(ifr));
378 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
379 sizeof(ifr.ifr_name));
380 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
381
382 // If a template was given as the name, ifr_name will be updated with the
383 // actual interface name.
384 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900385 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900386 return "";
387 }
388 const char* ifname = ifr.ifr_name;
389
390 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900391 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900392 return "";
393 }
394
Garrick Evans4f9f5572019-11-26 10:25:16 +0900395 if (!user.empty()) {
396 uid_t uid = -1;
397 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
398 PLOG(ERROR) << "Unable to look up UID for " << user;
399 RemoveTAP(ifname);
400 return "";
401 }
402 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
403 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
404 << ifname;
405 RemoveTAP(ifname);
406 return "";
407 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900408 }
409
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900410 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900411 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
412 if (!sock.is_valid()) {
413 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900414 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900415 RemoveTAP(ifname);
416 return "";
417 }
418
Garrick Evans621ed262019-11-13 12:28:43 +0900419 if (ipv4_addr) {
420 struct sockaddr_in* addr =
421 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
422 addr->sin_family = AF_INET;
423 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
424 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
425 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
426 << " {" << ipv4_addr->ToCidrString() << "}";
427 RemoveTAP(ifname);
428 return "";
429 }
430
431 struct sockaddr_in* netmask =
432 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
433 netmask->sin_family = AF_INET;
434 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
435 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
436 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
437 << " {" << ipv4_addr->ToCidrString() << "}";
438 RemoveTAP(ifname);
439 return "";
440 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900441 }
442
Garrick Evans621ed262019-11-13 12:28:43 +0900443 if (mac_addr) {
444 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
445 hwaddr->sa_family = ARPHRD_ETHER;
446 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
447 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
448 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
449 << " {" << MacAddressToString(*mac_addr) << "}";
450 RemoveTAP(ifname);
451 return "";
452 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900453 }
454
455 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900456 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900457 RemoveTAP(ifname);
458 return "";
459 }
460
461 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
462 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900463 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900464 RemoveTAP(ifname);
465 return "";
466 }
467
468 return ifname;
469}
470
471void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900472 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900473}
474
Hugo Benichi33860d72020-07-09 16:34:01 +0900475bool Datapath::ConnectVethPair(pid_t netns_pid,
476 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900477 const std::string& veth_ifname,
478 const std::string& peer_ifname,
479 const MacAddress& remote_mac_addr,
480 uint32_t remote_ipv4_addr,
481 uint32_t remote_ipv4_prefix_len,
482 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900483 // Set up the virtual pair across the current namespace and |netns_name|.
484 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
485 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
486 << peer_ifname;
487 return false;
488 }
489
490 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900491 {
Hugo Benichi33860d72020-07-09 16:34:01 +0900492 ScopedNS ns(netns_pid);
493 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900494 LOG(ERROR)
495 << "Cannot create virtual link -- invalid container namespace?";
496 return false;
497 }
498
Hugo Benichi76675592020-04-08 14:29:57 +0900499 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
500 remote_ipv4_prefix_len, true /* link up */,
501 remote_multicast_flag)) {
502 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
503 RemoveInterface(peer_ifname);
504 return false;
505 }
506 }
507
Hugo Benichi76675592020-04-08 14:29:57 +0900508 if (!ToggleInterface(veth_ifname, true /*up*/)) {
509 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
510 RemoveInterface(veth_ifname);
511 return false;
512 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900513
Hugo Benichi76675592020-04-08 14:29:57 +0900514 return true;
515}
516
Hugo Benichi33860d72020-07-09 16:34:01 +0900517bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
518 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900519 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900520 return process_runner_->ip("link", "add",
521 {veth_ifname, "type", "veth", "peer", "name",
522 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900523}
Garrick Evans54861622019-07-19 09:05:09 +0900524
Garrick Evans2470caa2020-03-04 14:15:41 +0900525bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
526 const std::string link = up ? "up" : "down";
527 return process_runner_->ip("link", "set", {ifname, link}) == 0;
528}
Garrick Evans54861622019-07-19 09:05:09 +0900529
Garrick Evans2470caa2020-03-04 14:15:41 +0900530bool Datapath::ConfigureInterface(const std::string& ifname,
531 const MacAddress& mac_addr,
532 uint32_t ipv4_addr,
533 uint32_t ipv4_prefix_len,
534 bool up,
535 bool enable_multicast) {
536 const std::string link = up ? "up" : "down";
537 const std::string multicast = enable_multicast ? "on" : "off";
538 return (process_runner_->ip(
539 "addr", "add",
540 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
541 IPv4AddressToString(
542 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
543 "dev", ifname}) == 0) &&
544 (process_runner_->ip("link", "set",
545 {
546 "dev",
547 ifname,
548 link,
549 "addr",
550 MacAddressToString(mac_addr),
551 "multicast",
552 multicast,
553 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900554}
555
556void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900557 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900558}
559
Hugo Benichi321f23b2020-09-25 15:42:05 +0900560bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
561 const std::string& src_ip) {
562 return process_runner_->iptables("filter", {"-I", "OUTPUT", "-o", oif, "-s",
563 src_ip, "-j", "DROP", "-w"}) == 0;
564}
565
566bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
567 const std::string& src_ip) {
568 return process_runner_->iptables("filter", {"-D", "OUTPUT", "-o", oif, "-s",
569 src_ip, "-j", "DROP", "-w"}) == 0;
570}
571
Hugo Benichifcf81022020-12-04 11:01:37 +0900572bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900573 // Veth interface configuration and client routing configuration:
574 // - attach a name to the client namespace.
575 // - create veth pair across the current namespace and the client namespace.
576 // - configure IPv4 address on remote veth inside client namespace.
577 // - configure IPv4 address on local veth inside host namespace.
578 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900579 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
580 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
581 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900582 return false;
583 }
584
Hugo Benichifcf81022020-12-04 11:01:37 +0900585 if (!ConnectVethPair(
586 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
587 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
588 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900589 LOG(ERROR) << "Failed to create veth pair for"
590 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900591 << nsinfo.pid;
592 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900593 return false;
594 }
595
Hugo Benichifcf81022020-12-04 11:01:37 +0900596 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
597 nsinfo.peer_subnet->AddressAtOffset(0),
598 nsinfo.peer_subnet->PrefixLength(),
599 true /* link up */, false /* enable_multicast */)) {
600 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
601 RemoveInterface(nsinfo.host_ifname);
602 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900603 return false;
604 }
605
606 {
Hugo Benichifcf81022020-12-04 11:01:37 +0900607 ScopedNS ns(nsinfo.pid);
608 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
609 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
610 RemoveInterface(nsinfo.host_ifname);
611 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900612 return false;
613 }
614
Hugo Benichifcf81022020-12-04 11:01:37 +0900615 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
616 INADDR_ANY)) {
617 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
618 << " inside namespace pid " << nsinfo.pid;
619 RemoveInterface(nsinfo.host_ifname);
620 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900621 return false;
622 }
623 }
624
625 // Host namespace routing configuration
626 // - ingress: add route to client subnet via |host_ifname|.
627 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
628 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
629 // Note that by default unsolicited ingress traffic is not forwarded to the
630 // client namespace unless the client specifically set port forwarding
631 // through permission_broker DBus APIs.
632 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
633 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900634 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
635 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
636 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900637 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900638 RemoveInterface(nsinfo.host_ifname);
639 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900640 return false;
641 }
642
Hugo Benichi7c342672020-09-08 09:18:14 +0900643 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900644 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900645 LOG(ERROR) << "Failed to set SNAT for traffic"
646 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900647 << nsinfo.host_ifname;
648 RemoveInterface(nsinfo.host_ifname);
649 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
650 nsinfo.peer_subnet->BaseAddress(), netmask);
651 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
652 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900653 return false;
654 }
655
Hugo Benichi93306e52020-12-04 16:08:00 +0900656 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
657 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
658 nsinfo.route_on_vpn);
659
Hugo Benichi7c342672020-09-08 09:18:14 +0900660 return true;
661}
662
Hugo Benichifcf81022020-12-04 11:01:37 +0900663void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900664 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
665 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
666 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900667 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900668 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
669 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
670 nsinfo.peer_subnet->BaseAddress(),
671 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
672 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900673}
674
Hugo Benichi8d622b52020-08-13 15:24:12 +0900675void Datapath::StartRoutingDevice(const std::string& ext_ifname,
676 const std::string& int_ifname,
677 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900678 TrafficSource source,
679 bool route_on_vpn) {
680 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900681 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900682 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
683 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
684 << "->" << int_ifname;
685
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900686 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900687 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
688 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900689
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900690 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900691 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
692 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900693
Hugo Benichi2a940542020-10-26 18:50:49 +0900694 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
695 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
696 << source << " for " << int_ifname;
697
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900698 if (!ext_ifname.empty()) {
699 // If |ext_ifname| is not null, mark egress traffic with the
700 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi2a940542020-10-26 18:50:49 +0900701 if (!ModifyFwmarkRoutingTag("PREROUTING", "-A", ext_ifname, int_ifname))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900702 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
703 << ext_ifname << "<-" << int_ifname;
704 } else {
705 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
706 // PREROUTING to apply any fwmark routing tag saved for the current
707 // connection, and rely on implicit routing to the default logical network
708 // otherwise.
Hugo Benichi1af52392020-11-27 18:09:32 +0900709 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname,
710 kFwmarkRoutingMask))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900711 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
712 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900713
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900714 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900715 // default network is eligible to be routed through a VPN if |route_on_vpn|
716 // is true.
717 if (route_on_vpn &&
718 !ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900719 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900720 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900721}
722
723void Datapath::StopRoutingDevice(const std::string& ext_ifname,
724 const std::string& int_ifname,
725 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900726 TrafficSource source,
727 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900728 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900729 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900730 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
731 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900732 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900733 if (!ext_ifname.empty()) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900734 ModifyFwmarkRoutingTag("PREROUTING", "-D", ext_ifname, int_ifname);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900735 } else {
Hugo Benichi1af52392020-11-27 18:09:32 +0900736 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname,
737 kFwmarkRoutingMask);
Hugo Benichi93306e52020-12-04 16:08:00 +0900738 if (route_on_vpn)
739 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900740 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900741}
742
Garrick Evansf0ab7132019-06-18 14:50:42 +0900743bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
744 const std::string& ipv4_addr) {
745 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900746 if (process_runner_->iptables(
747 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
748 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900749 return false;
750
751 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900752 if (process_runner_->iptables(
753 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
754 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900755 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
756 return false;
757 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900758 if (process_runner_->iptables(
759 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
760 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900761 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
762 return false;
763 }
764
765 return true;
766}
767
768void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
769 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900770 process_runner_->iptables(
771 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
772 "--to-destination", ipv4_addr, "-w"});
773 process_runner_->iptables(
774 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
775 "--to-destination", ipv4_addr, "-w"});
776 process_runner_->iptables(
777 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
778 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900779}
780
Hugo Benichie8758b52020-04-03 14:49:01 +0900781bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
782 return process_runner_->iptables(
783 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900784 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900785}
786
787void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
788 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900789 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900790}
791
Garrick Evans664a82f2019-12-17 12:18:05 +0900792bool Datapath::MaskInterfaceFlags(const std::string& ifname,
793 uint16_t on,
794 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900795 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
796 if (!sock.is_valid()) {
797 PLOG(ERROR) << "Failed to create control socket";
798 return false;
799 }
800 ifreq ifr;
801 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
802 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
803 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
804 return false;
805 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900806 ifr.ifr_flags |= on;
807 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900808 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900809 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
810 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900811 return false;
812 }
813 return true;
814}
815
Garrick Evans260ff302019-07-25 11:22:50 +0900816bool Datapath::AddIPv6HostRoute(const std::string& ifname,
817 const std::string& ipv6_addr,
818 int ipv6_prefix_len) {
819 std::string ipv6_addr_cidr =
820 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
821
Garrick Evans8e8e3472020-01-23 14:03:50 +0900822 return process_runner_->ip6("route", "replace",
823 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900824}
825
826void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
827 const std::string& ipv6_addr,
828 int ipv6_prefix_len) {
829 std::string ipv6_addr_cidr =
830 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
831
Garrick Evans8e8e3472020-01-23 14:03:50 +0900832 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900833}
834
Taoyu Lia0727dc2020-09-24 19:54:59 +0900835bool Datapath::AddIPv6Address(const std::string& ifname,
836 const std::string& ipv6_addr) {
837 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900838}
839
Taoyu Lia0727dc2020-09-24 19:54:59 +0900840void Datapath::RemoveIPv6Address(const std::string& ifname,
841 const std::string& ipv6_addr) {
842 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900843}
844
Hugo Benichi76be34a2020-08-26 22:35:54 +0900845void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900846 int ifindex = FindIfIndex(ext_ifname);
847 if (ifindex != 0 && !ModifyIptables(IpFamily::Dual, "mangle",
848 {"-A", kCheckRoutingMarkChain, "-o",
849 ext_ifname, "-m", "mark", "!", "--mark",
850 Fwmark::FromIfIndex(ifindex).ToString() +
851 "/" + kFwmarkRoutingMask.ToString(),
852 "-j", "DROP", "-w"}))
853 LOG(ERROR) << "Could not set fwmark routing filter rule for " << ext_ifname;
854
Hugo Benichi1af52392020-11-27 18:09:32 +0900855 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi76be34a2020-08-26 22:35:54 +0900856 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
857 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900858 // Save in CONNMARK the source tag for egress traffic of this connection.
859 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
860 kFwmarkAllSourcesMask))
861 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
862 "source tag on "
863 << ext_ifname;
864 // Restore from CONNMARK the source tag for ingress traffic of this connection
865 // (returned traffic).
866 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
867 kFwmarkAllSourcesMask))
868 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
869 "traffic received on "
870 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900871}
872
873void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900874 int ifindex = FindIfIndex(ext_ifname);
875 if (ifindex != 0 && !ModifyIptables(IpFamily::Dual, "mangle",
876 {"-D", kCheckRoutingMarkChain, "-o",
877 ext_ifname, "-m", "mark", "!", "--mark",
878 Fwmark::FromIfIndex(ifindex).ToString() +
879 "/" + kFwmarkRoutingMask.ToString(),
880 "-j", "DROP", "-w"}))
881 LOG(ERROR) << "Could not remove fwmark routing filter rule for "
882 << ext_ifname;
883
Hugo Benichi76be34a2020-08-26 22:35:54 +0900884 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
885 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900886 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
887 kFwmarkAllSourcesMask))
888 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
889 "fwmark source tag on "
890 << ext_ifname;
891 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
892 kFwmarkAllSourcesMask))
893 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
894 "traffic received on "
895 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900896}
897
Hugo Benichi2a940542020-10-26 18:50:49 +0900898void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi891275e2020-12-16 10:35:34 +0900899 if (process_runner_->iptables("nat", {"-A", "POSTROUTING", "-o", vpn_ifname,
900 "-j", "MASQUERADE", "-w"}) != 0)
901 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900902 StartConnectionPinning(vpn_ifname);
903 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", vpn_ifname, ""))
904 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +0900905 if (vpn_ifname != kArcBridge)
906 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
907 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi2a940542020-10-26 18:50:49 +0900908}
909
910void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900911 if (vpn_ifname != kArcBridge)
912 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
913 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi2a940542020-10-26 18:50:49 +0900914 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", vpn_ifname, ""))
915 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
916 StopConnectionPinning(vpn_ifname);
Hugo Benichi891275e2020-12-16 10:35:34 +0900917 if (process_runner_->iptables("nat", {"-D", "POSTROUTING", "-o", vpn_ifname,
918 "-j", "MASQUERADE", "-w"}) != 0)
919 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900920}
921
Hugo Benichi76be34a2020-08-26 22:35:54 +0900922bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
923 const std::string& op,
924 const std::string& oif) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900925 int ifindex = FindIfIndex(oif);
926 if (ifindex == 0) {
927 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
928 return false;
929 }
930
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900931 return ModifyConnmarkSet(family, "POSTROUTING", op, oif,
932 Fwmark::FromIfIndex(ifindex), kFwmarkRoutingMask);
933}
934
935bool Datapath::ModifyConnmarkSet(IpFamily family,
936 const std::string& chain,
937 const std::string& op,
938 const std::string& oif,
939 Fwmark mark,
940 Fwmark mask) {
941 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
942 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
943 return false;
944 }
945
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900946 std::vector<std::string> args = {op, chain};
947 if (!oif.empty()) {
948 args.push_back("-o");
949 args.push_back(oif);
950 }
951 args.push_back("-j");
952 args.push_back("CONNMARK");
953 args.push_back("--set-mark");
954 args.push_back(mark.ToString() + "/" + mask.ToString());
955 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +0900956
Hugo Benichi58f264a2020-10-16 18:16:05 +0900957 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +0900958}
959
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900960bool Datapath::ModifyConnmarkRestore(IpFamily family,
961 const std::string& chain,
962 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +0900963 const std::string& iif,
964 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900965 std::vector<std::string> args = {op, chain};
966 if (!iif.empty()) {
967 args.push_back("-i");
968 args.push_back(iif);
969 }
970 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +0900971 mask.ToString(), "-w"});
972 return ModifyIptables(family, "mangle", args);
973}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900974
Hugo Benichi1af52392020-11-27 18:09:32 +0900975bool Datapath::ModifyConnmarkSave(IpFamily family,
976 const std::string& chain,
977 const std::string& op,
978 const std::string& oif,
979 Fwmark mask) {
980 std::vector<std::string> args = {op, chain};
981 if (!oif.empty()) {
982 args.push_back("-o");
983 args.push_back(oif);
984 }
985 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
986 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +0900987 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900988}
989
Hugo Benichi2a940542020-10-26 18:50:49 +0900990bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
991 const std::string& op,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900992 const std::string& ext_ifname,
993 const std::string& int_ifname) {
994 int ifindex = FindIfIndex(ext_ifname);
995 if (ifindex == 0) {
996 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
997 return false;
998 }
999
Hugo Benichi2a940542020-10-26 18:50:49 +09001000 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001001 0 /*classid*/, Fwmark::FromIfIndex(ifindex),
1002 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001003}
1004
Hugo Benichi9be19b12020-08-14 15:33:40 +09001005bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
1006 const std::string& iif,
1007 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001008 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001009 0 /*classid*/, Fwmark::FromSource(source),
1010 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001011}
1012
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001013bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1014 TrafficSource source) {
1015 std::vector<std::string> args = {"-A",
1016 kApplyLocalSourceMarkChain,
1017 "-m",
1018 "mark",
1019 "--mark",
1020 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1021 "-j",
1022 "MARK",
1023 "--set-mark",
1024 Fwmark::FromSource(source).ToString() + "/" +
1025 kFwmarkAllSourcesMask.ToString(),
1026 "-w"};
1027 return ModifyIptables(IpFamily::Dual, "mangle", args);
1028}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001029
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001030bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1031 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001032 if (std::string(source.uid_name).empty() && source.classid == 0)
1033 return false;
1034
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001035 Fwmark mark = Fwmark::FromSource(source.source_type);
1036 if (source.is_on_vpn)
1037 mark = mark | kFwmarkRouteOnVpn;
1038
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001039 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1040 "" /*iif*/, source.uid_name, source.classid, mark,
1041 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001042}
1043
1044bool Datapath::ModifyFwmark(IpFamily family,
1045 const std::string& chain,
1046 const std::string& op,
1047 const std::string& iif,
1048 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001049 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001050 Fwmark mark,
1051 Fwmark mask,
1052 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001053 std::vector<std::string> args = {op, chain};
1054 if (!iif.empty()) {
1055 args.push_back("-i");
1056 args.push_back(iif);
1057 }
1058 if (!uid_name.empty()) {
1059 args.push_back("-m");
1060 args.push_back("owner");
1061 args.push_back("--uid-owner");
1062 args.push_back(uid_name);
1063 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001064 if (classid != 0) {
1065 args.push_back("-m");
1066 args.push_back("cgroup");
1067 args.push_back("--cgroup");
1068 args.push_back(base::StringPrintf("0x%08x", classid));
1069 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001070 args.push_back("-j");
1071 args.push_back("MARK");
1072 args.push_back("--set-mark");
1073 args.push_back(mark.ToString() + "/" + mask.ToString());
1074 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001075
Hugo Benichi58f264a2020-10-16 18:16:05 +09001076 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001077}
1078
Hugo Benichid82d8832020-08-14 10:05:03 +09001079bool Datapath::ModifyIpForwarding(IpFamily family,
1080 const std::string& op,
1081 const std::string& iif,
1082 const std::string& oif,
1083 bool log_failures) {
1084 if (iif.empty() && oif.empty()) {
1085 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1086 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001087 return false;
1088 }
1089
Hugo Benichid82d8832020-08-14 10:05:03 +09001090 std::vector<std::string> args = {op, "FORWARD"};
1091 if (!iif.empty()) {
1092 args.push_back("-i");
1093 args.push_back(iif);
1094 }
1095 if (!oif.empty()) {
1096 args.push_back("-o");
1097 args.push_back(oif);
1098 }
1099 args.push_back("-j");
1100 args.push_back("ACCEPT");
1101 args.push_back("-w");
1102
Hugo Benichi58f264a2020-10-16 18:16:05 +09001103 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001104}
1105
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001106bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1107 const std::string& op,
1108 const std::string& iif,
1109 Fwmark mark,
1110 Fwmark mask) {
1111 std::vector<std::string> args = {op, chain};
1112 if (!iif.empty()) {
1113 args.push_back("-i");
1114 args.push_back(iif);
1115 }
1116 if (mark.Value() != 0 && mask.Value() != 0) {
1117 args.push_back("-m");
1118 args.push_back("mark");
1119 args.push_back("--mark");
1120 args.push_back(mark.ToString() + "/" + mask.ToString());
1121 }
1122 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1123 return ModifyIptables(IpFamily::Dual, "mangle", args);
1124}
1125
1126bool Datapath::ModifyChain(IpFamily family,
1127 const std::string& table,
1128 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001129 const std::string& chain,
1130 bool log_failures) {
1131 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001132}
1133
1134bool Datapath::ModifyIptables(IpFamily family,
1135 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001136 const std::vector<std::string>& argv,
1137 bool log_failures) {
1138 switch (family) {
1139 case IPv4:
1140 case IPv6:
1141 case Dual:
1142 break;
1143 default:
1144 LOG(ERROR) << "Could not execute iptables command " << table
1145 << base::JoinString(argv, " ") << ": incorrect IP family "
1146 << family;
1147 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001148 }
1149
1150 bool success = true;
1151 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001152 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001153 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001154 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001155 return success;
1156}
1157
Hugo Benichid82d8832020-08-14 10:05:03 +09001158bool Datapath::StartIpForwarding(IpFamily family,
1159 const std::string& iif,
1160 const std::string& oif) {
1161 return ModifyIpForwarding(family, "-A", iif, oif);
1162}
1163
1164bool Datapath::StopIpForwarding(IpFamily family,
1165 const std::string& iif,
1166 const std::string& oif) {
1167 return ModifyIpForwarding(family, "-D", iif, oif);
1168}
1169
1170bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1171 const std::string& ifname2) {
1172 // Only start Ipv6 forwarding if -C returns false and it had not been
1173 // started yet.
1174 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1175 false /*log_failures*/) &&
1176 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1177 return false;
1178 }
1179
1180 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1181 false /*log_failures*/) &&
1182 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001183 RemoveIPv6Forwarding(ifname1, ifname2);
1184 return false;
1185 }
1186
1187 return true;
1188}
1189
1190void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1191 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001192 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1193 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001194}
1195
Garrick Evans3d97a392020-02-21 15:24:37 +09001196bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1197 uint32_t addr,
1198 uint32_t netmask) {
1199 struct rtentry route;
1200 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001201 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1202 SetSockaddrIn(&route.rt_dst, addr & netmask);
1203 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001204 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001205 return ModifyRtentry(SIOCADDRT, &route);
1206}
Garrick Evans3d97a392020-02-21 15:24:37 +09001207
Hugo Benichie8758b52020-04-03 14:49:01 +09001208bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1209 uint32_t addr,
1210 uint32_t netmask) {
1211 struct rtentry route;
1212 memset(&route, 0, sizeof(route));
1213 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1214 SetSockaddrIn(&route.rt_dst, addr & netmask);
1215 SetSockaddrIn(&route.rt_genmask, netmask);
1216 route.rt_flags = RTF_UP | RTF_GATEWAY;
1217 return ModifyRtentry(SIOCDELRT, &route);
1218}
1219
1220bool Datapath::AddIPv4Route(const std::string& ifname,
1221 uint32_t addr,
1222 uint32_t netmask) {
1223 struct rtentry route;
1224 memset(&route, 0, sizeof(route));
1225 SetSockaddrIn(&route.rt_dst, addr & netmask);
1226 SetSockaddrIn(&route.rt_genmask, netmask);
1227 char rt_dev[IFNAMSIZ];
1228 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1229 rt_dev[IFNAMSIZ - 1] = '\0';
1230 route.rt_dev = rt_dev;
1231 route.rt_flags = RTF_UP | RTF_GATEWAY;
1232 return ModifyRtentry(SIOCADDRT, &route);
1233}
1234
1235bool Datapath::DeleteIPv4Route(const std::string& ifname,
1236 uint32_t addr,
1237 uint32_t netmask) {
1238 struct rtentry route;
1239 memset(&route, 0, sizeof(route));
1240 SetSockaddrIn(&route.rt_dst, addr & netmask);
1241 SetSockaddrIn(&route.rt_genmask, netmask);
1242 char rt_dev[IFNAMSIZ];
1243 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1244 rt_dev[IFNAMSIZ - 1] = '\0';
1245 route.rt_dev = rt_dev;
1246 route.rt_flags = RTF_UP | RTF_GATEWAY;
1247 return ModifyRtentry(SIOCDELRT, &route);
1248}
1249
Taoyu Lia0727dc2020-09-24 19:54:59 +09001250bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001251 DCHECK(route);
1252 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001253 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001254 return false;
1255 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001256 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1257 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001258 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001259 return false;
1260 }
1261 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1262 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001263 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001264 return false;
1265 }
1266 return true;
1267}
1268
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001269bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1270 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1271 kArcAddr, kAdbServerPort, ifname,
1272 kLocalhostAddr, kAdbProxyTcpListenPort);
1273}
1274
1275void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1276 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1277 kArcAddr, kAdbServerPort, ifname,
1278 kLocalhostAddr, kAdbProxyTcpListenPort);
1279}
1280
1281bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1282 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1283 kAdbProxyTcpListenPort, ifname);
1284}
1285
1286void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1287 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1288 kAdbProxyTcpListenPort, ifname);
1289}
1290
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001291void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1292 if_nametoindex_[ifname] = ifindex;
1293}
1294
1295int Datapath::FindIfIndex(const std::string& ifname) {
1296 uint32_t ifindex = if_nametoindex(ifname.c_str());
1297 if (ifindex > 0) {
1298 if_nametoindex_[ifname] = ifindex;
1299 return ifindex;
1300 }
1301
1302 const auto it = if_nametoindex_.find(ifname);
1303 if (it != if_nametoindex_.end())
1304 return it->second;
1305
1306 return 0;
1307}
1308
Hugo Benichifcf81022020-12-04 11:01:37 +09001309std::ostream& operator<<(std::ostream& stream,
1310 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001311 stream << "{ pid: " << nsinfo.pid
1312 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001313 if (!nsinfo.outbound_ifname.empty()) {
1314 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1315 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001316 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1317 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001318 << ", peer_ifname: " << nsinfo.peer_ifname
1319 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1320 return stream;
1321}
1322
Garrick Evans3388a032020-03-24 11:25:55 +09001323} // namespace patchpanel