blob: 08128bc824194240833d9a8f44304c835a9b2baf [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
Hugo Benichiac799a82021-03-25 00:16:16 +0900136 // Create a FORWARD rule for accepting any ARC originated traffic regardless
137 // of the output interface. This enables for ARC certain multihoming
138 // scenarios (b/182594063).
139 if (process_runner_->iptables(
140 "filter", {"-A", "FORWARD", "-i", "arc+", "-j", "ACCEPT", "-w"}) != 0)
141 LOG(ERROR) << "Failed to install forwarding rule for ARC traffic";
142
Hugo Benichibf811c62020-09-07 17:30:45 +0900143 // chromium:898210: Drop any locally originated traffic that would exit a
144 // physical interface with a source IPv4 address from the subnet of IPs used
145 // for VMs, containers, and connected namespaces This is needed to prevent
146 // packets leaking with an incorrect src IP when a local process binds to the
147 // wrong interface.
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900148 if (!ModifyChain(IpFamily::IPv4, "filter", "-N", kDropGuestIpv4PrefixChain))
149 LOG(ERROR) << "Failed to create " << kDropGuestIpv4PrefixChain
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900150 << " filter chain";
151 if (!ModifyIptables(IpFamily::IPv4, "filter",
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900152 {"-I", "OUTPUT", "-j", kDropGuestIpv4PrefixChain, "-w"}))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900153 LOG(ERROR) << "Failed to set up jump rule from filter OUTPUT to "
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900154 << kDropGuestIpv4PrefixChain;
Hugo Benichibf811c62020-09-07 17:30:45 +0900155 for (const auto& oif : kPhysicalIfnamePrefixes) {
156 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
157 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
158 << kGuestIPv4Subnet << " exiting " << oif;
159 }
160
Hugo Benichi561fae42021-01-22 15:28:40 +0900161 // Set static SNAT rules for any IPv4 traffic originated from a guest (ARC,
162 // Crostini, ...) or a connected namespace.
163 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
164 // need to be explicitly dropped as SNAT cannot be applied to them.
165 if (process_runner_->iptables(
166 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
167 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0)
168 LOG(ERROR) << "Failed to install SNAT mark rules.";
169 if (process_runner_->iptables(
170 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
171 "MASQUERADE", "-w"}) != 0)
172 LOG(ERROR) << "Failed to install SNAT mark rules.";
Hugo Benichibf811c62020-09-07 17:30:45 +0900173 if (!AddOutboundIPv4SNATMark("vmtap+"))
Hugo Benichi561fae42021-01-22 15:28:40 +0900174 LOG(ERROR) << "Failed to set up NAT for TAP devices.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900175
Hugo Benichi2a940542020-10-26 18:50:49 +0900176 // Applies the routing tag saved in conntrack for any established connection
177 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900178 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
179 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900180 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
Hugo Benichi155de002021-01-19 16:45:46 +0900181 // b/177787823 Also restore the routing tag after routing has taken place so
182 // that packets pre-tagged with the VPN routing tag are in sync with their
183 // associated CONNMARK routing tag. This is necessary to correctly identify
184 // packets exiting through the wrong interface.
185 if (!ModifyConnmarkRestore(IpFamily::Dual, "POSTROUTING", "-A", "" /*iif*/,
186 kFwmarkRoutingMask))
187 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK restore rule";
Hugo Benichi2a940542020-10-26 18:50:49 +0900188
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900189 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
190 // tag and tagging the local traffic that should be routed through a VPN.
191 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyLocalSourceMarkChain))
192 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
193 << " mangle chain";
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900194 if (!ModifyIptables(IpFamily::Dual, "mangle",
195 {"-A", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
196 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
197 << " to mangle OUTPUT";
198 // Create rules for tagging local sources with the source tag and the vpn
199 // policy tag.
200 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900201 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900202 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
203 << " in " << kApplyLocalSourceMarkChain;
204 }
205 // Finally add a catch-all rule for tagging any remaining local sources with
206 // the SYSTEM source tag
207 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
208 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
209
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900210 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
211 // traffic that should be routed through a VPN.
212 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyVpnMarkChain))
213 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900214 // All local outgoing traffic eligible to VPN routing should traverse the VPN
215 // marking chain.
216 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", "" /*iif*/, kFwmarkRouteOnVpn,
217 kFwmarkVpnMask))
218 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
219 // Any traffic that already has a routing tag applied is accepted.
220 if (!ModifyIptables(
221 IpFamily::Dual, "mangle",
222 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
223 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
224 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
225 "connections";
Hugo Benichi155de002021-01-19 16:45:46 +0900226
227 // Sets up a mangle chain used in POSTROUTING for checking consistency between
228 // the routing tag and the output interface.
229 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kCheckRoutingMarkChain))
230 LOG(ERROR) << "Failed to set up " << kCheckRoutingMarkChain
231 << " mangle chain";
Hugo Benichi155de002021-01-19 16:45:46 +0900232 // b/177787823 If it already exists, the routing tag of any traffic exiting an
233 // interface (physical or VPN) must match the routing tag of that interface.
234 if (!ModifyIptables(IpFamily::Dual, "mangle",
235 {"-A", "POSTROUTING", "-m", "mark", "!", "--mark",
236 "0x0/" + kFwmarkRoutingMask.ToString(), "-j",
237 kCheckRoutingMarkChain, "-w"}))
238 LOG(ERROR) << "Failed to add POSTROUTING jump rule to "
239 << kCheckRoutingMarkChain;
Hugo Benichi52a64992021-01-28 17:47:33 +0900240
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900241 // b/178331695 Sets up a nat chain used in OUTPUT for redirecting DNS queries
242 // of system services. When a VPN is connected, a query routed through a
243 // physical network is redirected to the primary nameserver of that network.
244 if (!ModifyChain(IpFamily::IPv4, "nat", "-N", kRedirectDnsChain))
245 LOG(ERROR) << "Failed to set up " << kRedirectDnsChain << " nat chain";
246
Hugo Benichi52a64992021-01-28 17:47:33 +0900247 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
248 // incorrectly cause neighbor discovery icmpv6 packets to be dropped. Add
249 // these rules to bypass connmark rule for those packets.
250 for (const auto& type : kNeighborDiscoveryTypes) {
251 if (!ModifyIptables(IpFamily::IPv6, "mangle",
252 {"-I", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
253 "-j", "ACCEPT", "-w"}))
254 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
255 << " packets in OUTPUT";
256 if (!ModifyIptables(IpFamily::IPv6, "mangle",
257 {"-I", kCheckRoutingMarkChain, "-p", "icmpv6",
258 "--icmpv6-type", type, "-j", "RETURN", "-w"}))
259 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
260 << " packets in " << kCheckRoutingMarkChain;
261 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900262}
263
264void Datapath::Stop() {
Hugo Benichibf811c62020-09-07 17:30:45 +0900265 // Restore original local port range.
266 // TODO(garrick): The original history behind this tweak is gone. Some
267 // investigation is needed to see if it is still applicable.
268 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
269 "32768 61000") != 0)
270 LOG(ERROR) << "Failed to restore local port range";
271
272 // Disable packet forwarding
273 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
274 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
275
276 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
277 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900278
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900279 ResetIptables();
280}
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900281
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900282void Datapath::ResetIptables() {
283 // If it exists, remove jump rules from a built-in chain to a custom routing
284 // or tagging chain.
285 ModifyIptables(IpFamily::IPv4, "filter",
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900286 {"-D", "OUTPUT", "-j", kDropGuestIpv4PrefixChain, "-w"},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900287 false /*log_failures*/);
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900288
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900289 // Flush chains used for routing and fwmark tagging. Also delete additional
290 // chains made by patchpanel. Chains used by permission broker (nat
291 // PREROUTING, filter INPUT) and chains used for traffic counters (mangle
292 // {rx,tx}_{<iface>, vpn}) are not flushed.
293 static struct {
294 IpFamily family;
295 std::string table;
296 std::string chain;
297 bool should_delete;
298 } resetOps[] = {
299 {IpFamily::Dual, "filter", "FORWARD", false},
300 {IpFamily::Dual, "mangle", "FORWARD", false},
301 {IpFamily::Dual, "mangle", "INPUT", false},
302 {IpFamily::Dual, "mangle", "OUTPUT", false},
303 {IpFamily::Dual, "mangle", "POSTROUTING", false},
304 {IpFamily::Dual, "mangle", "PREROUTING", false},
305 {IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain, true},
306 {IpFamily::Dual, "mangle", kApplyVpnMarkChain, true},
307 {IpFamily::Dual, "mangle", kCheckRoutingMarkChain, true},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900308 {IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain, true},
309 {IpFamily::IPv4, "nat", kRedirectDnsChain, true},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900310 {IpFamily::IPv4, "nat", "POSTROUTING", false},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900311 {IpFamily::IPv4, "nat", "OUTPUT", false},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900312 };
313 for (const auto& op : resetOps) {
314 // Chains to delete are custom chains and will not exist the first time
315 // patchpanel starts after boot. Skip flushing and delete these chains if
316 // they do not exist to avoid logging spurious error messages.
317 if (op.should_delete && !ModifyChain(op.family, op.table, "-L", op.chain,
318 false /*log_failures*/))
319 continue;
Hugo Benichi155de002021-01-19 16:45:46 +0900320
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900321 if (!ModifyChain(op.family, op.table, "-F", op.chain))
322 LOG(ERROR) << "Failed to flush " << op.chain << " chain in table "
323 << op.table;
Hugo Benichi2a940542020-10-26 18:50:49 +0900324
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900325 if (op.should_delete && !ModifyChain(op.family, op.table, "-X", op.chain))
326 LOG(ERROR) << "Failed to delete " << op.chain << " chain in table "
327 << op.table;
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900328 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900329}
330
Hugo Benichi33860d72020-07-09 16:34:01 +0900331bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
332 // Try first to delete any netns with name |netns_name| in case patchpanel
333 // did not exit cleanly.
334 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
335 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
336 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
337}
338
339bool Datapath::NetnsDeleteName(const std::string& netns_name) {
340 return process_runner_->ip_netns_delete(netns_name) == 0;
341}
342
Garrick Evans8a949dc2019-07-18 16:17:53 +0900343bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900344 uint32_t ipv4_addr,
345 uint32_t ipv4_prefix_len) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900346 if (!Ioctl(ioctl_, SIOCBRADDBR, ifname.c_str())) {
347 LOG(ERROR) << "Failed to create bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900348 return false;
349 }
350
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900351 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900352 if (process_runner_->ip(
353 "addr", "add",
354 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
355 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
356 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900357 RemoveBridge(ifname);
358 return false;
359 }
360
361 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900362 RemoveBridge(ifname);
363 return false;
364 }
365
366 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900367 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900368 RemoveBridge(ifname);
369 return false;
370 }
371
372 return true;
373}
374
375void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900376 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900377 process_runner_->ip("link", "set", {ifname, "down"});
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900378 if (!Ioctl(ioctl_, SIOCBRDELBR, ifname.c_str()))
379 LOG(ERROR) << "Failed to destroy bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900380}
381
Garrick Evans621ed262019-11-13 12:28:43 +0900382bool Datapath::AddToBridge(const std::string& br_ifname,
383 const std::string& ifname) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900384 struct ifreq ifr;
385 memset(&ifr, 0, sizeof(ifr));
386 strncpy(ifr.ifr_name, br_ifname.c_str(), sizeof(ifr.ifr_name));
387 ifr.ifr_ifindex = FindIfIndex(ifname);
388
389 if (!Ioctl(ioctl_, SIOCBRADDIF, reinterpret_cast<const char*>(&ifr))) {
390 LOG(ERROR) << "Failed to add " << ifname << " to bridge " << br_ifname;
391 return false;
392 }
393
394 return true;
Garrick Evans621ed262019-11-13 12:28:43 +0900395}
396
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900397std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900398 const MacAddress* mac_addr,
399 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900400 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900401 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
402 if (!dev.is_valid()) {
403 PLOG(ERROR) << "Failed to open " << kTunDev;
404 return "";
405 }
406
407 struct ifreq ifr;
408 memset(&ifr, 0, sizeof(ifr));
409 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
410 sizeof(ifr.ifr_name));
411 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
412
413 // If a template was given as the name, ifr_name will be updated with the
414 // actual interface name.
415 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900416 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900417 return "";
418 }
419 const char* ifname = ifr.ifr_name;
420
421 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900422 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900423 return "";
424 }
425
Garrick Evans4f9f5572019-11-26 10:25:16 +0900426 if (!user.empty()) {
427 uid_t uid = -1;
428 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
429 PLOG(ERROR) << "Unable to look up UID for " << user;
430 RemoveTAP(ifname);
431 return "";
432 }
433 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
434 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
435 << ifname;
436 RemoveTAP(ifname);
437 return "";
438 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900439 }
440
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900441 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900442 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
443 if (!sock.is_valid()) {
444 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900445 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900446 RemoveTAP(ifname);
447 return "";
448 }
449
Garrick Evans621ed262019-11-13 12:28:43 +0900450 if (ipv4_addr) {
451 struct sockaddr_in* addr =
452 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
453 addr->sin_family = AF_INET;
454 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
455 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
456 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
457 << " {" << ipv4_addr->ToCidrString() << "}";
458 RemoveTAP(ifname);
459 return "";
460 }
461
462 struct sockaddr_in* netmask =
463 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
464 netmask->sin_family = AF_INET;
465 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
466 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
467 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
468 << " {" << ipv4_addr->ToCidrString() << "}";
469 RemoveTAP(ifname);
470 return "";
471 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900472 }
473
Garrick Evans621ed262019-11-13 12:28:43 +0900474 if (mac_addr) {
475 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
476 hwaddr->sa_family = ARPHRD_ETHER;
477 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
478 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
479 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
480 << " {" << MacAddressToString(*mac_addr) << "}";
481 RemoveTAP(ifname);
482 return "";
483 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900484 }
485
486 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900487 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900488 RemoveTAP(ifname);
489 return "";
490 }
491
492 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
493 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900494 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900495 RemoveTAP(ifname);
496 return "";
497 }
498
499 return ifname;
500}
501
502void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900503 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900504}
505
Hugo Benichi33860d72020-07-09 16:34:01 +0900506bool Datapath::ConnectVethPair(pid_t netns_pid,
507 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900508 const std::string& veth_ifname,
509 const std::string& peer_ifname,
510 const MacAddress& remote_mac_addr,
511 uint32_t remote_ipv4_addr,
512 uint32_t remote_ipv4_prefix_len,
513 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900514 // Set up the virtual pair across the current namespace and |netns_name|.
515 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
516 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
517 << peer_ifname;
518 return false;
519 }
520
521 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900522 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900523 ScopedNS ns(netns_pid, ScopedNS::Type::Network);
Hugo Benichi33860d72020-07-09 16:34:01 +0900524 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900525 LOG(ERROR)
526 << "Cannot create virtual link -- invalid container namespace?";
527 return false;
528 }
529
Hugo Benichi76675592020-04-08 14:29:57 +0900530 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
531 remote_ipv4_prefix_len, true /* link up */,
532 remote_multicast_flag)) {
533 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
534 RemoveInterface(peer_ifname);
535 return false;
536 }
537 }
538
Hugo Benichi76675592020-04-08 14:29:57 +0900539 if (!ToggleInterface(veth_ifname, true /*up*/)) {
540 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
541 RemoveInterface(veth_ifname);
542 return false;
543 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900544
Hugo Benichi76675592020-04-08 14:29:57 +0900545 return true;
546}
547
Hugo Benichi33860d72020-07-09 16:34:01 +0900548bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
549 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900550 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900551 return process_runner_->ip("link", "add",
552 {veth_ifname, "type", "veth", "peer", "name",
553 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900554}
Garrick Evans54861622019-07-19 09:05:09 +0900555
Garrick Evans2470caa2020-03-04 14:15:41 +0900556bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
557 const std::string link = up ? "up" : "down";
558 return process_runner_->ip("link", "set", {ifname, link}) == 0;
559}
Garrick Evans54861622019-07-19 09:05:09 +0900560
Garrick Evans2470caa2020-03-04 14:15:41 +0900561bool Datapath::ConfigureInterface(const std::string& ifname,
562 const MacAddress& mac_addr,
563 uint32_t ipv4_addr,
564 uint32_t ipv4_prefix_len,
565 bool up,
566 bool enable_multicast) {
567 const std::string link = up ? "up" : "down";
568 const std::string multicast = enable_multicast ? "on" : "off";
569 return (process_runner_->ip(
570 "addr", "add",
571 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
572 IPv4AddressToString(
573 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
574 "dev", ifname}) == 0) &&
575 (process_runner_->ip("link", "set",
576 {
577 "dev",
578 ifname,
579 link,
580 "addr",
581 MacAddressToString(mac_addr),
582 "multicast",
583 multicast,
584 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900585}
586
587void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900588 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900589}
590
Hugo Benichi321f23b2020-09-25 15:42:05 +0900591bool Datapath::AddSourceIPv4DropRule(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", {"-I", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
595 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900596}
597
598bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
599 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900600 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900601 "filter", {"-D", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
602 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900603}
604
Hugo Benichifcf81022020-12-04 11:01:37 +0900605bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900606 // Veth interface configuration and client routing configuration:
607 // - attach a name to the client namespace.
608 // - create veth pair across the current namespace and the client namespace.
609 // - configure IPv4 address on remote veth inside client namespace.
610 // - configure IPv4 address on local veth inside host namespace.
611 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900612 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
613 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
614 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900615 return false;
616 }
617
Hugo Benichifcf81022020-12-04 11:01:37 +0900618 if (!ConnectVethPair(
619 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
620 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
621 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900622 LOG(ERROR) << "Failed to create veth pair for"
623 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900624 << nsinfo.pid;
625 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900626 return false;
627 }
628
Hugo Benichifcf81022020-12-04 11:01:37 +0900629 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
630 nsinfo.peer_subnet->AddressAtOffset(0),
631 nsinfo.peer_subnet->PrefixLength(),
632 true /* link up */, false /* enable_multicast */)) {
633 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
634 RemoveInterface(nsinfo.host_ifname);
635 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900636 return false;
637 }
638
639 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900640 ScopedNS ns(nsinfo.pid, ScopedNS::Type::Network);
Hugo Benichifcf81022020-12-04 11:01:37 +0900641 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
642 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
643 RemoveInterface(nsinfo.host_ifname);
644 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900645 return false;
646 }
647
Hugo Benichifcf81022020-12-04 11:01:37 +0900648 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
649 INADDR_ANY)) {
650 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
651 << " inside namespace pid " << nsinfo.pid;
652 RemoveInterface(nsinfo.host_ifname);
653 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900654 return false;
655 }
656 }
657
658 // Host namespace routing configuration
659 // - ingress: add route to client subnet via |host_ifname|.
660 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
661 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
662 // Note that by default unsolicited ingress traffic is not forwarded to the
663 // client namespace unless the client specifically set port forwarding
664 // through permission_broker DBus APIs.
665 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
666 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900667 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
668 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
669 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900670 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900671 RemoveInterface(nsinfo.host_ifname);
672 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900673 return false;
674 }
675
Hugo Benichi7c342672020-09-08 09:18:14 +0900676 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900677 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900678 LOG(ERROR) << "Failed to set SNAT for traffic"
679 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900680 << nsinfo.host_ifname;
681 RemoveInterface(nsinfo.host_ifname);
682 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
683 nsinfo.peer_subnet->BaseAddress(), netmask);
684 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
685 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900686 return false;
687 }
688
Hugo Benichi93306e52020-12-04 16:08:00 +0900689 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
690 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
691 nsinfo.route_on_vpn);
692
Hugo Benichi7c342672020-09-08 09:18:14 +0900693 return true;
694}
695
Hugo Benichifcf81022020-12-04 11:01:37 +0900696void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900697 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
698 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
699 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900700 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900701 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
702 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
703 nsinfo.peer_subnet->BaseAddress(),
704 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
705 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900706}
707
Hugo Benichi8d622b52020-08-13 15:24:12 +0900708void Datapath::StartRoutingDevice(const std::string& ext_ifname,
709 const std::string& int_ifname,
710 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900711 TrafficSource source,
712 bool route_on_vpn) {
713 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900714 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900715 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
716 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
717 << "->" << int_ifname;
718
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900719 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900720 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
721 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900722
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900723 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900724 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
725 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900726
Hugo Benichi2a940542020-10-26 18:50:49 +0900727 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
728 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
729 << source << " for " << int_ifname;
730
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900731 if (!ext_ifname.empty()) {
732 // If |ext_ifname| is not null, mark egress traffic with the
733 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900734 int ifindex = FindIfIndex(ext_ifname);
735 if (ifindex != 0) {
736 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
737 if (!ModifyFwmarkRoutingTag("PREROUTING", "-A", routing_mark, int_ifname))
738 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
739 << ext_ifname << "<-" << int_ifname;
740 } else {
741 // Do not abort: if the PREROUTING tagging mark cannot be
742 // set then |int_ifname| will instead be routed to the default logical
743 // network without connection pinning, aka legacy routing.
744 LOG(ERROR) << "Failed to retrieve interface index of " << ext_ifname;
745 }
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900746 } else {
747 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
748 // PREROUTING to apply any fwmark routing tag saved for the current
749 // connection, and rely on implicit routing to the default logical network
750 // otherwise.
Hugo Benichi1af52392020-11-27 18:09:32 +0900751 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname,
752 kFwmarkRoutingMask))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900753 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
754 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900755
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900756 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900757 // default network is eligible to be routed through a VPN if |route_on_vpn|
758 // is true.
759 if (route_on_vpn &&
760 !ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900761 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900762 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900763}
764
765void Datapath::StopRoutingDevice(const std::string& ext_ifname,
766 const std::string& int_ifname,
767 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900768 TrafficSource source,
769 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900770 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900771 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900772 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
773 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900774 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900775 if (!ext_ifname.empty()) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900776 Fwmark routing_mark = CachedRoutingFwmark(ext_ifname);
777 ModifyFwmarkRoutingTag("PREROUTING", "-D", routing_mark, int_ifname);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900778 } else {
Hugo Benichi1af52392020-11-27 18:09:32 +0900779 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname,
780 kFwmarkRoutingMask);
Hugo Benichi93306e52020-12-04 16:08:00 +0900781 if (route_on_vpn)
782 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900783 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900784}
785
Garrick Evansf0ab7132019-06-18 14:50:42 +0900786bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
787 const std::string& ipv4_addr) {
788 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900789 if (process_runner_->iptables(
790 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
791 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900792 return false;
793
794 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900795 if (process_runner_->iptables(
796 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
797 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900798 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
799 return false;
800 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900801 if (process_runner_->iptables(
802 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
803 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900804 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
805 return false;
806 }
807
808 return true;
809}
810
811void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
812 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900813 process_runner_->iptables(
814 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
815 "--to-destination", ipv4_addr, "-w"});
816 process_runner_->iptables(
817 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
818 "--to-destination", ipv4_addr, "-w"});
819 process_runner_->iptables(
820 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
821 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900822}
823
Hugo Benichie8758b52020-04-03 14:49:01 +0900824bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
825 return process_runner_->iptables(
826 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900827 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900828}
829
830void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
831 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900832 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900833}
834
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900835bool Datapath::AddRedirectDnsRule(const std::string& ifname,
836 const std::string dns_ipv4_addr) {
837 bool success = true;
838 success &= RemoveRedirectDnsRule(ifname);
839 // Use Insert operation to ensure that the new DNS address is used first.
840 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
841 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
842 physical_dns_addresses_[ifname] = dns_ipv4_addr;
843 return success;
844}
845
846bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
847 const auto it = physical_dns_addresses_.find(ifname);
848 if (it == physical_dns_addresses_.end())
849 return true;
850
851 bool success = true;
852 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
853 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
854 physical_dns_addresses_.erase(it);
855 return success;
856}
857
858bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
859 const std::string& protocol,
860 const std::string& ifname,
861 const std::string& dns_ipv4_addr) {
862 std::vector<std::string> args = {op,
863 kRedirectDnsChain,
864 "-p",
865 protocol,
866 "--dport",
867 "53",
868 "-o",
869 ifname,
870 "-j",
871 "DNAT",
872 "--to-destination",
873 dns_ipv4_addr,
874 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900875 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900876}
877
878bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
879 std::vector<std::string> args = {
880 op,
881 "OUTPUT",
882 "-m",
883 "mark",
884 "!",
885 "--mark",
886 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
887 "-j",
888 kRedirectDnsChain,
889 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900890 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900891}
892
Garrick Evans664a82f2019-12-17 12:18:05 +0900893bool Datapath::MaskInterfaceFlags(const std::string& ifname,
894 uint16_t on,
895 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900896 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
897 if (!sock.is_valid()) {
898 PLOG(ERROR) << "Failed to create control socket";
899 return false;
900 }
901 ifreq ifr;
902 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
903 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
904 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
905 return false;
906 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900907 ifr.ifr_flags |= on;
908 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900909 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900910 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
911 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900912 return false;
913 }
914 return true;
915}
916
Garrick Evans260ff302019-07-25 11:22:50 +0900917bool Datapath::AddIPv6HostRoute(const std::string& ifname,
918 const std::string& ipv6_addr,
919 int ipv6_prefix_len) {
920 std::string ipv6_addr_cidr =
921 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
922
Garrick Evans8e8e3472020-01-23 14:03:50 +0900923 return process_runner_->ip6("route", "replace",
924 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900925}
926
927void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
928 const std::string& ipv6_addr,
929 int ipv6_prefix_len) {
930 std::string ipv6_addr_cidr =
931 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
932
Garrick Evans8e8e3472020-01-23 14:03:50 +0900933 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900934}
935
Taoyu Lia0727dc2020-09-24 19:54:59 +0900936bool Datapath::AddIPv6Address(const std::string& ifname,
937 const std::string& ipv6_addr) {
938 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900939}
940
Taoyu Lia0727dc2020-09-24 19:54:59 +0900941void Datapath::RemoveIPv6Address(const std::string& ifname,
942 const std::string& ipv6_addr) {
943 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900944}
945
Hugo Benichi76be34a2020-08-26 22:35:54 +0900946void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900947 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +0900948 if (ifindex == 0) {
949 // Can happen if the interface has already been removed (b/183679000).
950 LOG(ERROR) << "Failed to set up connection pinning on " << ext_ifname;
951 return;
952 }
953
954 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
955 LOG(INFO) << "Start connection pinning on " << ext_ifname
956 << " fwmark=" << routing_mark.ToString();
957 if (!ModifyIptables(
958 IpFamily::Dual, "mangle",
959 {"-A", kCheckRoutingMarkChain, "-o", ext_ifname, "-m", "mark", "!",
960 "--mark",
Hugo Benichi0a110402021-03-25 11:32:52 +0900961 routing_mark.ToString() + "/" + kFwmarkRoutingMask.ToString(),
962 "-w"}))
Hugo Benichi155de002021-01-19 16:45:46 +0900963 LOG(ERROR) << "Could not set fwmark routing filter rule for " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900964 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900965 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname,
966 routing_mark))
Hugo Benichi76be34a2020-08-26 22:35:54 +0900967 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900968 // Save in CONNMARK the source tag for egress traffic of this connection.
969 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
970 kFwmarkAllSourcesMask))
971 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
972 "source tag on "
973 << ext_ifname;
974 // Restore from CONNMARK the source tag for ingress traffic of this connection
975 // (returned traffic).
976 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
977 kFwmarkAllSourcesMask))
978 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
979 "traffic received on "
980 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900981}
982
983void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900984 Fwmark routing_mark = CachedRoutingFwmark(ext_ifname);
985 LOG(INFO) << "Stop connection pinning on " << ext_ifname
986 << " fwmark=" << routing_mark.ToString();
987 if (!ModifyIptables(
988 IpFamily::Dual, "mangle",
989 {"-D", kCheckRoutingMarkChain, "-o", ext_ifname, "-m", "mark", "!",
990 "--mark",
Hugo Benichi0a110402021-03-25 11:32:52 +0900991 routing_mark.ToString() + "/" + kFwmarkRoutingMask.ToString(),
992 "-w"}))
Hugo Benichi155de002021-01-19 16:45:46 +0900993 LOG(ERROR) << "Could not remove fwmark routing filter rule for "
994 << ext_ifname;
Hugo Benichi8c526e92021-03-25 14:59:59 +0900995 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname,
996 routing_mark))
Hugo Benichi76be34a2020-08-26 22:35:54 +0900997 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900998 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
999 kFwmarkAllSourcesMask))
1000 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
1001 "fwmark source tag on "
1002 << ext_ifname;
1003 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
1004 kFwmarkAllSourcesMask))
1005 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
1006 "traffic received on "
1007 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +09001008}
1009
Hugo Benichi2a940542020-10-26 18:50:49 +09001010void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +09001011 int ifindex = FindIfIndex(vpn_ifname);
1012 if (ifindex == 0) {
1013 // Can happen if the interface has already been removed (b/183679000).
1014 LOG(ERROR) << "Failed to start VPN routing on " << vpn_ifname;
1015 return;
1016 }
1017
1018 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
1019 LOG(INFO) << "Start VPN routing on " << vpn_ifname
1020 << " fwmark=" << routing_mark.ToString();
Hugo Benichi891275e2020-12-16 10:35:34 +09001021 if (process_runner_->iptables("nat", {"-A", "POSTROUTING", "-o", vpn_ifname,
1022 "-j", "MASQUERADE", "-w"}) != 0)
1023 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +09001024 StartConnectionPinning(vpn_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +09001025 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", routing_mark, ""))
Hugo Benichi2a940542020-10-26 18:50:49 +09001026 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +09001027 if (vpn_ifname != kArcBridge)
1028 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
1029 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001030 if (!ModifyRedirectDnsJumpRule("-A"))
1031 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001032}
1033
1034void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +09001035 Fwmark routing_mark = CachedRoutingFwmark(vpn_ifname);
1036 LOG(INFO) << "Stop VPN routing on " << vpn_ifname
1037 << " fwmark=" << routing_mark.ToString();
Hugo Benichibfc49112020-12-14 12:54:44 +09001038 if (vpn_ifname != kArcBridge)
1039 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
1040 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi8c526e92021-03-25 14:59:59 +09001041 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", routing_mark, ""))
Hugo Benichi2a940542020-10-26 18:50:49 +09001042 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
1043 StopConnectionPinning(vpn_ifname);
Hugo Benichi891275e2020-12-16 10:35:34 +09001044 if (process_runner_->iptables("nat", {"-D", "POSTROUTING", "-o", vpn_ifname,
1045 "-j", "MASQUERADE", "-w"}) != 0)
1046 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001047 if (!ModifyRedirectDnsJumpRule("-D"))
1048 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001049}
1050
Hugo Benichi76be34a2020-08-26 22:35:54 +09001051bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
1052 const std::string& op,
Hugo Benichi8c526e92021-03-25 14:59:59 +09001053 const std::string& oif,
1054 Fwmark routing_mark) {
1055 return ModifyConnmarkSet(family, "POSTROUTING", op, oif, routing_mark,
1056 kFwmarkRoutingMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001057}
1058
1059bool Datapath::ModifyConnmarkSet(IpFamily family,
1060 const std::string& chain,
1061 const std::string& op,
1062 const std::string& oif,
1063 Fwmark mark,
1064 Fwmark mask) {
1065 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
1066 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
1067 return false;
1068 }
1069
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001070 std::vector<std::string> args = {op, chain};
1071 if (!oif.empty()) {
1072 args.push_back("-o");
1073 args.push_back(oif);
1074 }
1075 args.push_back("-j");
1076 args.push_back("CONNMARK");
1077 args.push_back("--set-mark");
1078 args.push_back(mark.ToString() + "/" + mask.ToString());
1079 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +09001080
Hugo Benichi58f264a2020-10-16 18:16:05 +09001081 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +09001082}
1083
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001084bool Datapath::ModifyConnmarkRestore(IpFamily family,
1085 const std::string& chain,
1086 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001087 const std::string& iif,
1088 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001089 std::vector<std::string> args = {op, chain};
1090 if (!iif.empty()) {
1091 args.push_back("-i");
1092 args.push_back(iif);
1093 }
1094 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001095 mask.ToString(), "-w"});
1096 return ModifyIptables(family, "mangle", args);
1097}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001098
Hugo Benichi1af52392020-11-27 18:09:32 +09001099bool Datapath::ModifyConnmarkSave(IpFamily family,
1100 const std::string& chain,
1101 const std::string& op,
1102 const std::string& oif,
1103 Fwmark mask) {
1104 std::vector<std::string> args = {op, chain};
1105 if (!oif.empty()) {
1106 args.push_back("-o");
1107 args.push_back(oif);
1108 }
1109 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
1110 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +09001111 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001112}
1113
Hugo Benichi2a940542020-10-26 18:50:49 +09001114bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1115 const std::string& op,
Hugo Benichi8c526e92021-03-25 14:59:59 +09001116 Fwmark routing_mark,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001117 const std::string& int_ifname) {
Hugo Benichi2a940542020-10-26 18:50:49 +09001118 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi8c526e92021-03-25 14:59:59 +09001119 0 /*classid*/, routing_mark, kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001120}
1121
Hugo Benichi9be19b12020-08-14 15:33:40 +09001122bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
1123 const std::string& iif,
1124 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001125 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001126 0 /*classid*/, Fwmark::FromSource(source),
1127 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001128}
1129
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001130bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1131 TrafficSource source) {
1132 std::vector<std::string> args = {"-A",
1133 kApplyLocalSourceMarkChain,
1134 "-m",
1135 "mark",
1136 "--mark",
1137 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1138 "-j",
1139 "MARK",
1140 "--set-mark",
1141 Fwmark::FromSource(source).ToString() + "/" +
1142 kFwmarkAllSourcesMask.ToString(),
1143 "-w"};
1144 return ModifyIptables(IpFamily::Dual, "mangle", args);
1145}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001146
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001147bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1148 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001149 if (std::string(source.uid_name).empty() && source.classid == 0)
1150 return false;
1151
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001152 Fwmark mark = Fwmark::FromSource(source.source_type);
1153 if (source.is_on_vpn)
1154 mark = mark | kFwmarkRouteOnVpn;
1155
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001156 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1157 "" /*iif*/, source.uid_name, source.classid, mark,
1158 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001159}
1160
1161bool Datapath::ModifyFwmark(IpFamily family,
1162 const std::string& chain,
1163 const std::string& op,
1164 const std::string& iif,
1165 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001166 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001167 Fwmark mark,
1168 Fwmark mask,
1169 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001170 std::vector<std::string> args = {op, chain};
1171 if (!iif.empty()) {
1172 args.push_back("-i");
1173 args.push_back(iif);
1174 }
1175 if (!uid_name.empty()) {
1176 args.push_back("-m");
1177 args.push_back("owner");
1178 args.push_back("--uid-owner");
1179 args.push_back(uid_name);
1180 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001181 if (classid != 0) {
1182 args.push_back("-m");
1183 args.push_back("cgroup");
1184 args.push_back("--cgroup");
1185 args.push_back(base::StringPrintf("0x%08x", classid));
1186 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001187 args.push_back("-j");
1188 args.push_back("MARK");
1189 args.push_back("--set-mark");
1190 args.push_back(mark.ToString() + "/" + mask.ToString());
1191 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001192
Hugo Benichi58f264a2020-10-16 18:16:05 +09001193 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001194}
1195
Hugo Benichid82d8832020-08-14 10:05:03 +09001196bool Datapath::ModifyIpForwarding(IpFamily family,
1197 const std::string& op,
1198 const std::string& iif,
1199 const std::string& oif,
1200 bool log_failures) {
1201 if (iif.empty() && oif.empty()) {
1202 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1203 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001204 return false;
1205 }
1206
Hugo Benichid82d8832020-08-14 10:05:03 +09001207 std::vector<std::string> args = {op, "FORWARD"};
1208 if (!iif.empty()) {
1209 args.push_back("-i");
1210 args.push_back(iif);
1211 }
1212 if (!oif.empty()) {
1213 args.push_back("-o");
1214 args.push_back(oif);
1215 }
1216 args.push_back("-j");
1217 args.push_back("ACCEPT");
1218 args.push_back("-w");
1219
Hugo Benichi58f264a2020-10-16 18:16:05 +09001220 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001221}
1222
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001223bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1224 const std::string& op,
1225 const std::string& iif,
1226 Fwmark mark,
1227 Fwmark mask) {
1228 std::vector<std::string> args = {op, chain};
1229 if (!iif.empty()) {
1230 args.push_back("-i");
1231 args.push_back(iif);
1232 }
1233 if (mark.Value() != 0 && mask.Value() != 0) {
1234 args.push_back("-m");
1235 args.push_back("mark");
1236 args.push_back("--mark");
1237 args.push_back(mark.ToString() + "/" + mask.ToString());
1238 }
1239 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1240 return ModifyIptables(IpFamily::Dual, "mangle", args);
1241}
1242
1243bool Datapath::ModifyChain(IpFamily family,
1244 const std::string& table,
1245 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001246 const std::string& chain,
1247 bool log_failures) {
1248 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001249}
1250
1251bool Datapath::ModifyIptables(IpFamily family,
1252 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001253 const std::vector<std::string>& argv,
1254 bool log_failures) {
1255 switch (family) {
1256 case IPv4:
1257 case IPv6:
1258 case Dual:
1259 break;
1260 default:
1261 LOG(ERROR) << "Could not execute iptables command " << table
1262 << base::JoinString(argv, " ") << ": incorrect IP family "
1263 << family;
1264 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001265 }
1266
1267 bool success = true;
1268 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001269 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001270 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001271 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001272 return success;
1273}
1274
Hugo Benichid82d8832020-08-14 10:05:03 +09001275bool Datapath::StartIpForwarding(IpFamily family,
1276 const std::string& iif,
1277 const std::string& oif) {
1278 return ModifyIpForwarding(family, "-A", iif, oif);
1279}
1280
1281bool Datapath::StopIpForwarding(IpFamily family,
1282 const std::string& iif,
1283 const std::string& oif) {
1284 return ModifyIpForwarding(family, "-D", iif, oif);
1285}
1286
1287bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1288 const std::string& ifname2) {
1289 // Only start Ipv6 forwarding if -C returns false and it had not been
1290 // started yet.
1291 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1292 false /*log_failures*/) &&
1293 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1294 return false;
1295 }
1296
1297 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1298 false /*log_failures*/) &&
1299 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001300 RemoveIPv6Forwarding(ifname1, ifname2);
1301 return false;
1302 }
1303
1304 return true;
1305}
1306
1307void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1308 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001309 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1310 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001311}
1312
Garrick Evans3d97a392020-02-21 15:24:37 +09001313bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1314 uint32_t addr,
1315 uint32_t netmask) {
1316 struct rtentry route;
1317 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001318 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1319 SetSockaddrIn(&route.rt_dst, addr & netmask);
1320 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001321 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001322 return ModifyRtentry(SIOCADDRT, &route);
1323}
Garrick Evans3d97a392020-02-21 15:24:37 +09001324
Hugo Benichie8758b52020-04-03 14:49:01 +09001325bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1326 uint32_t addr,
1327 uint32_t netmask) {
1328 struct rtentry route;
1329 memset(&route, 0, sizeof(route));
1330 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1331 SetSockaddrIn(&route.rt_dst, addr & netmask);
1332 SetSockaddrIn(&route.rt_genmask, netmask);
1333 route.rt_flags = RTF_UP | RTF_GATEWAY;
1334 return ModifyRtentry(SIOCDELRT, &route);
1335}
1336
1337bool Datapath::AddIPv4Route(const std::string& ifname,
1338 uint32_t addr,
1339 uint32_t netmask) {
1340 struct rtentry route;
1341 memset(&route, 0, sizeof(route));
1342 SetSockaddrIn(&route.rt_dst, addr & netmask);
1343 SetSockaddrIn(&route.rt_genmask, netmask);
1344 char rt_dev[IFNAMSIZ];
1345 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1346 rt_dev[IFNAMSIZ - 1] = '\0';
1347 route.rt_dev = rt_dev;
1348 route.rt_flags = RTF_UP | RTF_GATEWAY;
1349 return ModifyRtentry(SIOCADDRT, &route);
1350}
1351
1352bool Datapath::DeleteIPv4Route(const std::string& ifname,
1353 uint32_t addr,
1354 uint32_t netmask) {
1355 struct rtentry route;
1356 memset(&route, 0, sizeof(route));
1357 SetSockaddrIn(&route.rt_dst, addr & netmask);
1358 SetSockaddrIn(&route.rt_genmask, netmask);
1359 char rt_dev[IFNAMSIZ];
1360 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1361 rt_dev[IFNAMSIZ - 1] = '\0';
1362 route.rt_dev = rt_dev;
1363 route.rt_flags = RTF_UP | RTF_GATEWAY;
1364 return ModifyRtentry(SIOCDELRT, &route);
1365}
1366
Taoyu Lia0727dc2020-09-24 19:54:59 +09001367bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001368 DCHECK(route);
1369 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001370 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001371 return false;
1372 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001373 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1374 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001375 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001376 return false;
1377 }
1378 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1379 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001380 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001381 return false;
1382 }
1383 return true;
1384}
1385
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001386bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1387 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1388 kArcAddr, kAdbServerPort, ifname,
1389 kLocalhostAddr, kAdbProxyTcpListenPort);
1390}
1391
1392void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1393 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1394 kArcAddr, kAdbServerPort, ifname,
1395 kLocalhostAddr, kAdbProxyTcpListenPort);
1396}
1397
1398bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1399 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1400 kAdbProxyTcpListenPort, ifname);
1401}
1402
1403void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1404 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1405 kAdbProxyTcpListenPort, ifname);
1406}
1407
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001408void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1409 if_nametoindex_[ifname] = ifindex;
1410}
1411
1412int Datapath::FindIfIndex(const std::string& ifname) {
1413 uint32_t ifindex = if_nametoindex(ifname.c_str());
1414 if (ifindex > 0) {
1415 if_nametoindex_[ifname] = ifindex;
1416 return ifindex;
1417 }
1418
1419 const auto it = if_nametoindex_.find(ifname);
1420 if (it != if_nametoindex_.end())
1421 return it->second;
1422
1423 return 0;
1424}
1425
Hugo Benichi8c526e92021-03-25 14:59:59 +09001426Fwmark Datapath::CachedRoutingFwmark(const std::string& ifname) {
1427 const auto it = if_nametoindex_.find(ifname);
1428 if (it != if_nametoindex_.end())
1429 return Fwmark::FromIfIndex(it->second);
1430
1431 LOG(WARNING) << "No interface index known for " << ifname;
1432 return Fwmark();
1433}
1434
Hugo Benichifcf81022020-12-04 11:01:37 +09001435std::ostream& operator<<(std::ostream& stream,
1436 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001437 stream << "{ pid: " << nsinfo.pid
1438 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001439 if (!nsinfo.outbound_ifname.empty()) {
1440 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1441 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001442 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1443 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001444 << ", peer_ifname: " << nsinfo.peer_ifname
1445 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1446 return stream;
1447}
1448
Garrick Evans3388a032020-03-24 11:25:55 +09001449} // namespace patchpanel