blob: a43d968e396872ee34a64de84a888c891eb82851 [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 Benichi2a940542020-10-26 18:50:49 +0900734 if (!ModifyFwmarkRoutingTag("PREROUTING", "-A", ext_ifname, int_ifname))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900735 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
736 << ext_ifname << "<-" << int_ifname;
737 } else {
738 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
739 // PREROUTING to apply any fwmark routing tag saved for the current
740 // connection, and rely on implicit routing to the default logical network
741 // otherwise.
Hugo Benichi1af52392020-11-27 18:09:32 +0900742 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname,
743 kFwmarkRoutingMask))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900744 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
745 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900746
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900747 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900748 // default network is eligible to be routed through a VPN if |route_on_vpn|
749 // is true.
750 if (route_on_vpn &&
751 !ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900752 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900753 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900754}
755
756void Datapath::StopRoutingDevice(const std::string& ext_ifname,
757 const std::string& int_ifname,
758 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900759 TrafficSource source,
760 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900761 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900762 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900763 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
764 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900765 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900766 if (!ext_ifname.empty()) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900767 ModifyFwmarkRoutingTag("PREROUTING", "-D", ext_ifname, int_ifname);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900768 } else {
Hugo Benichi1af52392020-11-27 18:09:32 +0900769 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname,
770 kFwmarkRoutingMask);
Hugo Benichi93306e52020-12-04 16:08:00 +0900771 if (route_on_vpn)
772 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900773 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900774}
775
Garrick Evansf0ab7132019-06-18 14:50:42 +0900776bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
777 const std::string& ipv4_addr) {
778 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900779 if (process_runner_->iptables(
780 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
781 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900782 return false;
783
784 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900785 if (process_runner_->iptables(
786 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
787 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900788 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
789 return false;
790 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900791 if (process_runner_->iptables(
792 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
793 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900794 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
795 return false;
796 }
797
798 return true;
799}
800
801void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
802 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900803 process_runner_->iptables(
804 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
805 "--to-destination", ipv4_addr, "-w"});
806 process_runner_->iptables(
807 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
808 "--to-destination", ipv4_addr, "-w"});
809 process_runner_->iptables(
810 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
811 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900812}
813
Hugo Benichie8758b52020-04-03 14:49:01 +0900814bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
815 return process_runner_->iptables(
816 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900817 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900818}
819
820void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
821 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900822 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900823}
824
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900825bool Datapath::AddRedirectDnsRule(const std::string& ifname,
826 const std::string dns_ipv4_addr) {
827 bool success = true;
828 success &= RemoveRedirectDnsRule(ifname);
829 // Use Insert operation to ensure that the new DNS address is used first.
830 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
831 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
832 physical_dns_addresses_[ifname] = dns_ipv4_addr;
833 return success;
834}
835
836bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
837 const auto it = physical_dns_addresses_.find(ifname);
838 if (it == physical_dns_addresses_.end())
839 return true;
840
841 bool success = true;
842 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
843 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
844 physical_dns_addresses_.erase(it);
845 return success;
846}
847
848bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
849 const std::string& protocol,
850 const std::string& ifname,
851 const std::string& dns_ipv4_addr) {
852 std::vector<std::string> args = {op,
853 kRedirectDnsChain,
854 "-p",
855 protocol,
856 "--dport",
857 "53",
858 "-o",
859 ifname,
860 "-j",
861 "DNAT",
862 "--to-destination",
863 dns_ipv4_addr,
864 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900865 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900866}
867
868bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
869 std::vector<std::string> args = {
870 op,
871 "OUTPUT",
872 "-m",
873 "mark",
874 "!",
875 "--mark",
876 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
877 "-j",
878 kRedirectDnsChain,
879 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900880 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900881}
882
Garrick Evans664a82f2019-12-17 12:18:05 +0900883bool Datapath::MaskInterfaceFlags(const std::string& ifname,
884 uint16_t on,
885 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900886 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
887 if (!sock.is_valid()) {
888 PLOG(ERROR) << "Failed to create control socket";
889 return false;
890 }
891 ifreq ifr;
892 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
893 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
894 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
895 return false;
896 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900897 ifr.ifr_flags |= on;
898 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900899 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900900 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
901 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900902 return false;
903 }
904 return true;
905}
906
Garrick Evans260ff302019-07-25 11:22:50 +0900907bool Datapath::AddIPv6HostRoute(const std::string& ifname,
908 const std::string& ipv6_addr,
909 int ipv6_prefix_len) {
910 std::string ipv6_addr_cidr =
911 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
912
Garrick Evans8e8e3472020-01-23 14:03:50 +0900913 return process_runner_->ip6("route", "replace",
914 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900915}
916
917void Datapath::RemoveIPv6HostRoute(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 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900924}
925
Taoyu Lia0727dc2020-09-24 19:54:59 +0900926bool Datapath::AddIPv6Address(const std::string& ifname,
927 const std::string& ipv6_addr) {
928 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900929}
930
Taoyu Lia0727dc2020-09-24 19:54:59 +0900931void Datapath::RemoveIPv6Address(const std::string& ifname,
932 const std::string& ipv6_addr) {
933 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900934}
935
Hugo Benichi76be34a2020-08-26 22:35:54 +0900936void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900937 int ifindex = FindIfIndex(ext_ifname);
938 if (ifindex != 0 && !ModifyIptables(IpFamily::Dual, "mangle",
939 {"-A", kCheckRoutingMarkChain, "-o",
940 ext_ifname, "-m", "mark", "!", "--mark",
941 Fwmark::FromIfIndex(ifindex).ToString() +
942 "/" + kFwmarkRoutingMask.ToString(),
943 "-j", "DROP", "-w"}))
944 LOG(ERROR) << "Could not set fwmark routing filter rule for " << ext_ifname;
945
Hugo Benichi1af52392020-11-27 18:09:32 +0900946 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi76be34a2020-08-26 22:35:54 +0900947 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
948 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900949 // Save in CONNMARK the source tag for egress traffic of this connection.
950 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
951 kFwmarkAllSourcesMask))
952 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
953 "source tag on "
954 << ext_ifname;
955 // Restore from CONNMARK the source tag for ingress traffic of this connection
956 // (returned traffic).
957 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
958 kFwmarkAllSourcesMask))
959 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
960 "traffic received on "
961 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900962}
963
964void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900965 int ifindex = FindIfIndex(ext_ifname);
966 if (ifindex != 0 && !ModifyIptables(IpFamily::Dual, "mangle",
967 {"-D", kCheckRoutingMarkChain, "-o",
968 ext_ifname, "-m", "mark", "!", "--mark",
969 Fwmark::FromIfIndex(ifindex).ToString() +
970 "/" + kFwmarkRoutingMask.ToString(),
971 "-j", "DROP", "-w"}))
972 LOG(ERROR) << "Could not remove fwmark routing filter rule for "
973 << ext_ifname;
974
Hugo Benichi76be34a2020-08-26 22:35:54 +0900975 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
976 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900977 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
978 kFwmarkAllSourcesMask))
979 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
980 "fwmark source tag on "
981 << ext_ifname;
982 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
983 kFwmarkAllSourcesMask))
984 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
985 "traffic received on "
986 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900987}
988
Hugo Benichi2a940542020-10-26 18:50:49 +0900989void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi891275e2020-12-16 10:35:34 +0900990 if (process_runner_->iptables("nat", {"-A", "POSTROUTING", "-o", vpn_ifname,
991 "-j", "MASQUERADE", "-w"}) != 0)
992 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900993 StartConnectionPinning(vpn_ifname);
994 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", vpn_ifname, ""))
995 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +0900996 if (vpn_ifname != kArcBridge)
997 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
998 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900999 if (!ModifyRedirectDnsJumpRule("-A"))
1000 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001001}
1002
1003void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichibfc49112020-12-14 12:54:44 +09001004 if (vpn_ifname != kArcBridge)
1005 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
1006 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi2a940542020-10-26 18:50:49 +09001007 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", vpn_ifname, ""))
1008 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
1009 StopConnectionPinning(vpn_ifname);
Hugo Benichi891275e2020-12-16 10:35:34 +09001010 if (process_runner_->iptables("nat", {"-D", "POSTROUTING", "-o", vpn_ifname,
1011 "-j", "MASQUERADE", "-w"}) != 0)
1012 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001013 if (!ModifyRedirectDnsJumpRule("-D"))
1014 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001015}
1016
Hugo Benichi76be34a2020-08-26 22:35:54 +09001017bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
1018 const std::string& op,
1019 const std::string& oif) {
Hugo Benichi76be34a2020-08-26 22:35:54 +09001020 int ifindex = FindIfIndex(oif);
1021 if (ifindex == 0) {
1022 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
1023 return false;
1024 }
1025
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001026 return ModifyConnmarkSet(family, "POSTROUTING", op, oif,
1027 Fwmark::FromIfIndex(ifindex), kFwmarkRoutingMask);
1028}
1029
1030bool Datapath::ModifyConnmarkSet(IpFamily family,
1031 const std::string& chain,
1032 const std::string& op,
1033 const std::string& oif,
1034 Fwmark mark,
1035 Fwmark mask) {
1036 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
1037 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
1038 return false;
1039 }
1040
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001041 std::vector<std::string> args = {op, chain};
1042 if (!oif.empty()) {
1043 args.push_back("-o");
1044 args.push_back(oif);
1045 }
1046 args.push_back("-j");
1047 args.push_back("CONNMARK");
1048 args.push_back("--set-mark");
1049 args.push_back(mark.ToString() + "/" + mask.ToString());
1050 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +09001051
Hugo Benichi58f264a2020-10-16 18:16:05 +09001052 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +09001053}
1054
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001055bool Datapath::ModifyConnmarkRestore(IpFamily family,
1056 const std::string& chain,
1057 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001058 const std::string& iif,
1059 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001060 std::vector<std::string> args = {op, chain};
1061 if (!iif.empty()) {
1062 args.push_back("-i");
1063 args.push_back(iif);
1064 }
1065 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001066 mask.ToString(), "-w"});
1067 return ModifyIptables(family, "mangle", args);
1068}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001069
Hugo Benichi1af52392020-11-27 18:09:32 +09001070bool Datapath::ModifyConnmarkSave(IpFamily family,
1071 const std::string& chain,
1072 const std::string& op,
1073 const std::string& oif,
1074 Fwmark mask) {
1075 std::vector<std::string> args = {op, chain};
1076 if (!oif.empty()) {
1077 args.push_back("-o");
1078 args.push_back(oif);
1079 }
1080 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
1081 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +09001082 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001083}
1084
Hugo Benichi2a940542020-10-26 18:50:49 +09001085bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1086 const std::string& op,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001087 const std::string& ext_ifname,
1088 const std::string& int_ifname) {
1089 int ifindex = FindIfIndex(ext_ifname);
1090 if (ifindex == 0) {
1091 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
1092 return false;
1093 }
1094
Hugo Benichi2a940542020-10-26 18:50:49 +09001095 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001096 0 /*classid*/, Fwmark::FromIfIndex(ifindex),
1097 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001098}
1099
Hugo Benichi9be19b12020-08-14 15:33:40 +09001100bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
1101 const std::string& iif,
1102 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001103 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001104 0 /*classid*/, Fwmark::FromSource(source),
1105 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001106}
1107
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001108bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1109 TrafficSource source) {
1110 std::vector<std::string> args = {"-A",
1111 kApplyLocalSourceMarkChain,
1112 "-m",
1113 "mark",
1114 "--mark",
1115 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1116 "-j",
1117 "MARK",
1118 "--set-mark",
1119 Fwmark::FromSource(source).ToString() + "/" +
1120 kFwmarkAllSourcesMask.ToString(),
1121 "-w"};
1122 return ModifyIptables(IpFamily::Dual, "mangle", args);
1123}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001124
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001125bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1126 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001127 if (std::string(source.uid_name).empty() && source.classid == 0)
1128 return false;
1129
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001130 Fwmark mark = Fwmark::FromSource(source.source_type);
1131 if (source.is_on_vpn)
1132 mark = mark | kFwmarkRouteOnVpn;
1133
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001134 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1135 "" /*iif*/, source.uid_name, source.classid, mark,
1136 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001137}
1138
1139bool Datapath::ModifyFwmark(IpFamily family,
1140 const std::string& chain,
1141 const std::string& op,
1142 const std::string& iif,
1143 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001144 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001145 Fwmark mark,
1146 Fwmark mask,
1147 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001148 std::vector<std::string> args = {op, chain};
1149 if (!iif.empty()) {
1150 args.push_back("-i");
1151 args.push_back(iif);
1152 }
1153 if (!uid_name.empty()) {
1154 args.push_back("-m");
1155 args.push_back("owner");
1156 args.push_back("--uid-owner");
1157 args.push_back(uid_name);
1158 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001159 if (classid != 0) {
1160 args.push_back("-m");
1161 args.push_back("cgroup");
1162 args.push_back("--cgroup");
1163 args.push_back(base::StringPrintf("0x%08x", classid));
1164 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001165 args.push_back("-j");
1166 args.push_back("MARK");
1167 args.push_back("--set-mark");
1168 args.push_back(mark.ToString() + "/" + mask.ToString());
1169 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001170
Hugo Benichi58f264a2020-10-16 18:16:05 +09001171 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001172}
1173
Hugo Benichid82d8832020-08-14 10:05:03 +09001174bool Datapath::ModifyIpForwarding(IpFamily family,
1175 const std::string& op,
1176 const std::string& iif,
1177 const std::string& oif,
1178 bool log_failures) {
1179 if (iif.empty() && oif.empty()) {
1180 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1181 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001182 return false;
1183 }
1184
Hugo Benichid82d8832020-08-14 10:05:03 +09001185 std::vector<std::string> args = {op, "FORWARD"};
1186 if (!iif.empty()) {
1187 args.push_back("-i");
1188 args.push_back(iif);
1189 }
1190 if (!oif.empty()) {
1191 args.push_back("-o");
1192 args.push_back(oif);
1193 }
1194 args.push_back("-j");
1195 args.push_back("ACCEPT");
1196 args.push_back("-w");
1197
Hugo Benichi58f264a2020-10-16 18:16:05 +09001198 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001199}
1200
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001201bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1202 const std::string& op,
1203 const std::string& iif,
1204 Fwmark mark,
1205 Fwmark mask) {
1206 std::vector<std::string> args = {op, chain};
1207 if (!iif.empty()) {
1208 args.push_back("-i");
1209 args.push_back(iif);
1210 }
1211 if (mark.Value() != 0 && mask.Value() != 0) {
1212 args.push_back("-m");
1213 args.push_back("mark");
1214 args.push_back("--mark");
1215 args.push_back(mark.ToString() + "/" + mask.ToString());
1216 }
1217 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1218 return ModifyIptables(IpFamily::Dual, "mangle", args);
1219}
1220
1221bool Datapath::ModifyChain(IpFamily family,
1222 const std::string& table,
1223 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001224 const std::string& chain,
1225 bool log_failures) {
1226 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001227}
1228
1229bool Datapath::ModifyIptables(IpFamily family,
1230 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001231 const std::vector<std::string>& argv,
1232 bool log_failures) {
1233 switch (family) {
1234 case IPv4:
1235 case IPv6:
1236 case Dual:
1237 break;
1238 default:
1239 LOG(ERROR) << "Could not execute iptables command " << table
1240 << base::JoinString(argv, " ") << ": incorrect IP family "
1241 << family;
1242 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001243 }
1244
1245 bool success = true;
1246 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001247 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001248 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001249 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001250 return success;
1251}
1252
Hugo Benichid82d8832020-08-14 10:05:03 +09001253bool Datapath::StartIpForwarding(IpFamily family,
1254 const std::string& iif,
1255 const std::string& oif) {
1256 return ModifyIpForwarding(family, "-A", iif, oif);
1257}
1258
1259bool Datapath::StopIpForwarding(IpFamily family,
1260 const std::string& iif,
1261 const std::string& oif) {
1262 return ModifyIpForwarding(family, "-D", iif, oif);
1263}
1264
1265bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1266 const std::string& ifname2) {
1267 // Only start Ipv6 forwarding if -C returns false and it had not been
1268 // started yet.
1269 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1270 false /*log_failures*/) &&
1271 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1272 return false;
1273 }
1274
1275 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1276 false /*log_failures*/) &&
1277 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001278 RemoveIPv6Forwarding(ifname1, ifname2);
1279 return false;
1280 }
1281
1282 return true;
1283}
1284
1285void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1286 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001287 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1288 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001289}
1290
Garrick Evans3d97a392020-02-21 15:24:37 +09001291bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1292 uint32_t addr,
1293 uint32_t netmask) {
1294 struct rtentry route;
1295 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001296 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1297 SetSockaddrIn(&route.rt_dst, addr & netmask);
1298 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001299 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001300 return ModifyRtentry(SIOCADDRT, &route);
1301}
Garrick Evans3d97a392020-02-21 15:24:37 +09001302
Hugo Benichie8758b52020-04-03 14:49:01 +09001303bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1304 uint32_t addr,
1305 uint32_t netmask) {
1306 struct rtentry route;
1307 memset(&route, 0, sizeof(route));
1308 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1309 SetSockaddrIn(&route.rt_dst, addr & netmask);
1310 SetSockaddrIn(&route.rt_genmask, netmask);
1311 route.rt_flags = RTF_UP | RTF_GATEWAY;
1312 return ModifyRtentry(SIOCDELRT, &route);
1313}
1314
1315bool Datapath::AddIPv4Route(const std::string& ifname,
1316 uint32_t addr,
1317 uint32_t netmask) {
1318 struct rtentry route;
1319 memset(&route, 0, sizeof(route));
1320 SetSockaddrIn(&route.rt_dst, addr & netmask);
1321 SetSockaddrIn(&route.rt_genmask, netmask);
1322 char rt_dev[IFNAMSIZ];
1323 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1324 rt_dev[IFNAMSIZ - 1] = '\0';
1325 route.rt_dev = rt_dev;
1326 route.rt_flags = RTF_UP | RTF_GATEWAY;
1327 return ModifyRtentry(SIOCADDRT, &route);
1328}
1329
1330bool Datapath::DeleteIPv4Route(const std::string& ifname,
1331 uint32_t addr,
1332 uint32_t netmask) {
1333 struct rtentry route;
1334 memset(&route, 0, sizeof(route));
1335 SetSockaddrIn(&route.rt_dst, addr & netmask);
1336 SetSockaddrIn(&route.rt_genmask, netmask);
1337 char rt_dev[IFNAMSIZ];
1338 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1339 rt_dev[IFNAMSIZ - 1] = '\0';
1340 route.rt_dev = rt_dev;
1341 route.rt_flags = RTF_UP | RTF_GATEWAY;
1342 return ModifyRtentry(SIOCDELRT, &route);
1343}
1344
Taoyu Lia0727dc2020-09-24 19:54:59 +09001345bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001346 DCHECK(route);
1347 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001348 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001349 return false;
1350 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001351 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1352 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001353 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001354 return false;
1355 }
1356 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1357 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001358 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001359 return false;
1360 }
1361 return true;
1362}
1363
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001364bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1365 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1366 kArcAddr, kAdbServerPort, ifname,
1367 kLocalhostAddr, kAdbProxyTcpListenPort);
1368}
1369
1370void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1371 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1372 kArcAddr, kAdbServerPort, ifname,
1373 kLocalhostAddr, kAdbProxyTcpListenPort);
1374}
1375
1376bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1377 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1378 kAdbProxyTcpListenPort, ifname);
1379}
1380
1381void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1382 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1383 kAdbProxyTcpListenPort, ifname);
1384}
1385
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001386void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1387 if_nametoindex_[ifname] = ifindex;
1388}
1389
1390int Datapath::FindIfIndex(const std::string& ifname) {
1391 uint32_t ifindex = if_nametoindex(ifname.c_str());
1392 if (ifindex > 0) {
1393 if_nametoindex_[ifname] = ifindex;
1394 return ifindex;
1395 }
1396
1397 const auto it = if_nametoindex_.find(ifname);
1398 if (it != if_nametoindex_.end())
1399 return it->second;
1400
1401 return 0;
1402}
1403
Hugo Benichifcf81022020-12-04 11:01:37 +09001404std::ostream& operator<<(std::ostream& stream,
1405 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001406 stream << "{ pid: " << nsinfo.pid
1407 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001408 if (!nsinfo.outbound_ifname.empty()) {
1409 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1410 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001411 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1412 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001413 << ", peer_ifname: " << nsinfo.peer_ifname
1414 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1415 return stream;
1416}
1417
Garrick Evans3388a032020-03-24 11:25:55 +09001418} // namespace patchpanel