blob: 08ac54b6d0dc4d23f50a597d80b22bb6ed63a53b [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
Hugo Benichif0f55562021-04-02 15:25:02 +090057// Maximum length of an iptables chain name.
58constexpr int kIptablesMaxChainLength = 28;
59
Garrick Evans8a067562020-05-11 12:47:30 +090060std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
61 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090062 if (n.length() < IFNAMSIZ)
63 return n;
Garrick Evans54861622019-07-19 09:05:09 +090064
Garrick Evans2f581a02020-05-11 10:43:35 +090065 // Best effort attempt to preserve the interface number, assuming it's the
66 // last char in the name.
67 auto c = ifname[ifname.length() - 1];
68 n.resize(IFNAMSIZ - 1);
69 n[n.length() - 1] = c;
70 return n;
Garrick Evans54861622019-07-19 09:05:09 +090071}
Garrick Evansf0ab7132019-06-18 14:50:42 +090072
Hugo Benichiaba7e2e2021-02-22 14:47:11 +090073bool Ioctl(ioctl_t ioctl_h, unsigned long req, const char* arg) {
74 base::ScopedFD control_fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
75 if (!control_fd.is_valid()) {
76 PLOG(ERROR) << "Failed to create control socket for ioctl request=" << req;
77 return false;
78 }
79 if ((*ioctl_h)(control_fd.get(), req, arg) != 0) {
80 PLOG(ERROR) << "ioctl request=" << req << " failed";
81 return false;
82 }
83 return true;
84}
85
Garrick Evans8a067562020-05-11 12:47:30 +090086} // namespace
87
88std::string ArcVethHostName(const std::string& ifname) {
89 return PrefixIfname("veth", ifname);
90}
91
92std::string ArcBridgeName(const std::string& ifname) {
93 return PrefixIfname("arc_", ifname);
94}
95
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090096Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
97 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090098
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090099Datapath::Datapath(MinijailedProcessRunner* process_runner,
100 Firewall* firewall,
101 ioctl_t ioctl_hook)
102 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900103 CHECK(process_runner_);
104}
105
Garrick Evans260ff302019-07-25 11:22:50 +0900106MinijailedProcessRunner& Datapath::runner() const {
107 return *process_runner_;
108}
109
Hugo Benichibf811c62020-09-07 17:30:45 +0900110void Datapath::Start() {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900111 // Restart from a clean iptables state in case of an unordered shutdown.
112 ResetIptables();
113
Hugo Benichibf811c62020-09-07 17:30:45 +0900114 // Enable IPv4 packet forwarding
115 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
116 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
117 << " Guest connectivity will not work correctly.";
118
119 // Limit local port range: Android owns 47104-61000.
120 // TODO(garrick): The original history behind this tweak is gone. Some
121 // investigation is needed to see if it is still applicable.
122 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
123 "32768 47103") != 0)
124 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
125 << " apps may not work correctly.";
126
127 // Enable IPv6 packet forwarding
128 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
129 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
130 << " IPv6 functionality may be broken.";
131
Hugo Benichi58125d32020-09-09 11:25:45 +0900132 // Create a FORWARD ACCEPT rule for connections already established.
133 if (process_runner_->iptables(
134 "filter", {"-A", "FORWARD", "-m", "state", "--state",
135 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900136 LOG(ERROR) << "Failed to install forwarding rule for established"
137 << " connections.";
138
Hugo Benichiac799a82021-03-25 00:16:16 +0900139 // Create a FORWARD rule for accepting any ARC originated traffic regardless
140 // of the output interface. This enables for ARC certain multihoming
141 // scenarios (b/182594063).
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900142 if (!ModifyJumpRule(IpFamily::IPv4, "filter", "-A", "FORWARD", "ACCEPT",
143 "arc+", "" /*oif*/))
Hugo Benichiac799a82021-03-25 00:16:16 +0900144 LOG(ERROR) << "Failed to install forwarding rule for ARC traffic";
145
Hugo Benichibf811c62020-09-07 17:30:45 +0900146 // chromium:898210: Drop any locally originated traffic that would exit a
147 // physical interface with a source IPv4 address from the subnet of IPs used
148 // for VMs, containers, and connected namespaces This is needed to prevent
149 // packets leaking with an incorrect src IP when a local process binds to the
150 // wrong interface.
Hugo Benichif0f55562021-04-02 15:25:02 +0900151 if (!AddChain(IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain))
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900152 LOG(ERROR) << "Failed to create " << kDropGuestIpv4PrefixChain
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900153 << " filter chain";
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900154 if (!ModifyJumpRule(IpFamily::IPv4, "filter", "-I", "OUTPUT",
155 kDropGuestIpv4PrefixChain, "" /*iif*/, "" /*oif*/))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900156 LOG(ERROR) << "Failed to set up jump rule from filter OUTPUT to "
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900157 << kDropGuestIpv4PrefixChain;
Hugo Benichibf811c62020-09-07 17:30:45 +0900158 for (const auto& oif : kPhysicalIfnamePrefixes) {
159 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
160 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
161 << kGuestIPv4Subnet << " exiting " << oif;
162 }
163
Hugo Benichi561fae42021-01-22 15:28:40 +0900164 // Set static SNAT rules for any IPv4 traffic originated from a guest (ARC,
165 // Crostini, ...) or a connected namespace.
166 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
167 // need to be explicitly dropped as SNAT cannot be applied to them.
168 if (process_runner_->iptables(
169 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
170 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0)
171 LOG(ERROR) << "Failed to install SNAT mark rules.";
172 if (process_runner_->iptables(
173 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
174 "MASQUERADE", "-w"}) != 0)
175 LOG(ERROR) << "Failed to install SNAT mark rules.";
Hugo Benichibf811c62020-09-07 17:30:45 +0900176 if (!AddOutboundIPv4SNATMark("vmtap+"))
Hugo Benichi561fae42021-01-22 15:28:40 +0900177 LOG(ERROR) << "Failed to set up NAT for TAP devices.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900178
Hugo Benichi2a940542020-10-26 18:50:49 +0900179 // Applies the routing tag saved in conntrack for any established connection
180 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900181 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
182 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900183 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
Hugo Benichi155de002021-01-19 16:45:46 +0900184 // b/177787823 Also restore the routing tag after routing has taken place so
185 // that packets pre-tagged with the VPN routing tag are in sync with their
186 // associated CONNMARK routing tag. This is necessary to correctly identify
187 // packets exiting through the wrong interface.
188 if (!ModifyConnmarkRestore(IpFamily::Dual, "POSTROUTING", "-A", "" /*iif*/,
189 kFwmarkRoutingMask))
190 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK restore rule";
Hugo Benichi2a940542020-10-26 18:50:49 +0900191
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900192 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
193 // tag and tagging the local traffic that should be routed through a VPN.
Hugo Benichif0f55562021-04-02 15:25:02 +0900194 if (!AddChain(IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900195 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
196 << " mangle chain";
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900197 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "OUTPUT",
198 kApplyLocalSourceMarkChain, "" /*iif*/, "" /*oif*/))
199
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900200 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
201 << " to mangle OUTPUT";
202 // Create rules for tagging local sources with the source tag and the vpn
203 // policy tag.
204 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900205 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900206 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
207 << " in " << kApplyLocalSourceMarkChain;
208 }
209 // Finally add a catch-all rule for tagging any remaining local sources with
210 // the SYSTEM source tag
211 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
212 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
213
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900214 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
215 // traffic that should be routed through a VPN.
Hugo Benichif0f55562021-04-02 15:25:02 +0900216 if (!AddChain(IpFamily::Dual, "mangle", kApplyVpnMarkChain))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900217 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900218 // All local outgoing traffic eligible to VPN routing should traverse the VPN
219 // marking chain.
220 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", "" /*iif*/, kFwmarkRouteOnVpn,
221 kFwmarkVpnMask))
222 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
223 // Any traffic that already has a routing tag applied is accepted.
224 if (!ModifyIptables(
225 IpFamily::Dual, "mangle",
226 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
227 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
228 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
229 "connections";
Hugo Benichi155de002021-01-19 16:45:46 +0900230
231 // Sets up a mangle chain used in POSTROUTING for checking consistency between
232 // the routing tag and the output interface.
Hugo Benichif0f55562021-04-02 15:25:02 +0900233 if (!AddChain(IpFamily::Dual, "mangle", kCheckRoutingMarkChain))
Hugo Benichi155de002021-01-19 16:45:46 +0900234 LOG(ERROR) << "Failed to set up " << kCheckRoutingMarkChain
235 << " mangle chain";
Hugo Benichi155de002021-01-19 16:45:46 +0900236 // b/177787823 If it already exists, the routing tag of any traffic exiting an
237 // interface (physical or VPN) must match the routing tag of that interface.
238 if (!ModifyIptables(IpFamily::Dual, "mangle",
239 {"-A", "POSTROUTING", "-m", "mark", "!", "--mark",
240 "0x0/" + kFwmarkRoutingMask.ToString(), "-j",
241 kCheckRoutingMarkChain, "-w"}))
242 LOG(ERROR) << "Failed to add POSTROUTING jump rule to "
243 << kCheckRoutingMarkChain;
Hugo Benichi52a64992021-01-28 17:47:33 +0900244
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900245 // b/178331695 Sets up a nat chain used in OUTPUT for redirecting DNS queries
246 // of system services. When a VPN is connected, a query routed through a
247 // physical network is redirected to the primary nameserver of that network.
Hugo Benichif0f55562021-04-02 15:25:02 +0900248 if (!AddChain(IpFamily::IPv4, "nat", kRedirectDnsChain))
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900249 LOG(ERROR) << "Failed to set up " << kRedirectDnsChain << " nat chain";
250
Hugo Benichi52a64992021-01-28 17:47:33 +0900251 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
252 // incorrectly cause neighbor discovery icmpv6 packets to be dropped. Add
253 // these rules to bypass connmark rule for those packets.
254 for (const auto& type : kNeighborDiscoveryTypes) {
255 if (!ModifyIptables(IpFamily::IPv6, "mangle",
256 {"-I", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
257 "-j", "ACCEPT", "-w"}))
258 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
259 << " packets in OUTPUT";
260 if (!ModifyIptables(IpFamily::IPv6, "mangle",
261 {"-I", kCheckRoutingMarkChain, "-p", "icmpv6",
262 "--icmpv6-type", type, "-j", "RETURN", "-w"}))
263 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
264 << " packets in " << kCheckRoutingMarkChain;
265 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900266}
267
268void Datapath::Stop() {
Hugo Benichibf811c62020-09-07 17:30:45 +0900269 // Restore original local port range.
270 // TODO(garrick): The original history behind this tweak is gone. Some
271 // investigation is needed to see if it is still applicable.
272 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
273 "32768 61000") != 0)
274 LOG(ERROR) << "Failed to restore local port range";
275
276 // Disable packet forwarding
277 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
278 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
279
280 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
281 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900282
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900283 ResetIptables();
284}
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900285
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900286void Datapath::ResetIptables() {
287 // If it exists, remove jump rules from a built-in chain to a custom routing
288 // or tagging chain.
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900289 ModifyJumpRule(IpFamily::IPv4, "filter", "-D", "OUTPUT",
290 kDropGuestIpv4PrefixChain, "" /*iif*/, "" /*oif*/,
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900291 false /*log_failures*/);
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900292
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900293 // Flush chains used for routing and fwmark tagging. Also delete additional
294 // chains made by patchpanel. Chains used by permission broker (nat
295 // PREROUTING, filter INPUT) and chains used for traffic counters (mangle
296 // {rx,tx}_{<iface>, vpn}) are not flushed.
297 static struct {
298 IpFamily family;
299 std::string table;
300 std::string chain;
301 bool should_delete;
302 } resetOps[] = {
303 {IpFamily::Dual, "filter", "FORWARD", false},
304 {IpFamily::Dual, "mangle", "FORWARD", false},
305 {IpFamily::Dual, "mangle", "INPUT", false},
306 {IpFamily::Dual, "mangle", "OUTPUT", false},
307 {IpFamily::Dual, "mangle", "POSTROUTING", false},
308 {IpFamily::Dual, "mangle", "PREROUTING", false},
309 {IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain, true},
310 {IpFamily::Dual, "mangle", kApplyVpnMarkChain, true},
311 {IpFamily::Dual, "mangle", kCheckRoutingMarkChain, true},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900312 {IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain, true},
313 {IpFamily::IPv4, "nat", kRedirectDnsChain, true},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900314 {IpFamily::IPv4, "nat", "POSTROUTING", false},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900315 {IpFamily::IPv4, "nat", "OUTPUT", false},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900316 };
317 for (const auto& op : resetOps) {
318 // Chains to delete are custom chains and will not exist the first time
319 // patchpanel starts after boot. Skip flushing and delete these chains if
320 // they do not exist to avoid logging spurious error messages.
321 if (op.should_delete && !ModifyChain(op.family, op.table, "-L", op.chain,
322 false /*log_failures*/))
323 continue;
Hugo Benichi155de002021-01-19 16:45:46 +0900324
Hugo Benichif0f55562021-04-02 15:25:02 +0900325 if (!FlushChain(op.family, op.table, op.chain))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900326 LOG(ERROR) << "Failed to flush " << op.chain << " chain in table "
327 << op.table;
Hugo Benichi2a940542020-10-26 18:50:49 +0900328
Hugo Benichif0f55562021-04-02 15:25:02 +0900329 if (op.should_delete && !RemoveChain(op.family, op.table, op.chain))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900330 LOG(ERROR) << "Failed to delete " << op.chain << " chain in table "
331 << op.table;
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900332 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900333}
334
Hugo Benichi33860d72020-07-09 16:34:01 +0900335bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
336 // Try first to delete any netns with name |netns_name| in case patchpanel
337 // did not exit cleanly.
338 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
339 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
340 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
341}
342
343bool Datapath::NetnsDeleteName(const std::string& netns_name) {
344 return process_runner_->ip_netns_delete(netns_name) == 0;
345}
346
Garrick Evans8a949dc2019-07-18 16:17:53 +0900347bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900348 uint32_t ipv4_addr,
349 uint32_t ipv4_prefix_len) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900350 if (!Ioctl(ioctl_, SIOCBRADDBR, ifname.c_str())) {
351 LOG(ERROR) << "Failed to create bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900352 return false;
353 }
354
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900355 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900356 if (process_runner_->ip(
357 "addr", "add",
358 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
359 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
360 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900361 RemoveBridge(ifname);
362 return false;
363 }
364
365 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900366 RemoveBridge(ifname);
367 return false;
368 }
369
370 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900371 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900372 RemoveBridge(ifname);
373 return false;
374 }
375
376 return true;
377}
378
379void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900380 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900381 process_runner_->ip("link", "set", {ifname, "down"});
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900382 if (!Ioctl(ioctl_, SIOCBRDELBR, ifname.c_str()))
383 LOG(ERROR) << "Failed to destroy bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900384}
385
Garrick Evans621ed262019-11-13 12:28:43 +0900386bool Datapath::AddToBridge(const std::string& br_ifname,
387 const std::string& ifname) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900388 struct ifreq ifr;
389 memset(&ifr, 0, sizeof(ifr));
390 strncpy(ifr.ifr_name, br_ifname.c_str(), sizeof(ifr.ifr_name));
391 ifr.ifr_ifindex = FindIfIndex(ifname);
392
393 if (!Ioctl(ioctl_, SIOCBRADDIF, reinterpret_cast<const char*>(&ifr))) {
394 LOG(ERROR) << "Failed to add " << ifname << " to bridge " << br_ifname;
395 return false;
396 }
397
398 return true;
Garrick Evans621ed262019-11-13 12:28:43 +0900399}
400
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900401std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900402 const MacAddress* mac_addr,
403 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900404 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900405 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
406 if (!dev.is_valid()) {
407 PLOG(ERROR) << "Failed to open " << kTunDev;
408 return "";
409 }
410
411 struct ifreq ifr;
412 memset(&ifr, 0, sizeof(ifr));
413 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
414 sizeof(ifr.ifr_name));
415 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
416
417 // If a template was given as the name, ifr_name will be updated with the
418 // actual interface name.
419 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900420 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900421 return "";
422 }
423 const char* ifname = ifr.ifr_name;
424
425 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900426 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900427 return "";
428 }
429
Garrick Evans4f9f5572019-11-26 10:25:16 +0900430 if (!user.empty()) {
431 uid_t uid = -1;
432 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
433 PLOG(ERROR) << "Unable to look up UID for " << user;
434 RemoveTAP(ifname);
435 return "";
436 }
437 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
438 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
439 << ifname;
440 RemoveTAP(ifname);
441 return "";
442 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900443 }
444
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900445 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900446 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
447 if (!sock.is_valid()) {
448 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900449 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900450 RemoveTAP(ifname);
451 return "";
452 }
453
Garrick Evans621ed262019-11-13 12:28:43 +0900454 if (ipv4_addr) {
455 struct sockaddr_in* addr =
456 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
457 addr->sin_family = AF_INET;
458 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
459 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
460 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
461 << " {" << ipv4_addr->ToCidrString() << "}";
462 RemoveTAP(ifname);
463 return "";
464 }
465
466 struct sockaddr_in* netmask =
467 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
468 netmask->sin_family = AF_INET;
469 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
470 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
471 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
472 << " {" << ipv4_addr->ToCidrString() << "}";
473 RemoveTAP(ifname);
474 return "";
475 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900476 }
477
Garrick Evans621ed262019-11-13 12:28:43 +0900478 if (mac_addr) {
479 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
480 hwaddr->sa_family = ARPHRD_ETHER;
481 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
482 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
483 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
484 << " {" << MacAddressToString(*mac_addr) << "}";
485 RemoveTAP(ifname);
486 return "";
487 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900488 }
489
490 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900491 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900492 RemoveTAP(ifname);
493 return "";
494 }
495
496 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
497 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900498 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900499 RemoveTAP(ifname);
500 return "";
501 }
502
503 return ifname;
504}
505
506void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900507 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900508}
509
Hugo Benichi33860d72020-07-09 16:34:01 +0900510bool Datapath::ConnectVethPair(pid_t netns_pid,
511 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900512 const std::string& veth_ifname,
513 const std::string& peer_ifname,
514 const MacAddress& remote_mac_addr,
515 uint32_t remote_ipv4_addr,
516 uint32_t remote_ipv4_prefix_len,
517 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900518 // Set up the virtual pair across the current namespace and |netns_name|.
519 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
520 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
521 << peer_ifname;
522 return false;
523 }
524
525 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900526 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900527 ScopedNS ns(netns_pid, ScopedNS::Type::Network);
Hugo Benichi33860d72020-07-09 16:34:01 +0900528 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900529 LOG(ERROR)
530 << "Cannot create virtual link -- invalid container namespace?";
531 return false;
532 }
533
Hugo Benichi76675592020-04-08 14:29:57 +0900534 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
535 remote_ipv4_prefix_len, true /* link up */,
536 remote_multicast_flag)) {
537 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
538 RemoveInterface(peer_ifname);
539 return false;
540 }
541 }
542
Hugo Benichi76675592020-04-08 14:29:57 +0900543 if (!ToggleInterface(veth_ifname, true /*up*/)) {
544 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
545 RemoveInterface(veth_ifname);
546 return false;
547 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900548
Hugo Benichi76675592020-04-08 14:29:57 +0900549 return true;
550}
551
Hugo Benichi33860d72020-07-09 16:34:01 +0900552bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
553 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900554 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900555 return process_runner_->ip("link", "add",
556 {veth_ifname, "type", "veth", "peer", "name",
557 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900558}
Garrick Evans54861622019-07-19 09:05:09 +0900559
Garrick Evans2470caa2020-03-04 14:15:41 +0900560bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
561 const std::string link = up ? "up" : "down";
562 return process_runner_->ip("link", "set", {ifname, link}) == 0;
563}
Garrick Evans54861622019-07-19 09:05:09 +0900564
Garrick Evans2470caa2020-03-04 14:15:41 +0900565bool Datapath::ConfigureInterface(const std::string& ifname,
566 const MacAddress& mac_addr,
567 uint32_t ipv4_addr,
568 uint32_t ipv4_prefix_len,
569 bool up,
570 bool enable_multicast) {
571 const std::string link = up ? "up" : "down";
572 const std::string multicast = enable_multicast ? "on" : "off";
573 return (process_runner_->ip(
574 "addr", "add",
575 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
576 IPv4AddressToString(
577 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
578 "dev", ifname}) == 0) &&
579 (process_runner_->ip("link", "set",
580 {
581 "dev",
582 ifname,
583 link,
584 "addr",
585 MacAddressToString(mac_addr),
586 "multicast",
587 multicast,
588 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900589}
590
591void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900592 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900593}
594
Hugo Benichi321f23b2020-09-25 15:42:05 +0900595bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
596 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900597 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900598 "filter", {"-I", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
599 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900600}
601
602bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
603 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900604 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900605 "filter", {"-D", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
606 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900607}
608
Hugo Benichifcf81022020-12-04 11:01:37 +0900609bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900610 // Veth interface configuration and client routing configuration:
611 // - attach a name to the client namespace.
612 // - create veth pair across the current namespace and the client namespace.
613 // - configure IPv4 address on remote veth inside client namespace.
614 // - configure IPv4 address on local veth inside host namespace.
615 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900616 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
617 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
618 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900619 return false;
620 }
621
Hugo Benichifcf81022020-12-04 11:01:37 +0900622 if (!ConnectVethPair(
623 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
624 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
625 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900626 LOG(ERROR) << "Failed to create veth pair for"
627 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900628 << nsinfo.pid;
629 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900630 return false;
631 }
632
Hugo Benichifcf81022020-12-04 11:01:37 +0900633 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
634 nsinfo.peer_subnet->AddressAtOffset(0),
635 nsinfo.peer_subnet->PrefixLength(),
636 true /* link up */, false /* enable_multicast */)) {
637 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
638 RemoveInterface(nsinfo.host_ifname);
639 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900640 return false;
641 }
642
643 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900644 ScopedNS ns(nsinfo.pid, ScopedNS::Type::Network);
Hugo Benichifcf81022020-12-04 11:01:37 +0900645 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
646 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
647 RemoveInterface(nsinfo.host_ifname);
648 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900649 return false;
650 }
651
Hugo Benichifcf81022020-12-04 11:01:37 +0900652 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
653 INADDR_ANY)) {
654 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
655 << " inside namespace pid " << nsinfo.pid;
656 RemoveInterface(nsinfo.host_ifname);
657 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900658 return false;
659 }
660 }
661
662 // Host namespace routing configuration
663 // - ingress: add route to client subnet via |host_ifname|.
664 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
665 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
666 // Note that by default unsolicited ingress traffic is not forwarded to the
667 // client namespace unless the client specifically set port forwarding
668 // through permission_broker DBus APIs.
669 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
670 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900671 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
672 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
673 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900674 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900675 RemoveInterface(nsinfo.host_ifname);
676 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900677 return false;
678 }
679
Hugo Benichi7c342672020-09-08 09:18:14 +0900680 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900681 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900682 LOG(ERROR) << "Failed to set SNAT for traffic"
683 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900684 << nsinfo.host_ifname;
685 RemoveInterface(nsinfo.host_ifname);
686 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
687 nsinfo.peer_subnet->BaseAddress(), netmask);
688 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
689 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900690 return false;
691 }
692
Hugo Benichi93306e52020-12-04 16:08:00 +0900693 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
694 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
695 nsinfo.route_on_vpn);
696
Hugo Benichi7c342672020-09-08 09:18:14 +0900697 return true;
698}
699
Hugo Benichifcf81022020-12-04 11:01:37 +0900700void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900701 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
702 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
703 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900704 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900705 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
706 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
707 nsinfo.peer_subnet->BaseAddress(),
708 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
709 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900710}
711
Hugo Benichi8d622b52020-08-13 15:24:12 +0900712void Datapath::StartRoutingDevice(const std::string& ext_ifname,
713 const std::string& int_ifname,
714 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900715 TrafficSource source,
716 bool route_on_vpn) {
717 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900718 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900719 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
720 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
721 << "->" << int_ifname;
722
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900723 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_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 Benichifa97b3b2020-10-06 22:45:26 +0900727 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900728 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
729 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900730
Hugo Benichi2a940542020-10-26 18:50:49 +0900731 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
732 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
733 << source << " for " << int_ifname;
734
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900735 if (!ext_ifname.empty()) {
736 // If |ext_ifname| is not null, mark egress traffic with the
737 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900738 int ifindex = FindIfIndex(ext_ifname);
739 if (ifindex != 0) {
740 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
741 if (!ModifyFwmarkRoutingTag("PREROUTING", "-A", routing_mark, int_ifname))
742 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
743 << ext_ifname << "<-" << int_ifname;
744 } else {
745 // Do not abort: if the PREROUTING tagging mark cannot be
746 // set then |int_ifname| will instead be routed to the default logical
747 // network without connection pinning, aka legacy routing.
748 LOG(ERROR) << "Failed to retrieve interface index of " << ext_ifname;
749 }
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900750 } else {
751 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
752 // PREROUTING to apply any fwmark routing tag saved for the current
753 // connection, and rely on implicit routing to the default logical network
754 // otherwise.
Hugo Benichi1af52392020-11-27 18:09:32 +0900755 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname,
756 kFwmarkRoutingMask))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900757 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
758 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900759
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900760 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900761 // default network is eligible to be routed through a VPN if |route_on_vpn|
762 // is true.
763 if (route_on_vpn &&
764 !ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900765 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900766 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900767}
768
769void Datapath::StopRoutingDevice(const std::string& ext_ifname,
770 const std::string& int_ifname,
771 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900772 TrafficSource source,
773 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900774 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900775 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900776 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
777 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900778 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900779 if (!ext_ifname.empty()) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900780 Fwmark routing_mark = CachedRoutingFwmark(ext_ifname);
781 ModifyFwmarkRoutingTag("PREROUTING", "-D", routing_mark, int_ifname);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900782 } else {
Hugo Benichi1af52392020-11-27 18:09:32 +0900783 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname,
784 kFwmarkRoutingMask);
Hugo Benichi93306e52020-12-04 16:08:00 +0900785 if (route_on_vpn)
786 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900787 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900788}
789
Garrick Evansf0ab7132019-06-18 14:50:42 +0900790bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
791 const std::string& ipv4_addr) {
792 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900793 if (process_runner_->iptables(
794 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
795 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900796 return false;
797
798 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900799 if (process_runner_->iptables(
800 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
801 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900802 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
803 return false;
804 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900805 if (process_runner_->iptables(
806 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
807 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900808 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
809 return false;
810 }
811
812 return true;
813}
814
815void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
816 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900817 process_runner_->iptables(
818 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
819 "--to-destination", ipv4_addr, "-w"});
820 process_runner_->iptables(
821 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
822 "--to-destination", ipv4_addr, "-w"});
823 process_runner_->iptables(
824 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
825 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900826}
827
Hugo Benichie8758b52020-04-03 14:49:01 +0900828bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
829 return process_runner_->iptables(
830 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900831 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900832}
833
834void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
835 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900836 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900837}
838
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900839bool Datapath::AddRedirectDnsRule(const std::string& ifname,
840 const std::string dns_ipv4_addr) {
841 bool success = true;
842 success &= RemoveRedirectDnsRule(ifname);
843 // Use Insert operation to ensure that the new DNS address is used first.
844 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
845 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
846 physical_dns_addresses_[ifname] = dns_ipv4_addr;
847 return success;
848}
849
850bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
851 const auto it = physical_dns_addresses_.find(ifname);
852 if (it == physical_dns_addresses_.end())
853 return true;
854
855 bool success = true;
856 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
857 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
858 physical_dns_addresses_.erase(it);
859 return success;
860}
861
862bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
863 const std::string& protocol,
864 const std::string& ifname,
865 const std::string& dns_ipv4_addr) {
866 std::vector<std::string> args = {op,
867 kRedirectDnsChain,
868 "-p",
869 protocol,
870 "--dport",
871 "53",
872 "-o",
873 ifname,
874 "-j",
875 "DNAT",
876 "--to-destination",
877 dns_ipv4_addr,
878 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900879 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900880}
881
882bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
883 std::vector<std::string> args = {
884 op,
885 "OUTPUT",
886 "-m",
887 "mark",
888 "!",
889 "--mark",
890 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
891 "-j",
892 kRedirectDnsChain,
893 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900894 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900895}
896
Garrick Evans664a82f2019-12-17 12:18:05 +0900897bool Datapath::MaskInterfaceFlags(const std::string& ifname,
898 uint16_t on,
899 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900900 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
901 if (!sock.is_valid()) {
902 PLOG(ERROR) << "Failed to create control socket";
903 return false;
904 }
905 ifreq ifr;
906 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
907 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
908 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
909 return false;
910 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900911 ifr.ifr_flags |= on;
912 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900913 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900914 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
915 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900916 return false;
917 }
918 return true;
919}
920
Garrick Evans260ff302019-07-25 11:22:50 +0900921bool Datapath::AddIPv6HostRoute(const std::string& ifname,
922 const std::string& ipv6_addr,
923 int ipv6_prefix_len) {
924 std::string ipv6_addr_cidr =
925 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
926
Garrick Evans8e8e3472020-01-23 14:03:50 +0900927 return process_runner_->ip6("route", "replace",
928 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900929}
930
931void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
932 const std::string& ipv6_addr,
933 int ipv6_prefix_len) {
934 std::string ipv6_addr_cidr =
935 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
936
Garrick Evans8e8e3472020-01-23 14:03:50 +0900937 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900938}
939
Taoyu Lia0727dc2020-09-24 19:54:59 +0900940bool Datapath::AddIPv6Address(const std::string& ifname,
941 const std::string& ipv6_addr) {
942 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900943}
944
Taoyu Lia0727dc2020-09-24 19:54:59 +0900945void Datapath::RemoveIPv6Address(const std::string& ifname,
946 const std::string& ipv6_addr) {
947 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900948}
949
Hugo Benichi76be34a2020-08-26 22:35:54 +0900950void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900951 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +0900952 if (ifindex == 0) {
953 // Can happen if the interface has already been removed (b/183679000).
954 LOG(ERROR) << "Failed to set up connection pinning on " << ext_ifname;
955 return;
956 }
957
958 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
959 LOG(INFO) << "Start connection pinning on " << ext_ifname
960 << " fwmark=" << routing_mark.ToString();
961 if (!ModifyIptables(
962 IpFamily::Dual, "mangle",
963 {"-A", kCheckRoutingMarkChain, "-o", ext_ifname, "-m", "mark", "!",
964 "--mark",
Hugo Benichi0a110402021-03-25 11:32:52 +0900965 routing_mark.ToString() + "/" + kFwmarkRoutingMask.ToString(),
966 "-w"}))
Hugo Benichi155de002021-01-19 16:45:46 +0900967 LOG(ERROR) << "Could not set fwmark routing filter rule for " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900968 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900969 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname,
970 routing_mark))
Hugo Benichi76be34a2020-08-26 22:35:54 +0900971 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900972 // Save in CONNMARK the source tag for egress traffic of this connection.
973 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
974 kFwmarkAllSourcesMask))
975 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
976 "source tag on "
977 << ext_ifname;
978 // Restore from CONNMARK the source tag for ingress traffic of this connection
979 // (returned traffic).
980 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
981 kFwmarkAllSourcesMask))
982 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
983 "traffic received on "
984 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900985}
986
987void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900988 Fwmark routing_mark = CachedRoutingFwmark(ext_ifname);
989 LOG(INFO) << "Stop connection pinning on " << ext_ifname
990 << " fwmark=" << routing_mark.ToString();
991 if (!ModifyIptables(
992 IpFamily::Dual, "mangle",
993 {"-D", kCheckRoutingMarkChain, "-o", ext_ifname, "-m", "mark", "!",
994 "--mark",
Hugo Benichi0a110402021-03-25 11:32:52 +0900995 routing_mark.ToString() + "/" + kFwmarkRoutingMask.ToString(),
996 "-w"}))
Hugo Benichi155de002021-01-19 16:45:46 +0900997 LOG(ERROR) << "Could not remove fwmark routing filter rule for "
998 << ext_ifname;
Hugo Benichi8c526e92021-03-25 14:59:59 +0900999 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname,
1000 routing_mark))
Hugo Benichi76be34a2020-08-26 22:35:54 +09001001 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +09001002 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
1003 kFwmarkAllSourcesMask))
1004 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
1005 "fwmark source tag on "
1006 << ext_ifname;
1007 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
1008 kFwmarkAllSourcesMask))
1009 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
1010 "traffic received on "
1011 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +09001012}
1013
Hugo Benichi2a940542020-10-26 18:50:49 +09001014void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +09001015 int ifindex = FindIfIndex(vpn_ifname);
1016 if (ifindex == 0) {
1017 // Can happen if the interface has already been removed (b/183679000).
1018 LOG(ERROR) << "Failed to start VPN routing on " << vpn_ifname;
1019 return;
1020 }
1021
1022 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
1023 LOG(INFO) << "Start VPN routing on " << vpn_ifname
1024 << " fwmark=" << routing_mark.ToString();
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001025 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-A", "POSTROUTING", "MASQUERADE",
1026 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +09001027 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +09001028 StartConnectionPinning(vpn_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +09001029 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", routing_mark, ""))
Hugo Benichi2a940542020-10-26 18:50:49 +09001030 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +09001031 if (vpn_ifname != kArcBridge)
1032 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
1033 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001034 if (!ModifyRedirectDnsJumpRule("-A"))
1035 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001036}
1037
1038void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +09001039 Fwmark routing_mark = CachedRoutingFwmark(vpn_ifname);
1040 LOG(INFO) << "Stop VPN routing on " << vpn_ifname
1041 << " fwmark=" << routing_mark.ToString();
Hugo Benichibfc49112020-12-14 12:54:44 +09001042 if (vpn_ifname != kArcBridge)
1043 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
1044 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi8c526e92021-03-25 14:59:59 +09001045 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", routing_mark, ""))
Hugo Benichi2a940542020-10-26 18:50:49 +09001046 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
1047 StopConnectionPinning(vpn_ifname);
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001048 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-D", "POSTROUTING", "MASQUERADE",
1049 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +09001050 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001051 if (!ModifyRedirectDnsJumpRule("-D"))
1052 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001053}
1054
Hugo Benichi76be34a2020-08-26 22:35:54 +09001055bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
1056 const std::string& op,
Hugo Benichi8c526e92021-03-25 14:59:59 +09001057 const std::string& oif,
1058 Fwmark routing_mark) {
1059 return ModifyConnmarkSet(family, "POSTROUTING", op, oif, routing_mark,
1060 kFwmarkRoutingMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001061}
1062
1063bool Datapath::ModifyConnmarkSet(IpFamily family,
1064 const std::string& chain,
1065 const std::string& op,
1066 const std::string& oif,
1067 Fwmark mark,
1068 Fwmark mask) {
1069 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
1070 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
1071 return false;
1072 }
1073
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001074 std::vector<std::string> args = {op, chain};
1075 if (!oif.empty()) {
1076 args.push_back("-o");
1077 args.push_back(oif);
1078 }
1079 args.push_back("-j");
1080 args.push_back("CONNMARK");
1081 args.push_back("--set-mark");
1082 args.push_back(mark.ToString() + "/" + mask.ToString());
1083 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +09001084
Hugo Benichi58f264a2020-10-16 18:16:05 +09001085 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +09001086}
1087
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001088bool Datapath::ModifyConnmarkRestore(IpFamily family,
1089 const std::string& chain,
1090 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001091 const std::string& iif,
1092 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001093 std::vector<std::string> args = {op, chain};
1094 if (!iif.empty()) {
1095 args.push_back("-i");
1096 args.push_back(iif);
1097 }
1098 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001099 mask.ToString(), "-w"});
1100 return ModifyIptables(family, "mangle", args);
1101}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001102
Hugo Benichi1af52392020-11-27 18:09:32 +09001103bool Datapath::ModifyConnmarkSave(IpFamily family,
1104 const std::string& chain,
1105 const std::string& op,
1106 const std::string& oif,
1107 Fwmark mask) {
1108 std::vector<std::string> args = {op, chain};
1109 if (!oif.empty()) {
1110 args.push_back("-o");
1111 args.push_back(oif);
1112 }
1113 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
1114 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +09001115 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001116}
1117
Hugo Benichi2a940542020-10-26 18:50:49 +09001118bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1119 const std::string& op,
Hugo Benichi8c526e92021-03-25 14:59:59 +09001120 Fwmark routing_mark,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001121 const std::string& int_ifname) {
Hugo Benichi2a940542020-10-26 18:50:49 +09001122 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi8c526e92021-03-25 14:59:59 +09001123 0 /*classid*/, routing_mark, kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001124}
1125
Hugo Benichi9be19b12020-08-14 15:33:40 +09001126bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
1127 const std::string& iif,
1128 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001129 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001130 0 /*classid*/, Fwmark::FromSource(source),
1131 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001132}
1133
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001134bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1135 TrafficSource source) {
1136 std::vector<std::string> args = {"-A",
1137 kApplyLocalSourceMarkChain,
1138 "-m",
1139 "mark",
1140 "--mark",
1141 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1142 "-j",
1143 "MARK",
1144 "--set-mark",
1145 Fwmark::FromSource(source).ToString() + "/" +
1146 kFwmarkAllSourcesMask.ToString(),
1147 "-w"};
1148 return ModifyIptables(IpFamily::Dual, "mangle", args);
1149}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001150
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001151bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1152 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001153 if (std::string(source.uid_name).empty() && source.classid == 0)
1154 return false;
1155
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001156 Fwmark mark = Fwmark::FromSource(source.source_type);
1157 if (source.is_on_vpn)
1158 mark = mark | kFwmarkRouteOnVpn;
1159
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001160 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1161 "" /*iif*/, source.uid_name, source.classid, mark,
1162 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001163}
1164
1165bool Datapath::ModifyFwmark(IpFamily family,
1166 const std::string& chain,
1167 const std::string& op,
1168 const std::string& iif,
1169 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001170 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001171 Fwmark mark,
1172 Fwmark mask,
1173 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001174 std::vector<std::string> args = {op, chain};
1175 if (!iif.empty()) {
1176 args.push_back("-i");
1177 args.push_back(iif);
1178 }
1179 if (!uid_name.empty()) {
1180 args.push_back("-m");
1181 args.push_back("owner");
1182 args.push_back("--uid-owner");
1183 args.push_back(uid_name);
1184 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001185 if (classid != 0) {
1186 args.push_back("-m");
1187 args.push_back("cgroup");
1188 args.push_back("--cgroup");
1189 args.push_back(base::StringPrintf("0x%08x", classid));
1190 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001191 args.push_back("-j");
1192 args.push_back("MARK");
1193 args.push_back("--set-mark");
1194 args.push_back(mark.ToString() + "/" + mask.ToString());
1195 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001196
Hugo Benichi58f264a2020-10-16 18:16:05 +09001197 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001198}
1199
Hugo Benichid82d8832020-08-14 10:05:03 +09001200bool Datapath::ModifyIpForwarding(IpFamily family,
1201 const std::string& op,
1202 const std::string& iif,
1203 const std::string& oif,
1204 bool log_failures) {
1205 if (iif.empty() && oif.empty()) {
1206 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1207 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001208 return false;
1209 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001210 return ModifyJumpRule(family, "filter", op, "FORWARD", "ACCEPT", iif, oif,
1211 log_failures);
1212}
Garrick Evans260ff302019-07-25 11:22:50 +09001213
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001214bool Datapath::ModifyJumpRule(IpFamily family,
1215 const std::string& table,
1216 const std::string& op,
1217 const std::string& chain,
1218 const std::string& target,
1219 const std::string& iif,
1220 const std::string& oif,
1221 bool log_failures) {
1222 std::vector<std::string> args = {op, chain};
Hugo Benichid82d8832020-08-14 10:05:03 +09001223 if (!iif.empty()) {
1224 args.push_back("-i");
1225 args.push_back(iif);
1226 }
1227 if (!oif.empty()) {
1228 args.push_back("-o");
1229 args.push_back(oif);
1230 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001231 args.insert(args.end(), {"-j", target, "-w"});
1232 return ModifyIptables(family, table, args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001233}
1234
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001235bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1236 const std::string& op,
1237 const std::string& iif,
1238 Fwmark mark,
1239 Fwmark mask) {
1240 std::vector<std::string> args = {op, chain};
1241 if (!iif.empty()) {
1242 args.push_back("-i");
1243 args.push_back(iif);
1244 }
1245 if (mark.Value() != 0 && mask.Value() != 0) {
1246 args.push_back("-m");
1247 args.push_back("mark");
1248 args.push_back("--mark");
1249 args.push_back(mark.ToString() + "/" + mask.ToString());
1250 }
1251 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1252 return ModifyIptables(IpFamily::Dual, "mangle", args);
1253}
1254
Hugo Benichif0f55562021-04-02 15:25:02 +09001255bool Datapath::AddChain(IpFamily family,
1256 const std::string& table,
1257 const std::string& name) {
1258 DCHECK(name.size() <= kIptablesMaxChainLength);
1259 return ModifyChain(family, table, "-N", name);
1260}
1261
1262bool Datapath::RemoveChain(IpFamily family,
1263 const std::string& table,
1264 const std::string& name) {
1265 return ModifyChain(family, table, "-X", name);
1266}
1267
1268bool Datapath::FlushChain(IpFamily family,
1269 const std::string& table,
1270 const std::string& name) {
1271 return ModifyChain(family, table, "-F", name);
1272}
1273
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001274bool Datapath::ModifyChain(IpFamily family,
1275 const std::string& table,
1276 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001277 const std::string& chain,
1278 bool log_failures) {
1279 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001280}
1281
1282bool Datapath::ModifyIptables(IpFamily family,
1283 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001284 const std::vector<std::string>& argv,
1285 bool log_failures) {
1286 switch (family) {
1287 case IPv4:
1288 case IPv6:
1289 case Dual:
1290 break;
1291 default:
1292 LOG(ERROR) << "Could not execute iptables command " << table
1293 << base::JoinString(argv, " ") << ": incorrect IP family "
1294 << family;
1295 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001296 }
1297
1298 bool success = true;
1299 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001300 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001301 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001302 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001303 return success;
1304}
1305
Hugo Benichid82d8832020-08-14 10:05:03 +09001306bool Datapath::StartIpForwarding(IpFamily family,
1307 const std::string& iif,
1308 const std::string& oif) {
1309 return ModifyIpForwarding(family, "-A", iif, oif);
1310}
1311
1312bool Datapath::StopIpForwarding(IpFamily family,
1313 const std::string& iif,
1314 const std::string& oif) {
1315 return ModifyIpForwarding(family, "-D", iif, oif);
1316}
1317
1318bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1319 const std::string& ifname2) {
1320 // Only start Ipv6 forwarding if -C returns false and it had not been
1321 // started yet.
1322 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1323 false /*log_failures*/) &&
1324 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1325 return false;
1326 }
1327
1328 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1329 false /*log_failures*/) &&
1330 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001331 RemoveIPv6Forwarding(ifname1, ifname2);
1332 return false;
1333 }
1334
1335 return true;
1336}
1337
1338void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1339 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001340 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1341 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001342}
1343
Garrick Evans3d97a392020-02-21 15:24:37 +09001344bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1345 uint32_t addr,
1346 uint32_t netmask) {
1347 struct rtentry route;
1348 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001349 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1350 SetSockaddrIn(&route.rt_dst, addr & netmask);
1351 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001352 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001353 return ModifyRtentry(SIOCADDRT, &route);
1354}
Garrick Evans3d97a392020-02-21 15:24:37 +09001355
Hugo Benichie8758b52020-04-03 14:49:01 +09001356bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1357 uint32_t addr,
1358 uint32_t netmask) {
1359 struct rtentry route;
1360 memset(&route, 0, sizeof(route));
1361 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1362 SetSockaddrIn(&route.rt_dst, addr & netmask);
1363 SetSockaddrIn(&route.rt_genmask, netmask);
1364 route.rt_flags = RTF_UP | RTF_GATEWAY;
1365 return ModifyRtentry(SIOCDELRT, &route);
1366}
1367
1368bool Datapath::AddIPv4Route(const std::string& ifname,
1369 uint32_t addr,
1370 uint32_t netmask) {
1371 struct rtentry route;
1372 memset(&route, 0, sizeof(route));
1373 SetSockaddrIn(&route.rt_dst, addr & netmask);
1374 SetSockaddrIn(&route.rt_genmask, netmask);
1375 char rt_dev[IFNAMSIZ];
1376 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1377 rt_dev[IFNAMSIZ - 1] = '\0';
1378 route.rt_dev = rt_dev;
1379 route.rt_flags = RTF_UP | RTF_GATEWAY;
1380 return ModifyRtentry(SIOCADDRT, &route);
1381}
1382
1383bool Datapath::DeleteIPv4Route(const std::string& ifname,
1384 uint32_t addr,
1385 uint32_t netmask) {
1386 struct rtentry route;
1387 memset(&route, 0, sizeof(route));
1388 SetSockaddrIn(&route.rt_dst, addr & netmask);
1389 SetSockaddrIn(&route.rt_genmask, netmask);
1390 char rt_dev[IFNAMSIZ];
1391 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1392 rt_dev[IFNAMSIZ - 1] = '\0';
1393 route.rt_dev = rt_dev;
1394 route.rt_flags = RTF_UP | RTF_GATEWAY;
1395 return ModifyRtentry(SIOCDELRT, &route);
1396}
1397
Taoyu Lia0727dc2020-09-24 19:54:59 +09001398bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001399 DCHECK(route);
1400 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001401 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001402 return false;
1403 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001404 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1405 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001406 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001407 return false;
1408 }
1409 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1410 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001411 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001412 return false;
1413 }
1414 return true;
1415}
1416
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001417bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1418 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1419 kArcAddr, kAdbServerPort, ifname,
1420 kLocalhostAddr, kAdbProxyTcpListenPort);
1421}
1422
1423void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1424 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1425 kArcAddr, kAdbServerPort, ifname,
1426 kLocalhostAddr, kAdbProxyTcpListenPort);
1427}
1428
1429bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1430 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1431 kAdbProxyTcpListenPort, ifname);
1432}
1433
1434void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1435 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1436 kAdbProxyTcpListenPort, ifname);
1437}
1438
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001439void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1440 if_nametoindex_[ifname] = ifindex;
1441}
1442
1443int Datapath::FindIfIndex(const std::string& ifname) {
1444 uint32_t ifindex = if_nametoindex(ifname.c_str());
1445 if (ifindex > 0) {
1446 if_nametoindex_[ifname] = ifindex;
1447 return ifindex;
1448 }
1449
1450 const auto it = if_nametoindex_.find(ifname);
1451 if (it != if_nametoindex_.end())
1452 return it->second;
1453
1454 return 0;
1455}
1456
Hugo Benichi8c526e92021-03-25 14:59:59 +09001457Fwmark Datapath::CachedRoutingFwmark(const std::string& ifname) {
1458 const auto it = if_nametoindex_.find(ifname);
1459 if (it != if_nametoindex_.end())
1460 return Fwmark::FromIfIndex(it->second);
1461
1462 LOG(WARNING) << "No interface index known for " << ifname;
1463 return Fwmark();
1464}
1465
Hugo Benichifcf81022020-12-04 11:01:37 +09001466std::ostream& operator<<(std::ostream& stream,
1467 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001468 stream << "{ pid: " << nsinfo.pid
1469 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001470 if (!nsinfo.outbound_ifname.empty()) {
1471 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1472 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001473 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1474 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001475 << ", peer_ifname: " << nsinfo.peer_ifname
1476 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1477 return stream;
1478}
1479
Garrick Evans3388a032020-03-24 11:25:55 +09001480} // namespace patchpanel