blob: eb5f5b042b241e5a2bb912911d6599a454279877 [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",
961 routing_mark.ToString() + "/" + kFwmarkRoutingMask.ToString(), "-j",
962 "DROP", "-w"}))
Hugo Benichi155de002021-01-19 16:45:46 +0900963 LOG(ERROR) << "Could not set fwmark routing filter rule for " << ext_ifname;
964
Hugo Benichi1af52392020-11-27 18:09:32 +0900965 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900966 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname,
967 routing_mark))
Hugo Benichi76be34a2020-08-26 22:35:54 +0900968 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900969 // Save in CONNMARK the source tag for egress traffic of this connection.
970 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
971 kFwmarkAllSourcesMask))
972 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
973 "source tag on "
974 << ext_ifname;
975 // Restore from CONNMARK the source tag for ingress traffic of this connection
976 // (returned traffic).
977 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
978 kFwmarkAllSourcesMask))
979 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
980 "traffic received on "
981 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900982}
983
984void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900985 Fwmark routing_mark = CachedRoutingFwmark(ext_ifname);
986 LOG(INFO) << "Stop connection pinning on " << ext_ifname
987 << " fwmark=" << routing_mark.ToString();
988 if (!ModifyIptables(
989 IpFamily::Dual, "mangle",
990 {"-D", kCheckRoutingMarkChain, "-o", ext_ifname, "-m", "mark", "!",
991 "--mark",
992 routing_mark.ToString() + "/" + kFwmarkRoutingMask.ToString(), "-j",
993 "DROP", "-w"}))
Hugo Benichi155de002021-01-19 16:45:46 +0900994 LOG(ERROR) << "Could not remove fwmark routing filter rule for "
995 << ext_ifname;
Hugo Benichi8c526e92021-03-25 14:59:59 +0900996 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname,
997 routing_mark))
Hugo Benichi76be34a2020-08-26 22:35:54 +0900998 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900999 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
1000 kFwmarkAllSourcesMask))
1001 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
1002 "fwmark source tag on "
1003 << ext_ifname;
1004 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
1005 kFwmarkAllSourcesMask))
1006 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
1007 "traffic received on "
1008 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +09001009}
1010
Hugo Benichi2a940542020-10-26 18:50:49 +09001011void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +09001012 int ifindex = FindIfIndex(vpn_ifname);
1013 if (ifindex == 0) {
1014 // Can happen if the interface has already been removed (b/183679000).
1015 LOG(ERROR) << "Failed to start VPN routing on " << vpn_ifname;
1016 return;
1017 }
1018
1019 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
1020 LOG(INFO) << "Start VPN routing on " << vpn_ifname
1021 << " fwmark=" << routing_mark.ToString();
Hugo Benichi891275e2020-12-16 10:35:34 +09001022 if (process_runner_->iptables("nat", {"-A", "POSTROUTING", "-o", vpn_ifname,
1023 "-j", "MASQUERADE", "-w"}) != 0)
1024 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +09001025 StartConnectionPinning(vpn_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +09001026 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", routing_mark, ""))
Hugo Benichi2a940542020-10-26 18:50:49 +09001027 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +09001028 if (vpn_ifname != kArcBridge)
1029 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
1030 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001031 if (!ModifyRedirectDnsJumpRule("-A"))
1032 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001033}
1034
1035void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +09001036 Fwmark routing_mark = CachedRoutingFwmark(vpn_ifname);
1037 LOG(INFO) << "Stop VPN routing on " << vpn_ifname
1038 << " fwmark=" << routing_mark.ToString();
Hugo Benichibfc49112020-12-14 12:54:44 +09001039 if (vpn_ifname != kArcBridge)
1040 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
1041 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi8c526e92021-03-25 14:59:59 +09001042 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", routing_mark, ""))
Hugo Benichi2a940542020-10-26 18:50:49 +09001043 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
1044 StopConnectionPinning(vpn_ifname);
Hugo Benichi891275e2020-12-16 10:35:34 +09001045 if (process_runner_->iptables("nat", {"-D", "POSTROUTING", "-o", vpn_ifname,
1046 "-j", "MASQUERADE", "-w"}) != 0)
1047 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001048 if (!ModifyRedirectDnsJumpRule("-D"))
1049 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001050}
1051
Hugo Benichi76be34a2020-08-26 22:35:54 +09001052bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
1053 const std::string& op,
Hugo Benichi8c526e92021-03-25 14:59:59 +09001054 const std::string& oif,
1055 Fwmark routing_mark) {
1056 return ModifyConnmarkSet(family, "POSTROUTING", op, oif, routing_mark,
1057 kFwmarkRoutingMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001058}
1059
1060bool Datapath::ModifyConnmarkSet(IpFamily family,
1061 const std::string& chain,
1062 const std::string& op,
1063 const std::string& oif,
1064 Fwmark mark,
1065 Fwmark mask) {
1066 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
1067 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
1068 return false;
1069 }
1070
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001071 std::vector<std::string> args = {op, chain};
1072 if (!oif.empty()) {
1073 args.push_back("-o");
1074 args.push_back(oif);
1075 }
1076 args.push_back("-j");
1077 args.push_back("CONNMARK");
1078 args.push_back("--set-mark");
1079 args.push_back(mark.ToString() + "/" + mask.ToString());
1080 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +09001081
Hugo Benichi58f264a2020-10-16 18:16:05 +09001082 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +09001083}
1084
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001085bool Datapath::ModifyConnmarkRestore(IpFamily family,
1086 const std::string& chain,
1087 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001088 const std::string& iif,
1089 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001090 std::vector<std::string> args = {op, chain};
1091 if (!iif.empty()) {
1092 args.push_back("-i");
1093 args.push_back(iif);
1094 }
1095 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001096 mask.ToString(), "-w"});
1097 return ModifyIptables(family, "mangle", args);
1098}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001099
Hugo Benichi1af52392020-11-27 18:09:32 +09001100bool Datapath::ModifyConnmarkSave(IpFamily family,
1101 const std::string& chain,
1102 const std::string& op,
1103 const std::string& oif,
1104 Fwmark mask) {
1105 std::vector<std::string> args = {op, chain};
1106 if (!oif.empty()) {
1107 args.push_back("-o");
1108 args.push_back(oif);
1109 }
1110 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
1111 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +09001112 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001113}
1114
Hugo Benichi2a940542020-10-26 18:50:49 +09001115bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1116 const std::string& op,
Hugo Benichi8c526e92021-03-25 14:59:59 +09001117 Fwmark routing_mark,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001118 const std::string& int_ifname) {
Hugo Benichi2a940542020-10-26 18:50:49 +09001119 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi8c526e92021-03-25 14:59:59 +09001120 0 /*classid*/, routing_mark, kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001121}
1122
Hugo Benichi9be19b12020-08-14 15:33:40 +09001123bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
1124 const std::string& iif,
1125 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001126 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001127 0 /*classid*/, Fwmark::FromSource(source),
1128 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001129}
1130
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001131bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1132 TrafficSource source) {
1133 std::vector<std::string> args = {"-A",
1134 kApplyLocalSourceMarkChain,
1135 "-m",
1136 "mark",
1137 "--mark",
1138 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1139 "-j",
1140 "MARK",
1141 "--set-mark",
1142 Fwmark::FromSource(source).ToString() + "/" +
1143 kFwmarkAllSourcesMask.ToString(),
1144 "-w"};
1145 return ModifyIptables(IpFamily::Dual, "mangle", args);
1146}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001147
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001148bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1149 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001150 if (std::string(source.uid_name).empty() && source.classid == 0)
1151 return false;
1152
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001153 Fwmark mark = Fwmark::FromSource(source.source_type);
1154 if (source.is_on_vpn)
1155 mark = mark | kFwmarkRouteOnVpn;
1156
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001157 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1158 "" /*iif*/, source.uid_name, source.classid, mark,
1159 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001160}
1161
1162bool Datapath::ModifyFwmark(IpFamily family,
1163 const std::string& chain,
1164 const std::string& op,
1165 const std::string& iif,
1166 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001167 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001168 Fwmark mark,
1169 Fwmark mask,
1170 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001171 std::vector<std::string> args = {op, chain};
1172 if (!iif.empty()) {
1173 args.push_back("-i");
1174 args.push_back(iif);
1175 }
1176 if (!uid_name.empty()) {
1177 args.push_back("-m");
1178 args.push_back("owner");
1179 args.push_back("--uid-owner");
1180 args.push_back(uid_name);
1181 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001182 if (classid != 0) {
1183 args.push_back("-m");
1184 args.push_back("cgroup");
1185 args.push_back("--cgroup");
1186 args.push_back(base::StringPrintf("0x%08x", classid));
1187 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001188 args.push_back("-j");
1189 args.push_back("MARK");
1190 args.push_back("--set-mark");
1191 args.push_back(mark.ToString() + "/" + mask.ToString());
1192 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001193
Hugo Benichi58f264a2020-10-16 18:16:05 +09001194 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001195}
1196
Hugo Benichid82d8832020-08-14 10:05:03 +09001197bool Datapath::ModifyIpForwarding(IpFamily family,
1198 const std::string& op,
1199 const std::string& iif,
1200 const std::string& oif,
1201 bool log_failures) {
1202 if (iif.empty() && oif.empty()) {
1203 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1204 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001205 return false;
1206 }
1207
Hugo Benichid82d8832020-08-14 10:05:03 +09001208 std::vector<std::string> args = {op, "FORWARD"};
1209 if (!iif.empty()) {
1210 args.push_back("-i");
1211 args.push_back(iif);
1212 }
1213 if (!oif.empty()) {
1214 args.push_back("-o");
1215 args.push_back(oif);
1216 }
1217 args.push_back("-j");
1218 args.push_back("ACCEPT");
1219 args.push_back("-w");
1220
Hugo Benichi58f264a2020-10-16 18:16:05 +09001221 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001222}
1223
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001224bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1225 const std::string& op,
1226 const std::string& iif,
1227 Fwmark mark,
1228 Fwmark mask) {
1229 std::vector<std::string> args = {op, chain};
1230 if (!iif.empty()) {
1231 args.push_back("-i");
1232 args.push_back(iif);
1233 }
1234 if (mark.Value() != 0 && mask.Value() != 0) {
1235 args.push_back("-m");
1236 args.push_back("mark");
1237 args.push_back("--mark");
1238 args.push_back(mark.ToString() + "/" + mask.ToString());
1239 }
1240 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1241 return ModifyIptables(IpFamily::Dual, "mangle", args);
1242}
1243
1244bool Datapath::ModifyChain(IpFamily family,
1245 const std::string& table,
1246 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001247 const std::string& chain,
1248 bool log_failures) {
1249 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001250}
1251
1252bool Datapath::ModifyIptables(IpFamily family,
1253 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001254 const std::vector<std::string>& argv,
1255 bool log_failures) {
1256 switch (family) {
1257 case IPv4:
1258 case IPv6:
1259 case Dual:
1260 break;
1261 default:
1262 LOG(ERROR) << "Could not execute iptables command " << table
1263 << base::JoinString(argv, " ") << ": incorrect IP family "
1264 << family;
1265 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001266 }
1267
1268 bool success = true;
1269 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001270 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001271 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001272 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001273 return success;
1274}
1275
Hugo Benichid82d8832020-08-14 10:05:03 +09001276bool Datapath::StartIpForwarding(IpFamily family,
1277 const std::string& iif,
1278 const std::string& oif) {
1279 return ModifyIpForwarding(family, "-A", iif, oif);
1280}
1281
1282bool Datapath::StopIpForwarding(IpFamily family,
1283 const std::string& iif,
1284 const std::string& oif) {
1285 return ModifyIpForwarding(family, "-D", iif, oif);
1286}
1287
1288bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1289 const std::string& ifname2) {
1290 // Only start Ipv6 forwarding if -C returns false and it had not been
1291 // started yet.
1292 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1293 false /*log_failures*/) &&
1294 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1295 return false;
1296 }
1297
1298 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1299 false /*log_failures*/) &&
1300 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001301 RemoveIPv6Forwarding(ifname1, ifname2);
1302 return false;
1303 }
1304
1305 return true;
1306}
1307
1308void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1309 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001310 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1311 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001312}
1313
Garrick Evans3d97a392020-02-21 15:24:37 +09001314bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1315 uint32_t addr,
1316 uint32_t netmask) {
1317 struct rtentry route;
1318 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001319 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1320 SetSockaddrIn(&route.rt_dst, addr & netmask);
1321 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001322 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001323 return ModifyRtentry(SIOCADDRT, &route);
1324}
Garrick Evans3d97a392020-02-21 15:24:37 +09001325
Hugo Benichie8758b52020-04-03 14:49:01 +09001326bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1327 uint32_t addr,
1328 uint32_t netmask) {
1329 struct rtentry route;
1330 memset(&route, 0, sizeof(route));
1331 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1332 SetSockaddrIn(&route.rt_dst, addr & netmask);
1333 SetSockaddrIn(&route.rt_genmask, netmask);
1334 route.rt_flags = RTF_UP | RTF_GATEWAY;
1335 return ModifyRtentry(SIOCDELRT, &route);
1336}
1337
1338bool Datapath::AddIPv4Route(const std::string& ifname,
1339 uint32_t addr,
1340 uint32_t netmask) {
1341 struct rtentry route;
1342 memset(&route, 0, sizeof(route));
1343 SetSockaddrIn(&route.rt_dst, addr & netmask);
1344 SetSockaddrIn(&route.rt_genmask, netmask);
1345 char rt_dev[IFNAMSIZ];
1346 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1347 rt_dev[IFNAMSIZ - 1] = '\0';
1348 route.rt_dev = rt_dev;
1349 route.rt_flags = RTF_UP | RTF_GATEWAY;
1350 return ModifyRtentry(SIOCADDRT, &route);
1351}
1352
1353bool Datapath::DeleteIPv4Route(const std::string& ifname,
1354 uint32_t addr,
1355 uint32_t netmask) {
1356 struct rtentry route;
1357 memset(&route, 0, sizeof(route));
1358 SetSockaddrIn(&route.rt_dst, addr & netmask);
1359 SetSockaddrIn(&route.rt_genmask, netmask);
1360 char rt_dev[IFNAMSIZ];
1361 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1362 rt_dev[IFNAMSIZ - 1] = '\0';
1363 route.rt_dev = rt_dev;
1364 route.rt_flags = RTF_UP | RTF_GATEWAY;
1365 return ModifyRtentry(SIOCDELRT, &route);
1366}
1367
Taoyu Lia0727dc2020-09-24 19:54:59 +09001368bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001369 DCHECK(route);
1370 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001371 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001372 return false;
1373 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001374 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1375 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001376 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001377 return false;
1378 }
1379 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1380 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001381 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001382 return false;
1383 }
1384 return true;
1385}
1386
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001387bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1388 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1389 kArcAddr, kAdbServerPort, ifname,
1390 kLocalhostAddr, kAdbProxyTcpListenPort);
1391}
1392
1393void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1394 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1395 kArcAddr, kAdbServerPort, ifname,
1396 kLocalhostAddr, kAdbProxyTcpListenPort);
1397}
1398
1399bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1400 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1401 kAdbProxyTcpListenPort, ifname);
1402}
1403
1404void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1405 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1406 kAdbProxyTcpListenPort, ifname);
1407}
1408
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001409void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1410 if_nametoindex_[ifname] = ifindex;
1411}
1412
1413int Datapath::FindIfIndex(const std::string& ifname) {
1414 uint32_t ifindex = if_nametoindex(ifname.c_str());
1415 if (ifindex > 0) {
1416 if_nametoindex_[ifname] = ifindex;
1417 return ifindex;
1418 }
1419
1420 const auto it = if_nametoindex_.find(ifname);
1421 if (it != if_nametoindex_.end())
1422 return it->second;
1423
1424 return 0;
1425}
1426
Hugo Benichi8c526e92021-03-25 14:59:59 +09001427Fwmark Datapath::CachedRoutingFwmark(const std::string& ifname) {
1428 const auto it = if_nametoindex_.find(ifname);
1429 if (it != if_nametoindex_.end())
1430 return Fwmark::FromIfIndex(it->second);
1431
1432 LOG(WARNING) << "No interface index known for " << ifname;
1433 return Fwmark();
1434}
1435
Hugo Benichifcf81022020-12-04 11:01:37 +09001436std::ostream& operator<<(std::ostream& stream,
1437 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001438 stream << "{ pid: " << nsinfo.pid
1439 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001440 if (!nsinfo.outbound_ifname.empty()) {
1441 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1442 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001443 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1444 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001445 << ", peer_ifname: " << nsinfo.peer_ifname
1446 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1447 return stream;
1448}
1449
Garrick Evans3388a032020-03-24 11:25:55 +09001450} // namespace patchpanel