blob: c4678ada9d8b4d3925d2f1f494e633a5cd8b5288 [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.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900220 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", kFwmarkRouteOnVpn,
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900221 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 Benichid872d3d2021-03-29 10:20:53 +0900731 std::string subchain = "PREROUTING_" + int_ifname;
732 // This can fail if patchpanel did not stopped correctly or failed to cleanup
733 // the chain when |int_ifname| was previously deleted.
734 if (!AddChain(IpFamily::Dual, "mangle", subchain))
735 LOG(ERROR) << "Failed to create mangle chain " << subchain;
736 // Make sure the chain is empty if patchpanel did not cleaned correctly that
737 // chain before.
738 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
739 LOG(ERROR) << "Could not flush " << subchain;
740 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "PREROUTING", subchain,
741 int_ifname, "" /*oif*/))
742 LOG(ERROR) << "Could not add jump rule from mangle PREROUTING to "
743 << subchain;
744 if (!ModifyFwmarkSourceTag(subchain, "-A", source))
745 LOG(ERROR) << "Failed to add fwmark tagging rule for source " << source
746 << " in " << subchain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900747
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900748 if (!ext_ifname.empty()) {
749 // If |ext_ifname| is not null, mark egress traffic with the
750 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900751 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900752 if (ifindex == 0) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900753 LOG(ERROR) << "Failed to retrieve interface index of " << ext_ifname;
Hugo Benichid872d3d2021-03-29 10:20:53 +0900754 return;
Hugo Benichi8c526e92021-03-25 14:59:59 +0900755 }
Hugo Benichid872d3d2021-03-29 10:20:53 +0900756 if (!ModifyFwmarkRoutingTag(subchain, "-A", Fwmark::FromIfIndex(ifindex)))
757 LOG(ERROR) << "Failed to add fwmark routing tag for " << ext_ifname
758 << "<-" << int_ifname << " in " << subchain;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900759 } else {
760 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
761 // PREROUTING to apply any fwmark routing tag saved for the current
762 // connection, and rely on implicit routing to the default logical network
763 // otherwise.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900764 if (!ModifyConnmarkRestore(IpFamily::Dual, subchain, "-A", "" /*iif*/,
Hugo Benichi1af52392020-11-27 18:09:32 +0900765 kFwmarkRoutingMask))
Hugo Benichid872d3d2021-03-29 10:20:53 +0900766 LOG(ERROR) << "Failed to add CONNMARK restore rule in " << subchain;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900767
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900768 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900769 // default network is eligible to be routed through a VPN if |route_on_vpn|
770 // is true.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900771 if (route_on_vpn && !ModifyFwmarkVpnJumpRule(subchain, "-A", {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900772 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900773 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900774}
775
776void Datapath::StopRoutingDevice(const std::string& ext_ifname,
777 const std::string& int_ifname,
778 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900779 TrafficSource source,
780 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900781 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900782 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900783 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
784 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900785
786 std::string subchain = "PREROUTING_" + int_ifname;
787 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "PREROUTING", subchain,
788 int_ifname, "" /*oif*/);
789 FlushChain(IpFamily::Dual, "mangle", subchain);
790 RemoveChain(IpFamily::Dual, "mangle", subchain);
Hugo Benichi8d622b52020-08-13 15:24:12 +0900791}
792
Garrick Evansf0ab7132019-06-18 14:50:42 +0900793bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
794 const std::string& ipv4_addr) {
795 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900796 if (process_runner_->iptables(
797 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
798 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900799 return false;
800
801 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900802 if (process_runner_->iptables(
803 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
804 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900805 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
806 return false;
807 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900808 if (process_runner_->iptables(
809 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
810 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900811 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
812 return false;
813 }
814
815 return true;
816}
817
818void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
819 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900820 process_runner_->iptables(
821 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
822 "--to-destination", ipv4_addr, "-w"});
823 process_runner_->iptables(
824 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
825 "--to-destination", ipv4_addr, "-w"});
826 process_runner_->iptables(
827 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
828 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900829}
830
Hugo Benichid872d3d2021-03-29 10:20:53 +0900831// TODO(b/161060333) Migrate this rule to the PREROUTING_<iface> subchains
Hugo Benichie8758b52020-04-03 14:49:01 +0900832bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
833 return process_runner_->iptables(
834 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900835 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900836}
837
838void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
839 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900840 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900841}
842
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900843bool Datapath::AddRedirectDnsRule(const std::string& ifname,
844 const std::string dns_ipv4_addr) {
845 bool success = true;
846 success &= RemoveRedirectDnsRule(ifname);
847 // Use Insert operation to ensure that the new DNS address is used first.
848 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
849 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
850 physical_dns_addresses_[ifname] = dns_ipv4_addr;
851 return success;
852}
853
854bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
855 const auto it = physical_dns_addresses_.find(ifname);
856 if (it == physical_dns_addresses_.end())
857 return true;
858
859 bool success = true;
860 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
861 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
862 physical_dns_addresses_.erase(it);
863 return success;
864}
865
866bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
867 const std::string& protocol,
868 const std::string& ifname,
869 const std::string& dns_ipv4_addr) {
870 std::vector<std::string> args = {op,
871 kRedirectDnsChain,
872 "-p",
873 protocol,
874 "--dport",
875 "53",
876 "-o",
877 ifname,
878 "-j",
879 "DNAT",
880 "--to-destination",
881 dns_ipv4_addr,
882 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900883 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900884}
885
886bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
887 std::vector<std::string> args = {
888 op,
889 "OUTPUT",
890 "-m",
891 "mark",
892 "!",
893 "--mark",
894 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
895 "-j",
896 kRedirectDnsChain,
897 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900898 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900899}
900
Garrick Evans664a82f2019-12-17 12:18:05 +0900901bool Datapath::MaskInterfaceFlags(const std::string& ifname,
902 uint16_t on,
903 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900904 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
905 if (!sock.is_valid()) {
906 PLOG(ERROR) << "Failed to create control socket";
907 return false;
908 }
909 ifreq ifr;
910 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
911 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
912 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
913 return false;
914 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900915 ifr.ifr_flags |= on;
916 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900917 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900918 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
919 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900920 return false;
921 }
922 return true;
923}
924
Garrick Evans260ff302019-07-25 11:22:50 +0900925bool Datapath::AddIPv6HostRoute(const std::string& ifname,
926 const std::string& ipv6_addr,
927 int ipv6_prefix_len) {
928 std::string ipv6_addr_cidr =
929 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
930
Garrick Evans8e8e3472020-01-23 14:03:50 +0900931 return process_runner_->ip6("route", "replace",
932 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900933}
934
935void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
936 const std::string& ipv6_addr,
937 int ipv6_prefix_len) {
938 std::string ipv6_addr_cidr =
939 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
940
Garrick Evans8e8e3472020-01-23 14:03:50 +0900941 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900942}
943
Taoyu Lia0727dc2020-09-24 19:54:59 +0900944bool Datapath::AddIPv6Address(const std::string& ifname,
945 const std::string& ipv6_addr) {
946 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900947}
948
Taoyu Lia0727dc2020-09-24 19:54:59 +0900949void Datapath::RemoveIPv6Address(const std::string& ifname,
950 const std::string& ipv6_addr) {
951 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900952}
953
Hugo Benichi76be34a2020-08-26 22:35:54 +0900954void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900955 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +0900956 if (ifindex == 0) {
957 // Can happen if the interface has already been removed (b/183679000).
958 LOG(ERROR) << "Failed to set up connection pinning on " << ext_ifname;
959 return;
960 }
961
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900962 std::string subchain = "POSTROUTING_" + ext_ifname;
963 // This can fail if patchpanel did not stopped correctly or failed to cleanup
964 // the chain when |ext_ifname| was previously deleted.
965 if (!AddChain(IpFamily::Dual, "mangle", subchain))
966 LOG(ERROR) << "Failed to create mangle chain " << subchain;
967 // Make sure the chain is empty if patchpanel did not cleaned correctly that
968 // chain before.
969 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
970 LOG(ERROR) << "Could not flush " << subchain;
971 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "POSTROUTING", subchain,
972 "" /*iif*/, ext_ifname))
973 LOG(ERROR) << "Could not add jump rule from mangle POSTROUTING to "
974 << subchain;
975
Hugo Benichi8c526e92021-03-25 14:59:59 +0900976 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
977 LOG(INFO) << "Start connection pinning on " << ext_ifname
978 << " fwmark=" << routing_mark.ToString();
979 if (!ModifyIptables(
980 IpFamily::Dual, "mangle",
981 {"-A", kCheckRoutingMarkChain, "-o", ext_ifname, "-m", "mark", "!",
982 "--mark",
Hugo Benichi0a110402021-03-25 11:32:52 +0900983 routing_mark.ToString() + "/" + kFwmarkRoutingMask.ToString(),
984 "-w"}))
Hugo Benichi155de002021-01-19 16:45:46 +0900985 LOG(ERROR) << "Could not set fwmark routing filter rule for " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900986 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900987 if (!ModifyConnmarkSet(IpFamily::Dual, subchain, "-A", routing_mark,
988 kFwmarkRoutingMask))
Hugo Benichi76be34a2020-08-26 22:35:54 +0900989 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900990 // Save in CONNMARK the source tag for egress traffic of this connection.
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900991 if (!ModifyConnmarkSave(IpFamily::Dual, subchain, "-A",
Hugo Benichi1af52392020-11-27 18:09:32 +0900992 kFwmarkAllSourcesMask))
993 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
994 "source tag on "
995 << ext_ifname;
996 // Restore from CONNMARK the source tag for ingress traffic of this connection
997 // (returned traffic).
998 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
999 kFwmarkAllSourcesMask))
1000 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
1001 "traffic received on "
1002 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +09001003}
1004
1005void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +09001006 std::string subchain = "POSTROUTING_" + ext_ifname;
1007 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "POSTROUTING", subchain,
1008 "" /*iif*/, ext_ifname);
1009 FlushChain(IpFamily::Dual, "mangle", subchain);
1010 RemoveChain(IpFamily::Dual, "mangle", subchain);
1011 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
1012 kFwmarkAllSourcesMask))
1013 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
1014 "traffic received on "
1015 << ext_ifname;
1016
1017 // TODO(b/183679000) Reorganize these rules such that they can be removed
1018 // with just the interface name.
Hugo Benichi8c526e92021-03-25 14:59:59 +09001019 Fwmark routing_mark = CachedRoutingFwmark(ext_ifname);
1020 LOG(INFO) << "Stop connection pinning on " << ext_ifname
1021 << " fwmark=" << routing_mark.ToString();
1022 if (!ModifyIptables(
1023 IpFamily::Dual, "mangle",
1024 {"-D", kCheckRoutingMarkChain, "-o", ext_ifname, "-m", "mark", "!",
1025 "--mark",
Hugo Benichi0a110402021-03-25 11:32:52 +09001026 routing_mark.ToString() + "/" + kFwmarkRoutingMask.ToString(),
1027 "-w"}))
Hugo Benichi155de002021-01-19 16:45:46 +09001028 LOG(ERROR) << "Could not remove fwmark routing filter rule for "
1029 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +09001030}
1031
Hugo Benichi2a940542020-10-26 18:50:49 +09001032void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +09001033 int ifindex = FindIfIndex(vpn_ifname);
1034 if (ifindex == 0) {
1035 // Can happen if the interface has already been removed (b/183679000).
1036 LOG(ERROR) << "Failed to start VPN routing on " << vpn_ifname;
1037 return;
1038 }
1039
1040 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
1041 LOG(INFO) << "Start VPN routing on " << vpn_ifname
1042 << " fwmark=" << routing_mark.ToString();
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001043 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-A", "POSTROUTING", "MASQUERADE",
1044 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +09001045 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +09001046 StartConnectionPinning(vpn_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +09001047 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", routing_mark))
Hugo Benichi2a940542020-10-26 18:50:49 +09001048 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +09001049 if (vpn_ifname != kArcBridge)
1050 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
1051 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001052 if (!ModifyRedirectDnsJumpRule("-A"))
1053 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001054}
1055
1056void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +09001057 Fwmark routing_mark = CachedRoutingFwmark(vpn_ifname);
1058 LOG(INFO) << "Stop VPN routing on " << vpn_ifname
1059 << " fwmark=" << routing_mark.ToString();
Hugo Benichibfc49112020-12-14 12:54:44 +09001060 if (vpn_ifname != kArcBridge)
1061 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
1062 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichid872d3d2021-03-29 10:20:53 +09001063 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", routing_mark))
Hugo Benichi2a940542020-10-26 18:50:49 +09001064 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
1065 StopConnectionPinning(vpn_ifname);
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001066 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-D", "POSTROUTING", "MASQUERADE",
1067 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +09001068 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001069 if (!ModifyRedirectDnsJumpRule("-D"))
1070 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001071}
1072
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001073bool Datapath::ModifyConnmarkSet(IpFamily family,
1074 const std::string& chain,
1075 const std::string& op,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001076 Fwmark mark,
1077 Fwmark mask) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +09001078 return ModifyIptables(family, "mangle",
1079 {op, chain, "-j", "CONNMARK", "--set-mark",
1080 mark.ToString() + "/" + mask.ToString(), "-w"});
Hugo Benichi76be34a2020-08-26 22:35:54 +09001081}
1082
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001083bool Datapath::ModifyConnmarkRestore(IpFamily family,
1084 const std::string& chain,
1085 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001086 const std::string& iif,
1087 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001088 std::vector<std::string> args = {op, chain};
1089 if (!iif.empty()) {
1090 args.push_back("-i");
1091 args.push_back(iif);
1092 }
1093 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001094 mask.ToString(), "-w"});
1095 return ModifyIptables(family, "mangle", args);
1096}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001097
Hugo Benichi1af52392020-11-27 18:09:32 +09001098bool Datapath::ModifyConnmarkSave(IpFamily family,
1099 const std::string& chain,
1100 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001101 Fwmark mask) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +09001102 std::vector<std::string> args = {
1103 op, chain, "-j", "CONNMARK", "--save-mark",
1104 "--mask", mask.ToString(), "-w"};
Hugo Benichi58f264a2020-10-16 18:16:05 +09001105 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001106}
1107
Hugo Benichi2a940542020-10-26 18:50:49 +09001108bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1109 const std::string& op,
Hugo Benichid872d3d2021-03-29 10:20:53 +09001110 Fwmark routing_mark) {
1111 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*int_ifname*/,
1112 "" /*uid_name*/, 0 /*classid*/, routing_mark,
1113 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001114}
1115
Hugo Benichid872d3d2021-03-29 10:20:53 +09001116bool Datapath::ModifyFwmarkSourceTag(const std::string& chain,
1117 const std::string& op,
Hugo Benichi9be19b12020-08-14 15:33:40 +09001118 TrafficSource source) {
Hugo Benichid872d3d2021-03-29 10:20:53 +09001119 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*iif*/, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001120 0 /*classid*/, Fwmark::FromSource(source),
1121 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001122}
1123
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001124bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1125 TrafficSource source) {
1126 std::vector<std::string> args = {"-A",
1127 kApplyLocalSourceMarkChain,
1128 "-m",
1129 "mark",
1130 "--mark",
1131 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1132 "-j",
1133 "MARK",
1134 "--set-mark",
1135 Fwmark::FromSource(source).ToString() + "/" +
1136 kFwmarkAllSourcesMask.ToString(),
1137 "-w"};
1138 return ModifyIptables(IpFamily::Dual, "mangle", args);
1139}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001140
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001141bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1142 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001143 if (std::string(source.uid_name).empty() && source.classid == 0)
1144 return false;
1145
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001146 Fwmark mark = Fwmark::FromSource(source.source_type);
1147 if (source.is_on_vpn)
1148 mark = mark | kFwmarkRouteOnVpn;
1149
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001150 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1151 "" /*iif*/, source.uid_name, source.classid, mark,
1152 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001153}
1154
1155bool Datapath::ModifyFwmark(IpFamily family,
1156 const std::string& chain,
1157 const std::string& op,
1158 const std::string& iif,
1159 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001160 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001161 Fwmark mark,
1162 Fwmark mask,
1163 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001164 std::vector<std::string> args = {op, chain};
1165 if (!iif.empty()) {
1166 args.push_back("-i");
1167 args.push_back(iif);
1168 }
1169 if (!uid_name.empty()) {
1170 args.push_back("-m");
1171 args.push_back("owner");
1172 args.push_back("--uid-owner");
1173 args.push_back(uid_name);
1174 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001175 if (classid != 0) {
1176 args.push_back("-m");
1177 args.push_back("cgroup");
1178 args.push_back("--cgroup");
1179 args.push_back(base::StringPrintf("0x%08x", classid));
1180 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001181 args.push_back("-j");
1182 args.push_back("MARK");
1183 args.push_back("--set-mark");
1184 args.push_back(mark.ToString() + "/" + mask.ToString());
1185 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001186
Hugo Benichi58f264a2020-10-16 18:16:05 +09001187 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001188}
1189
Hugo Benichid82d8832020-08-14 10:05:03 +09001190bool Datapath::ModifyIpForwarding(IpFamily family,
1191 const std::string& op,
1192 const std::string& iif,
1193 const std::string& oif,
1194 bool log_failures) {
1195 if (iif.empty() && oif.empty()) {
1196 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1197 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001198 return false;
1199 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001200 return ModifyJumpRule(family, "filter", op, "FORWARD", "ACCEPT", iif, oif,
1201 log_failures);
1202}
Garrick Evans260ff302019-07-25 11:22:50 +09001203
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001204bool Datapath::ModifyJumpRule(IpFamily family,
1205 const std::string& table,
1206 const std::string& op,
1207 const std::string& chain,
1208 const std::string& target,
1209 const std::string& iif,
1210 const std::string& oif,
1211 bool log_failures) {
1212 std::vector<std::string> args = {op, chain};
Hugo Benichid82d8832020-08-14 10:05:03 +09001213 if (!iif.empty()) {
1214 args.push_back("-i");
1215 args.push_back(iif);
1216 }
1217 if (!oif.empty()) {
1218 args.push_back("-o");
1219 args.push_back(oif);
1220 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001221 args.insert(args.end(), {"-j", target, "-w"});
1222 return ModifyIptables(family, table, args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001223}
1224
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001225bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1226 const std::string& op,
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001227 Fwmark mark,
1228 Fwmark mask) {
1229 std::vector<std::string> args = {op, chain};
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001230 if (mark.Value() != 0 && mask.Value() != 0) {
1231 args.push_back("-m");
1232 args.push_back("mark");
1233 args.push_back("--mark");
1234 args.push_back(mark.ToString() + "/" + mask.ToString());
1235 }
1236 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1237 return ModifyIptables(IpFamily::Dual, "mangle", args);
1238}
1239
Hugo Benichif0f55562021-04-02 15:25:02 +09001240bool Datapath::AddChain(IpFamily family,
1241 const std::string& table,
1242 const std::string& name) {
1243 DCHECK(name.size() <= kIptablesMaxChainLength);
1244 return ModifyChain(family, table, "-N", name);
1245}
1246
1247bool Datapath::RemoveChain(IpFamily family,
1248 const std::string& table,
1249 const std::string& name) {
1250 return ModifyChain(family, table, "-X", name);
1251}
1252
1253bool Datapath::FlushChain(IpFamily family,
1254 const std::string& table,
1255 const std::string& name) {
1256 return ModifyChain(family, table, "-F", name);
1257}
1258
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001259bool Datapath::ModifyChain(IpFamily family,
1260 const std::string& table,
1261 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001262 const std::string& chain,
1263 bool log_failures) {
1264 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001265}
1266
1267bool Datapath::ModifyIptables(IpFamily family,
1268 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001269 const std::vector<std::string>& argv,
1270 bool log_failures) {
1271 switch (family) {
1272 case IPv4:
1273 case IPv6:
1274 case Dual:
1275 break;
1276 default:
1277 LOG(ERROR) << "Could not execute iptables command " << table
1278 << base::JoinString(argv, " ") << ": incorrect IP family "
1279 << family;
1280 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001281 }
1282
1283 bool success = true;
1284 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001285 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001286 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001287 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001288 return success;
1289}
1290
Hugo Benichid82d8832020-08-14 10:05:03 +09001291bool Datapath::StartIpForwarding(IpFamily family,
1292 const std::string& iif,
1293 const std::string& oif) {
1294 return ModifyIpForwarding(family, "-A", iif, oif);
1295}
1296
1297bool Datapath::StopIpForwarding(IpFamily family,
1298 const std::string& iif,
1299 const std::string& oif) {
1300 return ModifyIpForwarding(family, "-D", iif, oif);
1301}
1302
1303bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1304 const std::string& ifname2) {
1305 // Only start Ipv6 forwarding if -C returns false and it had not been
1306 // started yet.
1307 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1308 false /*log_failures*/) &&
1309 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1310 return false;
1311 }
1312
1313 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1314 false /*log_failures*/) &&
1315 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001316 RemoveIPv6Forwarding(ifname1, ifname2);
1317 return false;
1318 }
1319
1320 return true;
1321}
1322
1323void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1324 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001325 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1326 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001327}
1328
Garrick Evans3d97a392020-02-21 15:24:37 +09001329bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1330 uint32_t addr,
1331 uint32_t netmask) {
1332 struct rtentry route;
1333 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001334 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1335 SetSockaddrIn(&route.rt_dst, addr & netmask);
1336 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001337 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001338 return ModifyRtentry(SIOCADDRT, &route);
1339}
Garrick Evans3d97a392020-02-21 15:24:37 +09001340
Hugo Benichie8758b52020-04-03 14:49:01 +09001341bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1342 uint32_t addr,
1343 uint32_t netmask) {
1344 struct rtentry route;
1345 memset(&route, 0, sizeof(route));
1346 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1347 SetSockaddrIn(&route.rt_dst, addr & netmask);
1348 SetSockaddrIn(&route.rt_genmask, netmask);
1349 route.rt_flags = RTF_UP | RTF_GATEWAY;
1350 return ModifyRtentry(SIOCDELRT, &route);
1351}
1352
1353bool Datapath::AddIPv4Route(const std::string& ifname,
1354 uint32_t addr,
1355 uint32_t netmask) {
1356 struct rtentry route;
1357 memset(&route, 0, sizeof(route));
1358 SetSockaddrIn(&route.rt_dst, addr & netmask);
1359 SetSockaddrIn(&route.rt_genmask, netmask);
1360 char rt_dev[IFNAMSIZ];
1361 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1362 rt_dev[IFNAMSIZ - 1] = '\0';
1363 route.rt_dev = rt_dev;
1364 route.rt_flags = RTF_UP | RTF_GATEWAY;
1365 return ModifyRtentry(SIOCADDRT, &route);
1366}
1367
1368bool Datapath::DeleteIPv4Route(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(SIOCDELRT, &route);
1381}
1382
Taoyu Lia0727dc2020-09-24 19:54:59 +09001383bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001384 DCHECK(route);
1385 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001386 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001387 return false;
1388 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001389 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1390 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001391 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001392 return false;
1393 }
1394 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1395 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001396 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001397 return false;
1398 }
1399 return true;
1400}
1401
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001402bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1403 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1404 kArcAddr, kAdbServerPort, ifname,
1405 kLocalhostAddr, kAdbProxyTcpListenPort);
1406}
1407
1408void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1409 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1410 kArcAddr, kAdbServerPort, ifname,
1411 kLocalhostAddr, kAdbProxyTcpListenPort);
1412}
1413
1414bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1415 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1416 kAdbProxyTcpListenPort, ifname);
1417}
1418
1419void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1420 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1421 kAdbProxyTcpListenPort, ifname);
1422}
1423
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001424void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1425 if_nametoindex_[ifname] = ifindex;
1426}
1427
1428int Datapath::FindIfIndex(const std::string& ifname) {
1429 uint32_t ifindex = if_nametoindex(ifname.c_str());
1430 if (ifindex > 0) {
1431 if_nametoindex_[ifname] = ifindex;
1432 return ifindex;
1433 }
1434
1435 const auto it = if_nametoindex_.find(ifname);
1436 if (it != if_nametoindex_.end())
1437 return it->second;
1438
1439 return 0;
1440}
1441
Hugo Benichi8c526e92021-03-25 14:59:59 +09001442Fwmark Datapath::CachedRoutingFwmark(const std::string& ifname) {
1443 const auto it = if_nametoindex_.find(ifname);
1444 if (it != if_nametoindex_.end())
1445 return Fwmark::FromIfIndex(it->second);
1446
1447 LOG(WARNING) << "No interface index known for " << ifname;
1448 return Fwmark();
1449}
1450
Hugo Benichifcf81022020-12-04 11:01:37 +09001451std::ostream& operator<<(std::ostream& stream,
1452 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001453 stream << "{ pid: " << nsinfo.pid
1454 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001455 if (!nsinfo.outbound_ifname.empty()) {
1456 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1457 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001458 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1459 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001460 << ", peer_ifname: " << nsinfo.peer_ifname
1461 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1462 return stream;
1463}
1464
Garrick Evans3388a032020-03-24 11:25:55 +09001465} // namespace patchpanel