blob: 1d0a660faaaa641188b893a7aeb475ae424d5224 [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
Qijiang Fan713061e2021-03-08 15:45:12 +090020#include <base/check.h>
Garrick Evansc7ae82c2019-09-04 16:25:10 +090021#include <base/files/scoped_file.h>
22#include <base/logging.h>
Taoyu Li79871c92020-07-02 16:09:39 +090023#include <base/posix/eintr_wrapper.h>
Garrick Evans54861622019-07-19 09:05:09 +090024#include <base/strings/string_number_conversions.h>
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +090025#include <base/strings/string_util.h>
26#include <base/strings/stringprintf.h>
Garrick Evans4f9f5572019-11-26 10:25:16 +090027#include <brillo/userdb_utils.h>
Garrick Evans54861622019-07-19 09:05:09 +090028
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090029#include "patchpanel/adb_proxy.h"
Hugo Benichibfc49112020-12-14 12:54:44 +090030#include "patchpanel/arc_service.h"
Garrick Evans3388a032020-03-24 11:25:55 +090031#include "patchpanel/net_util.h"
32#include "patchpanel/scoped_ns.h"
Garrick Evansc7ae82c2019-09-04 16:25:10 +090033
Garrick Evans3388a032020-03-24 11:25:55 +090034namespace patchpanel {
Garrick Evans54861622019-07-19 09:05:09 +090035
Garrick Evansc7ae82c2019-09-04 16:25:10 +090036namespace {
Hugo Benichi76675592020-04-08 14:29:57 +090037// TODO(hugobenichi) Consolidate this constant definition in a single place.
38constexpr pid_t kTestPID = -2;
Garrick Evansc7ae82c2019-09-04 16:25:10 +090039constexpr char kDefaultIfname[] = "vmtap%d";
40constexpr char kTunDev[] = "/dev/net/tun";
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090041constexpr char kArcAddr[] = "100.115.92.2";
42constexpr char kLocalhostAddr[] = "127.0.0.1";
43constexpr uint16_t kAdbServerPort = 5555;
Hugo Benichie8758b52020-04-03 14:49:01 +090044
Hugo Benichibf811c62020-09-07 17:30:45 +090045// Constants used for dropping locally originated traffic bound to an incorrect
46// source IPv4 address.
47constexpr char kGuestIPv4Subnet[] = "100.115.92.0/23";
48constexpr std::array<const char*, 6> kPhysicalIfnamePrefixes{
49 {"eth+", "wlan+", "mlan+", "usb+", "wwan+", "rmnet+"}};
50
Hugo Benichi3a9162b2020-09-09 15:47:40 +090051constexpr char kApplyLocalSourceMarkChain[] = "apply_local_source_mark";
Hugo Benichi3ef370b2020-11-16 19:07:17 +090052constexpr char kApplyVpnMarkChain[] = "apply_vpn_mark";
Hugo Benichi155de002021-01-19 16:45:46 +090053constexpr char kCheckRoutingMarkChain[] = "check_routing_mark";
Hugo Benichi1e0656f2021-02-15 15:43:38 +090054constexpr char kDropGuestIpv4PrefixChain[] = "drop_guest_ipv4_prefix";
55constexpr char kRedirectDnsChain[] = "redirect_dns";
Hugo Benichi2a940542020-10-26 18:50:49 +090056
Garrick Evans8a067562020-05-11 12:47:30 +090057std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
58 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090059 if (n.length() < IFNAMSIZ)
60 return n;
Garrick Evans54861622019-07-19 09:05:09 +090061
Garrick Evans2f581a02020-05-11 10:43:35 +090062 // Best effort attempt to preserve the interface number, assuming it's the
63 // last char in the name.
64 auto c = ifname[ifname.length() - 1];
65 n.resize(IFNAMSIZ - 1);
66 n[n.length() - 1] = c;
67 return n;
Garrick Evans54861622019-07-19 09:05:09 +090068}
Garrick Evansf0ab7132019-06-18 14:50:42 +090069
Hugo Benichiaba7e2e2021-02-22 14:47:11 +090070bool Ioctl(ioctl_t ioctl_h, unsigned long req, const char* arg) {
71 base::ScopedFD control_fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
72 if (!control_fd.is_valid()) {
73 PLOG(ERROR) << "Failed to create control socket for ioctl request=" << req;
74 return false;
75 }
76 if ((*ioctl_h)(control_fd.get(), req, arg) != 0) {
77 PLOG(ERROR) << "ioctl request=" << req << " failed";
78 return false;
79 }
80 return true;
81}
82
Garrick Evans8a067562020-05-11 12:47:30 +090083} // namespace
84
85std::string ArcVethHostName(const std::string& ifname) {
86 return PrefixIfname("veth", ifname);
87}
88
89std::string ArcBridgeName(const std::string& ifname) {
90 return PrefixIfname("arc_", ifname);
91}
92
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090093Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
94 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090095
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090096Datapath::Datapath(MinijailedProcessRunner* process_runner,
97 Firewall* firewall,
98 ioctl_t ioctl_hook)
99 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900100 CHECK(process_runner_);
101}
102
Garrick Evans260ff302019-07-25 11:22:50 +0900103MinijailedProcessRunner& Datapath::runner() const {
104 return *process_runner_;
105}
106
Hugo Benichibf811c62020-09-07 17:30:45 +0900107void Datapath::Start() {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900108 // Restart from a clean iptables state in case of an unordered shutdown.
109 ResetIptables();
110
Hugo Benichibf811c62020-09-07 17:30:45 +0900111 // Enable IPv4 packet forwarding
112 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
113 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
114 << " Guest connectivity will not work correctly.";
115
116 // Limit local port range: Android owns 47104-61000.
117 // TODO(garrick): The original history behind this tweak is gone. Some
118 // investigation is needed to see if it is still applicable.
119 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
120 "32768 47103") != 0)
121 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
122 << " apps may not work correctly.";
123
124 // Enable IPv6 packet forwarding
125 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
126 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
127 << " IPv6 functionality may be broken.";
128
Hugo Benichi58125d32020-09-09 11:25:45 +0900129 // Create a FORWARD ACCEPT rule for connections already established.
130 if (process_runner_->iptables(
131 "filter", {"-A", "FORWARD", "-m", "state", "--state",
132 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900133 LOG(ERROR) << "Failed to install forwarding rule for established"
134 << " connections.";
135
136 // chromium:898210: Drop any locally originated traffic that would exit a
137 // physical interface with a source IPv4 address from the subnet of IPs used
138 // for VMs, containers, and connected namespaces This is needed to prevent
139 // packets leaking with an incorrect src IP when a local process binds to the
140 // wrong interface.
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900141 if (!ModifyChain(IpFamily::IPv4, "filter", "-N", kDropGuestIpv4PrefixChain))
142 LOG(ERROR) << "Failed to create " << kDropGuestIpv4PrefixChain
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900143 << " filter chain";
144 if (!ModifyIptables(IpFamily::IPv4, "filter",
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900145 {"-I", "OUTPUT", "-j", kDropGuestIpv4PrefixChain, "-w"}))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900146 LOG(ERROR) << "Failed to set up jump rule from filter OUTPUT to "
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900147 << kDropGuestIpv4PrefixChain;
Hugo Benichibf811c62020-09-07 17:30:45 +0900148 for (const auto& oif : kPhysicalIfnamePrefixes) {
149 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
150 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
151 << kGuestIPv4Subnet << " exiting " << oif;
152 }
153
Hugo Benichi561fae42021-01-22 15:28:40 +0900154 // Set static SNAT rules for any IPv4 traffic originated from a guest (ARC,
155 // Crostini, ...) or a connected namespace.
156 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
157 // need to be explicitly dropped as SNAT cannot be applied to them.
158 if (process_runner_->iptables(
159 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
160 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0)
161 LOG(ERROR) << "Failed to install SNAT mark rules.";
162 if (process_runner_->iptables(
163 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
164 "MASQUERADE", "-w"}) != 0)
165 LOG(ERROR) << "Failed to install SNAT mark rules.";
Hugo Benichibf811c62020-09-07 17:30:45 +0900166 if (!AddOutboundIPv4SNATMark("vmtap+"))
Hugo Benichi561fae42021-01-22 15:28:40 +0900167 LOG(ERROR) << "Failed to set up NAT for TAP devices.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900168
Hugo Benichi2a940542020-10-26 18:50:49 +0900169 // Applies the routing tag saved in conntrack for any established connection
170 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900171 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
172 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900173 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
Hugo Benichi155de002021-01-19 16:45:46 +0900174 // b/177787823 Also restore the routing tag after routing has taken place so
175 // that packets pre-tagged with the VPN routing tag are in sync with their
176 // associated CONNMARK routing tag. This is necessary to correctly identify
177 // packets exiting through the wrong interface.
178 if (!ModifyConnmarkRestore(IpFamily::Dual, "POSTROUTING", "-A", "" /*iif*/,
179 kFwmarkRoutingMask))
180 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK restore rule";
Hugo Benichi2a940542020-10-26 18:50:49 +0900181
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900182 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
183 // tag and tagging the local traffic that should be routed through a VPN.
184 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyLocalSourceMarkChain))
185 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
186 << " mangle chain";
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900187 if (!ModifyIptables(IpFamily::Dual, "mangle",
188 {"-A", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
189 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
190 << " to mangle OUTPUT";
191 // Create rules for tagging local sources with the source tag and the vpn
192 // policy tag.
193 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900194 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900195 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
196 << " in " << kApplyLocalSourceMarkChain;
197 }
198 // Finally add a catch-all rule for tagging any remaining local sources with
199 // the SYSTEM source tag
200 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
201 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
202
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900203 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
204 // traffic that should be routed through a VPN.
205 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyVpnMarkChain))
206 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900207 // All local outgoing traffic eligible to VPN routing should traverse the VPN
208 // marking chain.
209 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", "" /*iif*/, kFwmarkRouteOnVpn,
210 kFwmarkVpnMask))
211 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
212 // Any traffic that already has a routing tag applied is accepted.
213 if (!ModifyIptables(
214 IpFamily::Dual, "mangle",
215 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
216 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
217 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
218 "connections";
Hugo Benichi155de002021-01-19 16:45:46 +0900219
220 // Sets up a mangle chain used in POSTROUTING for checking consistency between
221 // the routing tag and the output interface.
222 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kCheckRoutingMarkChain))
223 LOG(ERROR) << "Failed to set up " << kCheckRoutingMarkChain
224 << " mangle chain";
Hugo Benichi155de002021-01-19 16:45:46 +0900225 // b/177787823 If it already exists, the routing tag of any traffic exiting an
226 // interface (physical or VPN) must match the routing tag of that interface.
227 if (!ModifyIptables(IpFamily::Dual, "mangle",
228 {"-A", "POSTROUTING", "-m", "mark", "!", "--mark",
229 "0x0/" + kFwmarkRoutingMask.ToString(), "-j",
230 kCheckRoutingMarkChain, "-w"}))
231 LOG(ERROR) << "Failed to add POSTROUTING jump rule to "
232 << kCheckRoutingMarkChain;
Hugo Benichi52a64992021-01-28 17:47:33 +0900233
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900234 // b/178331695 Sets up a nat chain used in OUTPUT for redirecting DNS queries
235 // of system services. When a VPN is connected, a query routed through a
236 // physical network is redirected to the primary nameserver of that network.
237 if (!ModifyChain(IpFamily::IPv4, "nat", "-N", kRedirectDnsChain))
238 LOG(ERROR) << "Failed to set up " << kRedirectDnsChain << " nat chain";
239
Hugo Benichi52a64992021-01-28 17:47:33 +0900240 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
241 // incorrectly cause neighbor discovery icmpv6 packets to be dropped. Add
242 // these rules to bypass connmark rule for those packets.
243 for (const auto& type : kNeighborDiscoveryTypes) {
244 if (!ModifyIptables(IpFamily::IPv6, "mangle",
245 {"-I", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
246 "-j", "ACCEPT", "-w"}))
247 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
248 << " packets in OUTPUT";
249 if (!ModifyIptables(IpFamily::IPv6, "mangle",
250 {"-I", kCheckRoutingMarkChain, "-p", "icmpv6",
251 "--icmpv6-type", type, "-j", "RETURN", "-w"}))
252 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
253 << " packets in " << kCheckRoutingMarkChain;
254 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900255}
256
257void Datapath::Stop() {
Hugo Benichibf811c62020-09-07 17:30:45 +0900258 // Restore original local port range.
259 // TODO(garrick): The original history behind this tweak is gone. Some
260 // investigation is needed to see if it is still applicable.
261 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
262 "32768 61000") != 0)
263 LOG(ERROR) << "Failed to restore local port range";
264
265 // Disable packet forwarding
266 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
267 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
268
269 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
270 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900271
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900272 ResetIptables();
273}
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900274
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900275void Datapath::ResetIptables() {
276 // If it exists, remove jump rules from a built-in chain to a custom routing
277 // or tagging chain.
278 ModifyIptables(IpFamily::IPv4, "filter",
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900279 {"-D", "OUTPUT", "-j", kDropGuestIpv4PrefixChain, "-w"},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900280 false /*log_failures*/);
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900281
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900282 // Flush chains used for routing and fwmark tagging. Also delete additional
283 // chains made by patchpanel. Chains used by permission broker (nat
284 // PREROUTING, filter INPUT) and chains used for traffic counters (mangle
285 // {rx,tx}_{<iface>, vpn}) are not flushed.
286 static struct {
287 IpFamily family;
288 std::string table;
289 std::string chain;
290 bool should_delete;
291 } resetOps[] = {
292 {IpFamily::Dual, "filter", "FORWARD", false},
293 {IpFamily::Dual, "mangle", "FORWARD", false},
294 {IpFamily::Dual, "mangle", "INPUT", false},
295 {IpFamily::Dual, "mangle", "OUTPUT", false},
296 {IpFamily::Dual, "mangle", "POSTROUTING", false},
297 {IpFamily::Dual, "mangle", "PREROUTING", false},
298 {IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain, true},
299 {IpFamily::Dual, "mangle", kApplyVpnMarkChain, true},
300 {IpFamily::Dual, "mangle", kCheckRoutingMarkChain, true},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900301 {IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain, true},
302 {IpFamily::IPv4, "nat", kRedirectDnsChain, true},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900303 {IpFamily::IPv4, "nat", "POSTROUTING", false},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900304 {IpFamily::IPv4, "nat", "OUTPUT", false},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900305 };
306 for (const auto& op : resetOps) {
307 // Chains to delete are custom chains and will not exist the first time
308 // patchpanel starts after boot. Skip flushing and delete these chains if
309 // they do not exist to avoid logging spurious error messages.
310 if (op.should_delete && !ModifyChain(op.family, op.table, "-L", op.chain,
311 false /*log_failures*/))
312 continue;
Hugo Benichi155de002021-01-19 16:45:46 +0900313
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900314 if (!ModifyChain(op.family, op.table, "-F", op.chain))
315 LOG(ERROR) << "Failed to flush " << op.chain << " chain in table "
316 << op.table;
Hugo Benichi2a940542020-10-26 18:50:49 +0900317
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900318 if (op.should_delete && !ModifyChain(op.family, op.table, "-X", op.chain))
319 LOG(ERROR) << "Failed to delete " << op.chain << " chain in table "
320 << op.table;
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900321 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900322}
323
Hugo Benichi33860d72020-07-09 16:34:01 +0900324bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
325 // Try first to delete any netns with name |netns_name| in case patchpanel
326 // did not exit cleanly.
327 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
328 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
329 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
330}
331
332bool Datapath::NetnsDeleteName(const std::string& netns_name) {
333 return process_runner_->ip_netns_delete(netns_name) == 0;
334}
335
Garrick Evans8a949dc2019-07-18 16:17:53 +0900336bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900337 uint32_t ipv4_addr,
338 uint32_t ipv4_prefix_len) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900339 if (!Ioctl(ioctl_, SIOCBRADDBR, ifname.c_str())) {
340 LOG(ERROR) << "Failed to create bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900341 return false;
342 }
343
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900344 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900345 if (process_runner_->ip(
346 "addr", "add",
347 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
348 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
349 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900350 RemoveBridge(ifname);
351 return false;
352 }
353
354 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900355 RemoveBridge(ifname);
356 return false;
357 }
358
359 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900360 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900361 RemoveBridge(ifname);
362 return false;
363 }
364
365 return true;
366}
367
368void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900369 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900370 process_runner_->ip("link", "set", {ifname, "down"});
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900371 if (!Ioctl(ioctl_, SIOCBRDELBR, ifname.c_str()))
372 LOG(ERROR) << "Failed to destroy bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900373}
374
Garrick Evans621ed262019-11-13 12:28:43 +0900375bool Datapath::AddToBridge(const std::string& br_ifname,
376 const std::string& ifname) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900377 struct ifreq ifr;
378 memset(&ifr, 0, sizeof(ifr));
379 strncpy(ifr.ifr_name, br_ifname.c_str(), sizeof(ifr.ifr_name));
380 ifr.ifr_ifindex = FindIfIndex(ifname);
381
382 if (!Ioctl(ioctl_, SIOCBRADDIF, reinterpret_cast<const char*>(&ifr))) {
383 LOG(ERROR) << "Failed to add " << ifname << " to bridge " << br_ifname;
384 return false;
385 }
386
387 return true;
Garrick Evans621ed262019-11-13 12:28:43 +0900388}
389
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900390std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900391 const MacAddress* mac_addr,
392 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900393 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900394 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
395 if (!dev.is_valid()) {
396 PLOG(ERROR) << "Failed to open " << kTunDev;
397 return "";
398 }
399
400 struct ifreq ifr;
401 memset(&ifr, 0, sizeof(ifr));
402 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
403 sizeof(ifr.ifr_name));
404 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
405
406 // If a template was given as the name, ifr_name will be updated with the
407 // actual interface name.
408 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900409 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900410 return "";
411 }
412 const char* ifname = ifr.ifr_name;
413
414 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900415 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900416 return "";
417 }
418
Garrick Evans4f9f5572019-11-26 10:25:16 +0900419 if (!user.empty()) {
420 uid_t uid = -1;
421 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
422 PLOG(ERROR) << "Unable to look up UID for " << user;
423 RemoveTAP(ifname);
424 return "";
425 }
426 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
427 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
428 << ifname;
429 RemoveTAP(ifname);
430 return "";
431 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900432 }
433
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900434 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900435 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
436 if (!sock.is_valid()) {
437 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900438 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900439 RemoveTAP(ifname);
440 return "";
441 }
442
Garrick Evans621ed262019-11-13 12:28:43 +0900443 if (ipv4_addr) {
444 struct sockaddr_in* addr =
445 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
446 addr->sin_family = AF_INET;
447 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
448 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
449 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
450 << " {" << ipv4_addr->ToCidrString() << "}";
451 RemoveTAP(ifname);
452 return "";
453 }
454
455 struct sockaddr_in* netmask =
456 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
457 netmask->sin_family = AF_INET;
458 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
459 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
460 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
461 << " {" << ipv4_addr->ToCidrString() << "}";
462 RemoveTAP(ifname);
463 return "";
464 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900465 }
466
Garrick Evans621ed262019-11-13 12:28:43 +0900467 if (mac_addr) {
468 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
469 hwaddr->sa_family = ARPHRD_ETHER;
470 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
471 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
472 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
473 << " {" << MacAddressToString(*mac_addr) << "}";
474 RemoveTAP(ifname);
475 return "";
476 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900477 }
478
479 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900480 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900481 RemoveTAP(ifname);
482 return "";
483 }
484
485 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
486 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900487 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900488 RemoveTAP(ifname);
489 return "";
490 }
491
492 return ifname;
493}
494
495void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900496 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900497}
498
Hugo Benichi33860d72020-07-09 16:34:01 +0900499bool Datapath::ConnectVethPair(pid_t netns_pid,
500 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900501 const std::string& veth_ifname,
502 const std::string& peer_ifname,
503 const MacAddress& remote_mac_addr,
504 uint32_t remote_ipv4_addr,
505 uint32_t remote_ipv4_prefix_len,
506 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900507 // Set up the virtual pair across the current namespace and |netns_name|.
508 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
509 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
510 << peer_ifname;
511 return false;
512 }
513
514 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900515 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900516 ScopedNS ns(netns_pid, ScopedNS::Type::Network);
Hugo Benichi33860d72020-07-09 16:34:01 +0900517 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900518 LOG(ERROR)
519 << "Cannot create virtual link -- invalid container namespace?";
520 return false;
521 }
522
Hugo Benichi76675592020-04-08 14:29:57 +0900523 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
524 remote_ipv4_prefix_len, true /* link up */,
525 remote_multicast_flag)) {
526 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
527 RemoveInterface(peer_ifname);
528 return false;
529 }
530 }
531
Hugo Benichi76675592020-04-08 14:29:57 +0900532 if (!ToggleInterface(veth_ifname, true /*up*/)) {
533 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
534 RemoveInterface(veth_ifname);
535 return false;
536 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900537
Hugo Benichi76675592020-04-08 14:29:57 +0900538 return true;
539}
540
Hugo Benichi33860d72020-07-09 16:34:01 +0900541bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
542 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900543 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900544 return process_runner_->ip("link", "add",
545 {veth_ifname, "type", "veth", "peer", "name",
546 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900547}
Garrick Evans54861622019-07-19 09:05:09 +0900548
Garrick Evans2470caa2020-03-04 14:15:41 +0900549bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
550 const std::string link = up ? "up" : "down";
551 return process_runner_->ip("link", "set", {ifname, link}) == 0;
552}
Garrick Evans54861622019-07-19 09:05:09 +0900553
Garrick Evans2470caa2020-03-04 14:15:41 +0900554bool Datapath::ConfigureInterface(const std::string& ifname,
555 const MacAddress& mac_addr,
556 uint32_t ipv4_addr,
557 uint32_t ipv4_prefix_len,
558 bool up,
559 bool enable_multicast) {
560 const std::string link = up ? "up" : "down";
561 const std::string multicast = enable_multicast ? "on" : "off";
562 return (process_runner_->ip(
563 "addr", "add",
564 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
565 IPv4AddressToString(
566 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
567 "dev", ifname}) == 0) &&
568 (process_runner_->ip("link", "set",
569 {
570 "dev",
571 ifname,
572 link,
573 "addr",
574 MacAddressToString(mac_addr),
575 "multicast",
576 multicast,
577 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900578}
579
580void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900581 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900582}
583
Hugo Benichi321f23b2020-09-25 15:42:05 +0900584bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
585 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900586 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900587 "filter", {"-I", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
588 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900589}
590
591bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
592 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900593 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900594 "filter", {"-D", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
595 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900596}
597
Hugo Benichifcf81022020-12-04 11:01:37 +0900598bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900599 // Veth interface configuration and client routing configuration:
600 // - attach a name to the client namespace.
601 // - create veth pair across the current namespace and the client namespace.
602 // - configure IPv4 address on remote veth inside client namespace.
603 // - configure IPv4 address on local veth inside host namespace.
604 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900605 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
606 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
607 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900608 return false;
609 }
610
Hugo Benichifcf81022020-12-04 11:01:37 +0900611 if (!ConnectVethPair(
612 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
613 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
614 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900615 LOG(ERROR) << "Failed to create veth pair for"
616 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900617 << nsinfo.pid;
618 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900619 return false;
620 }
621
Hugo Benichifcf81022020-12-04 11:01:37 +0900622 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
623 nsinfo.peer_subnet->AddressAtOffset(0),
624 nsinfo.peer_subnet->PrefixLength(),
625 true /* link up */, false /* enable_multicast */)) {
626 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
627 RemoveInterface(nsinfo.host_ifname);
628 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900629 return false;
630 }
631
632 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900633 ScopedNS ns(nsinfo.pid, ScopedNS::Type::Network);
Hugo Benichifcf81022020-12-04 11:01:37 +0900634 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
635 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
636 RemoveInterface(nsinfo.host_ifname);
637 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900638 return false;
639 }
640
Hugo Benichifcf81022020-12-04 11:01:37 +0900641 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
642 INADDR_ANY)) {
643 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
644 << " inside namespace pid " << nsinfo.pid;
645 RemoveInterface(nsinfo.host_ifname);
646 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900647 return false;
648 }
649 }
650
651 // Host namespace routing configuration
652 // - ingress: add route to client subnet via |host_ifname|.
653 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
654 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
655 // Note that by default unsolicited ingress traffic is not forwarded to the
656 // client namespace unless the client specifically set port forwarding
657 // through permission_broker DBus APIs.
658 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
659 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900660 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
661 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
662 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900663 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900664 RemoveInterface(nsinfo.host_ifname);
665 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900666 return false;
667 }
668
Hugo Benichi7c342672020-09-08 09:18:14 +0900669 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900670 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900671 LOG(ERROR) << "Failed to set SNAT for traffic"
672 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900673 << nsinfo.host_ifname;
674 RemoveInterface(nsinfo.host_ifname);
675 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
676 nsinfo.peer_subnet->BaseAddress(), netmask);
677 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
678 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900679 return false;
680 }
681
Hugo Benichi93306e52020-12-04 16:08:00 +0900682 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
683 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
684 nsinfo.route_on_vpn);
685
Hugo Benichi7c342672020-09-08 09:18:14 +0900686 return true;
687}
688
Hugo Benichifcf81022020-12-04 11:01:37 +0900689void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900690 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
691 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
692 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900693 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900694 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
695 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
696 nsinfo.peer_subnet->BaseAddress(),
697 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
698 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900699}
700
Hugo Benichi8d622b52020-08-13 15:24:12 +0900701void Datapath::StartRoutingDevice(const std::string& ext_ifname,
702 const std::string& int_ifname,
703 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900704 TrafficSource source,
705 bool route_on_vpn) {
706 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900707 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900708 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
709 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
710 << "->" << int_ifname;
711
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900712 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900713 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
714 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900715
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900716 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900717 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
718 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900719
Hugo Benichi2a940542020-10-26 18:50:49 +0900720 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
721 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
722 << source << " for " << int_ifname;
723
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900724 if (!ext_ifname.empty()) {
725 // If |ext_ifname| is not null, mark egress traffic with the
726 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi2a940542020-10-26 18:50:49 +0900727 if (!ModifyFwmarkRoutingTag("PREROUTING", "-A", ext_ifname, int_ifname))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900728 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
729 << ext_ifname << "<-" << int_ifname;
730 } else {
731 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
732 // PREROUTING to apply any fwmark routing tag saved for the current
733 // connection, and rely on implicit routing to the default logical network
734 // otherwise.
Hugo Benichi1af52392020-11-27 18:09:32 +0900735 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname,
736 kFwmarkRoutingMask))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900737 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
738 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900739
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900740 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900741 // default network is eligible to be routed through a VPN if |route_on_vpn|
742 // is true.
743 if (route_on_vpn &&
744 !ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900745 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900746 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900747}
748
749void Datapath::StopRoutingDevice(const std::string& ext_ifname,
750 const std::string& int_ifname,
751 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900752 TrafficSource source,
753 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900754 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900755 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900756 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
757 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900758 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900759 if (!ext_ifname.empty()) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900760 ModifyFwmarkRoutingTag("PREROUTING", "-D", ext_ifname, int_ifname);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900761 } else {
Hugo Benichi1af52392020-11-27 18:09:32 +0900762 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname,
763 kFwmarkRoutingMask);
Hugo Benichi93306e52020-12-04 16:08:00 +0900764 if (route_on_vpn)
765 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900766 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900767}
768
Garrick Evansf0ab7132019-06-18 14:50:42 +0900769bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
770 const std::string& ipv4_addr) {
771 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900772 if (process_runner_->iptables(
773 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
774 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900775 return false;
776
777 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900778 if (process_runner_->iptables(
779 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
780 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900781 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
782 return false;
783 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900784 if (process_runner_->iptables(
785 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
786 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900787 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
788 return false;
789 }
790
791 return true;
792}
793
794void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
795 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900796 process_runner_->iptables(
797 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
798 "--to-destination", ipv4_addr, "-w"});
799 process_runner_->iptables(
800 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
801 "--to-destination", ipv4_addr, "-w"});
802 process_runner_->iptables(
803 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
804 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900805}
806
Hugo Benichie8758b52020-04-03 14:49:01 +0900807bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
808 return process_runner_->iptables(
809 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900810 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900811}
812
813void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
814 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900815 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900816}
817
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900818bool Datapath::AddRedirectDnsRule(const std::string& ifname,
819 const std::string dns_ipv4_addr) {
820 bool success = true;
821 success &= RemoveRedirectDnsRule(ifname);
822 // Use Insert operation to ensure that the new DNS address is used first.
823 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
824 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
825 physical_dns_addresses_[ifname] = dns_ipv4_addr;
826 return success;
827}
828
829bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
830 const auto it = physical_dns_addresses_.find(ifname);
831 if (it == physical_dns_addresses_.end())
832 return true;
833
834 bool success = true;
835 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
836 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
837 physical_dns_addresses_.erase(it);
838 return success;
839}
840
841bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
842 const std::string& protocol,
843 const std::string& ifname,
844 const std::string& dns_ipv4_addr) {
845 std::vector<std::string> args = {op,
846 kRedirectDnsChain,
847 "-p",
848 protocol,
849 "--dport",
850 "53",
851 "-o",
852 ifname,
853 "-j",
854 "DNAT",
855 "--to-destination",
856 dns_ipv4_addr,
857 "-w"};
858 return process_runner_->iptables("nat", args) != 0;
859}
860
861bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
862 std::vector<std::string> args = {
863 op,
864 "OUTPUT",
865 "-m",
866 "mark",
867 "!",
868 "--mark",
869 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
870 "-j",
871 kRedirectDnsChain,
872 "-w"};
873 return process_runner_->iptables("nat", args) != 0;
874}
875
Garrick Evans664a82f2019-12-17 12:18:05 +0900876bool Datapath::MaskInterfaceFlags(const std::string& ifname,
877 uint16_t on,
878 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900879 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
880 if (!sock.is_valid()) {
881 PLOG(ERROR) << "Failed to create control socket";
882 return false;
883 }
884 ifreq ifr;
885 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
886 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
887 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
888 return false;
889 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900890 ifr.ifr_flags |= on;
891 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900892 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900893 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
894 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900895 return false;
896 }
897 return true;
898}
899
Garrick Evans260ff302019-07-25 11:22:50 +0900900bool Datapath::AddIPv6HostRoute(const std::string& ifname,
901 const std::string& ipv6_addr,
902 int ipv6_prefix_len) {
903 std::string ipv6_addr_cidr =
904 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
905
Garrick Evans8e8e3472020-01-23 14:03:50 +0900906 return process_runner_->ip6("route", "replace",
907 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900908}
909
910void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
911 const std::string& ipv6_addr,
912 int ipv6_prefix_len) {
913 std::string ipv6_addr_cidr =
914 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
915
Garrick Evans8e8e3472020-01-23 14:03:50 +0900916 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900917}
918
Taoyu Lia0727dc2020-09-24 19:54:59 +0900919bool Datapath::AddIPv6Address(const std::string& ifname,
920 const std::string& ipv6_addr) {
921 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900922}
923
Taoyu Lia0727dc2020-09-24 19:54:59 +0900924void Datapath::RemoveIPv6Address(const std::string& ifname,
925 const std::string& ipv6_addr) {
926 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900927}
928
Hugo Benichi76be34a2020-08-26 22:35:54 +0900929void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900930 int ifindex = FindIfIndex(ext_ifname);
931 if (ifindex != 0 && !ModifyIptables(IpFamily::Dual, "mangle",
932 {"-A", kCheckRoutingMarkChain, "-o",
933 ext_ifname, "-m", "mark", "!", "--mark",
934 Fwmark::FromIfIndex(ifindex).ToString() +
935 "/" + kFwmarkRoutingMask.ToString(),
936 "-j", "DROP", "-w"}))
937 LOG(ERROR) << "Could not set fwmark routing filter rule for " << ext_ifname;
938
Hugo Benichi1af52392020-11-27 18:09:32 +0900939 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi76be34a2020-08-26 22:35:54 +0900940 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
941 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900942 // Save in CONNMARK the source tag for egress traffic of this connection.
943 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
944 kFwmarkAllSourcesMask))
945 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
946 "source tag on "
947 << ext_ifname;
948 // Restore from CONNMARK the source tag for ingress traffic of this connection
949 // (returned traffic).
950 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
951 kFwmarkAllSourcesMask))
952 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
953 "traffic received on "
954 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900955}
956
957void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900958 int ifindex = FindIfIndex(ext_ifname);
959 if (ifindex != 0 && !ModifyIptables(IpFamily::Dual, "mangle",
960 {"-D", kCheckRoutingMarkChain, "-o",
961 ext_ifname, "-m", "mark", "!", "--mark",
962 Fwmark::FromIfIndex(ifindex).ToString() +
963 "/" + kFwmarkRoutingMask.ToString(),
964 "-j", "DROP", "-w"}))
965 LOG(ERROR) << "Could not remove fwmark routing filter rule for "
966 << ext_ifname;
967
Hugo Benichi76be34a2020-08-26 22:35:54 +0900968 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
969 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900970 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
971 kFwmarkAllSourcesMask))
972 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
973 "fwmark source tag on "
974 << ext_ifname;
975 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
976 kFwmarkAllSourcesMask))
977 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
978 "traffic received on "
979 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900980}
981
Hugo Benichi2a940542020-10-26 18:50:49 +0900982void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi891275e2020-12-16 10:35:34 +0900983 if (process_runner_->iptables("nat", {"-A", "POSTROUTING", "-o", vpn_ifname,
984 "-j", "MASQUERADE", "-w"}) != 0)
985 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900986 StartConnectionPinning(vpn_ifname);
987 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", vpn_ifname, ""))
988 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +0900989 if (vpn_ifname != kArcBridge)
990 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
991 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900992 if (!ModifyRedirectDnsJumpRule("-A"))
993 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900994}
995
996void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900997 if (vpn_ifname != kArcBridge)
998 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
999 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi2a940542020-10-26 18:50:49 +09001000 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", vpn_ifname, ""))
1001 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
1002 StopConnectionPinning(vpn_ifname);
Hugo Benichi891275e2020-12-16 10:35:34 +09001003 if (process_runner_->iptables("nat", {"-D", "POSTROUTING", "-o", vpn_ifname,
1004 "-j", "MASQUERADE", "-w"}) != 0)
1005 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001006 if (!ModifyRedirectDnsJumpRule("-D"))
1007 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001008}
1009
Hugo Benichi76be34a2020-08-26 22:35:54 +09001010bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
1011 const std::string& op,
1012 const std::string& oif) {
Hugo Benichi76be34a2020-08-26 22:35:54 +09001013 int ifindex = FindIfIndex(oif);
1014 if (ifindex == 0) {
1015 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
1016 return false;
1017 }
1018
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001019 return ModifyConnmarkSet(family, "POSTROUTING", op, oif,
1020 Fwmark::FromIfIndex(ifindex), kFwmarkRoutingMask);
1021}
1022
1023bool Datapath::ModifyConnmarkSet(IpFamily family,
1024 const std::string& chain,
1025 const std::string& op,
1026 const std::string& oif,
1027 Fwmark mark,
1028 Fwmark mask) {
1029 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
1030 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
1031 return false;
1032 }
1033
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001034 std::vector<std::string> args = {op, chain};
1035 if (!oif.empty()) {
1036 args.push_back("-o");
1037 args.push_back(oif);
1038 }
1039 args.push_back("-j");
1040 args.push_back("CONNMARK");
1041 args.push_back("--set-mark");
1042 args.push_back(mark.ToString() + "/" + mask.ToString());
1043 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +09001044
Hugo Benichi58f264a2020-10-16 18:16:05 +09001045 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +09001046}
1047
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001048bool Datapath::ModifyConnmarkRestore(IpFamily family,
1049 const std::string& chain,
1050 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001051 const std::string& iif,
1052 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001053 std::vector<std::string> args = {op, chain};
1054 if (!iif.empty()) {
1055 args.push_back("-i");
1056 args.push_back(iif);
1057 }
1058 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001059 mask.ToString(), "-w"});
1060 return ModifyIptables(family, "mangle", args);
1061}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001062
Hugo Benichi1af52392020-11-27 18:09:32 +09001063bool Datapath::ModifyConnmarkSave(IpFamily family,
1064 const std::string& chain,
1065 const std::string& op,
1066 const std::string& oif,
1067 Fwmark mask) {
1068 std::vector<std::string> args = {op, chain};
1069 if (!oif.empty()) {
1070 args.push_back("-o");
1071 args.push_back(oif);
1072 }
1073 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
1074 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +09001075 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001076}
1077
Hugo Benichi2a940542020-10-26 18:50:49 +09001078bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1079 const std::string& op,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001080 const std::string& ext_ifname,
1081 const std::string& int_ifname) {
1082 int ifindex = FindIfIndex(ext_ifname);
1083 if (ifindex == 0) {
1084 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
1085 return false;
1086 }
1087
Hugo Benichi2a940542020-10-26 18:50:49 +09001088 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001089 0 /*classid*/, Fwmark::FromIfIndex(ifindex),
1090 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001091}
1092
Hugo Benichi9be19b12020-08-14 15:33:40 +09001093bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
1094 const std::string& iif,
1095 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001096 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001097 0 /*classid*/, Fwmark::FromSource(source),
1098 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001099}
1100
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001101bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1102 TrafficSource source) {
1103 std::vector<std::string> args = {"-A",
1104 kApplyLocalSourceMarkChain,
1105 "-m",
1106 "mark",
1107 "--mark",
1108 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1109 "-j",
1110 "MARK",
1111 "--set-mark",
1112 Fwmark::FromSource(source).ToString() + "/" +
1113 kFwmarkAllSourcesMask.ToString(),
1114 "-w"};
1115 return ModifyIptables(IpFamily::Dual, "mangle", args);
1116}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001117
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001118bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1119 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001120 if (std::string(source.uid_name).empty() && source.classid == 0)
1121 return false;
1122
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001123 Fwmark mark = Fwmark::FromSource(source.source_type);
1124 if (source.is_on_vpn)
1125 mark = mark | kFwmarkRouteOnVpn;
1126
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001127 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1128 "" /*iif*/, source.uid_name, source.classid, mark,
1129 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001130}
1131
1132bool Datapath::ModifyFwmark(IpFamily family,
1133 const std::string& chain,
1134 const std::string& op,
1135 const std::string& iif,
1136 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001137 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001138 Fwmark mark,
1139 Fwmark mask,
1140 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001141 std::vector<std::string> args = {op, chain};
1142 if (!iif.empty()) {
1143 args.push_back("-i");
1144 args.push_back(iif);
1145 }
1146 if (!uid_name.empty()) {
1147 args.push_back("-m");
1148 args.push_back("owner");
1149 args.push_back("--uid-owner");
1150 args.push_back(uid_name);
1151 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001152 if (classid != 0) {
1153 args.push_back("-m");
1154 args.push_back("cgroup");
1155 args.push_back("--cgroup");
1156 args.push_back(base::StringPrintf("0x%08x", classid));
1157 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001158 args.push_back("-j");
1159 args.push_back("MARK");
1160 args.push_back("--set-mark");
1161 args.push_back(mark.ToString() + "/" + mask.ToString());
1162 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001163
Hugo Benichi58f264a2020-10-16 18:16:05 +09001164 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001165}
1166
Hugo Benichid82d8832020-08-14 10:05:03 +09001167bool Datapath::ModifyIpForwarding(IpFamily family,
1168 const std::string& op,
1169 const std::string& iif,
1170 const std::string& oif,
1171 bool log_failures) {
1172 if (iif.empty() && oif.empty()) {
1173 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1174 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001175 return false;
1176 }
1177
Hugo Benichid82d8832020-08-14 10:05:03 +09001178 std::vector<std::string> args = {op, "FORWARD"};
1179 if (!iif.empty()) {
1180 args.push_back("-i");
1181 args.push_back(iif);
1182 }
1183 if (!oif.empty()) {
1184 args.push_back("-o");
1185 args.push_back(oif);
1186 }
1187 args.push_back("-j");
1188 args.push_back("ACCEPT");
1189 args.push_back("-w");
1190
Hugo Benichi58f264a2020-10-16 18:16:05 +09001191 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001192}
1193
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001194bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1195 const std::string& op,
1196 const std::string& iif,
1197 Fwmark mark,
1198 Fwmark mask) {
1199 std::vector<std::string> args = {op, chain};
1200 if (!iif.empty()) {
1201 args.push_back("-i");
1202 args.push_back(iif);
1203 }
1204 if (mark.Value() != 0 && mask.Value() != 0) {
1205 args.push_back("-m");
1206 args.push_back("mark");
1207 args.push_back("--mark");
1208 args.push_back(mark.ToString() + "/" + mask.ToString());
1209 }
1210 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1211 return ModifyIptables(IpFamily::Dual, "mangle", args);
1212}
1213
1214bool Datapath::ModifyChain(IpFamily family,
1215 const std::string& table,
1216 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001217 const std::string& chain,
1218 bool log_failures) {
1219 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001220}
1221
1222bool Datapath::ModifyIptables(IpFamily family,
1223 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001224 const std::vector<std::string>& argv,
1225 bool log_failures) {
1226 switch (family) {
1227 case IPv4:
1228 case IPv6:
1229 case Dual:
1230 break;
1231 default:
1232 LOG(ERROR) << "Could not execute iptables command " << table
1233 << base::JoinString(argv, " ") << ": incorrect IP family "
1234 << family;
1235 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001236 }
1237
1238 bool success = true;
1239 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001240 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001241 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001242 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001243 return success;
1244}
1245
Hugo Benichid82d8832020-08-14 10:05:03 +09001246bool Datapath::StartIpForwarding(IpFamily family,
1247 const std::string& iif,
1248 const std::string& oif) {
1249 return ModifyIpForwarding(family, "-A", iif, oif);
1250}
1251
1252bool Datapath::StopIpForwarding(IpFamily family,
1253 const std::string& iif,
1254 const std::string& oif) {
1255 return ModifyIpForwarding(family, "-D", iif, oif);
1256}
1257
1258bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1259 const std::string& ifname2) {
1260 // Only start Ipv6 forwarding if -C returns false and it had not been
1261 // started yet.
1262 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1263 false /*log_failures*/) &&
1264 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1265 return false;
1266 }
1267
1268 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1269 false /*log_failures*/) &&
1270 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001271 RemoveIPv6Forwarding(ifname1, ifname2);
1272 return false;
1273 }
1274
1275 return true;
1276}
1277
1278void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1279 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001280 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1281 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001282}
1283
Garrick Evans3d97a392020-02-21 15:24:37 +09001284bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1285 uint32_t addr,
1286 uint32_t netmask) {
1287 struct rtentry route;
1288 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001289 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1290 SetSockaddrIn(&route.rt_dst, addr & netmask);
1291 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001292 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001293 return ModifyRtentry(SIOCADDRT, &route);
1294}
Garrick Evans3d97a392020-02-21 15:24:37 +09001295
Hugo Benichie8758b52020-04-03 14:49:01 +09001296bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1297 uint32_t addr,
1298 uint32_t netmask) {
1299 struct rtentry route;
1300 memset(&route, 0, sizeof(route));
1301 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1302 SetSockaddrIn(&route.rt_dst, addr & netmask);
1303 SetSockaddrIn(&route.rt_genmask, netmask);
1304 route.rt_flags = RTF_UP | RTF_GATEWAY;
1305 return ModifyRtentry(SIOCDELRT, &route);
1306}
1307
1308bool Datapath::AddIPv4Route(const std::string& ifname,
1309 uint32_t addr,
1310 uint32_t netmask) {
1311 struct rtentry route;
1312 memset(&route, 0, sizeof(route));
1313 SetSockaddrIn(&route.rt_dst, addr & netmask);
1314 SetSockaddrIn(&route.rt_genmask, netmask);
1315 char rt_dev[IFNAMSIZ];
1316 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1317 rt_dev[IFNAMSIZ - 1] = '\0';
1318 route.rt_dev = rt_dev;
1319 route.rt_flags = RTF_UP | RTF_GATEWAY;
1320 return ModifyRtentry(SIOCADDRT, &route);
1321}
1322
1323bool Datapath::DeleteIPv4Route(const std::string& ifname,
1324 uint32_t addr,
1325 uint32_t netmask) {
1326 struct rtentry route;
1327 memset(&route, 0, sizeof(route));
1328 SetSockaddrIn(&route.rt_dst, addr & netmask);
1329 SetSockaddrIn(&route.rt_genmask, netmask);
1330 char rt_dev[IFNAMSIZ];
1331 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1332 rt_dev[IFNAMSIZ - 1] = '\0';
1333 route.rt_dev = rt_dev;
1334 route.rt_flags = RTF_UP | RTF_GATEWAY;
1335 return ModifyRtentry(SIOCDELRT, &route);
1336}
1337
Taoyu Lia0727dc2020-09-24 19:54:59 +09001338bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001339 DCHECK(route);
1340 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001341 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001342 return false;
1343 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001344 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1345 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001346 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001347 return false;
1348 }
1349 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1350 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001351 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001352 return false;
1353 }
1354 return true;
1355}
1356
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001357bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1358 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1359 kArcAddr, kAdbServerPort, ifname,
1360 kLocalhostAddr, kAdbProxyTcpListenPort);
1361}
1362
1363void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1364 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1365 kArcAddr, kAdbServerPort, ifname,
1366 kLocalhostAddr, kAdbProxyTcpListenPort);
1367}
1368
1369bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1370 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1371 kAdbProxyTcpListenPort, ifname);
1372}
1373
1374void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1375 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1376 kAdbProxyTcpListenPort, ifname);
1377}
1378
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001379void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1380 if_nametoindex_[ifname] = ifindex;
1381}
1382
1383int Datapath::FindIfIndex(const std::string& ifname) {
1384 uint32_t ifindex = if_nametoindex(ifname.c_str());
1385 if (ifindex > 0) {
1386 if_nametoindex_[ifname] = ifindex;
1387 return ifindex;
1388 }
1389
1390 const auto it = if_nametoindex_.find(ifname);
1391 if (it != if_nametoindex_.end())
1392 return it->second;
1393
1394 return 0;
1395}
1396
Hugo Benichifcf81022020-12-04 11:01:37 +09001397std::ostream& operator<<(std::ostream& stream,
1398 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001399 stream << "{ pid: " << nsinfo.pid
1400 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001401 if (!nsinfo.outbound_ifname.empty()) {
1402 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1403 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001404 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1405 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001406 << ", peer_ifname: " << nsinfo.peer_ifname
1407 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1408 return stream;
1409}
1410
Garrick Evans3388a032020-03-24 11:25:55 +09001411} // namespace patchpanel