blob: fd9890613025c723d558efddf810789ac48bcc9e [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 Benichi1e0656f2021-02-15 15:43:38 +090053constexpr char kDropGuestIpv4PrefixChain[] = "drop_guest_ipv4_prefix";
54constexpr char kRedirectDnsChain[] = "redirect_dns";
Hugo Benichibb38bdd2021-05-14 10:36:11 +090055constexpr char kVpnAcceptChain[] = "vpn_accept";
56constexpr char kVpnLockdownChain[] = "vpn_lockdown";
Hugo Benichi2a940542020-10-26 18:50:49 +090057
Hugo Benichif0f55562021-04-02 15:25:02 +090058// Maximum length of an iptables chain name.
59constexpr int kIptablesMaxChainLength = 28;
60
Garrick Evans8a067562020-05-11 12:47:30 +090061std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
62 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090063 if (n.length() < IFNAMSIZ)
64 return n;
Garrick Evans54861622019-07-19 09:05:09 +090065
Garrick Evans2f581a02020-05-11 10:43:35 +090066 // Best effort attempt to preserve the interface number, assuming it's the
67 // last char in the name.
68 auto c = ifname[ifname.length() - 1];
69 n.resize(IFNAMSIZ - 1);
70 n[n.length() - 1] = c;
71 return n;
Garrick Evans54861622019-07-19 09:05:09 +090072}
Garrick Evansf0ab7132019-06-18 14:50:42 +090073
Hugo Benichiaba7e2e2021-02-22 14:47:11 +090074bool Ioctl(ioctl_t ioctl_h, unsigned long req, const char* arg) {
75 base::ScopedFD control_fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
76 if (!control_fd.is_valid()) {
77 PLOG(ERROR) << "Failed to create control socket for ioctl request=" << req;
78 return false;
79 }
80 if ((*ioctl_h)(control_fd.get(), req, arg) != 0) {
81 PLOG(ERROR) << "ioctl request=" << req << " failed";
82 return false;
83 }
84 return true;
85}
86
Garrick Evans8a067562020-05-11 12:47:30 +090087} // namespace
88
89std::string ArcVethHostName(const std::string& ifname) {
90 return PrefixIfname("veth", ifname);
91}
92
93std::string ArcBridgeName(const std::string& ifname) {
94 return PrefixIfname("arc_", ifname);
95}
96
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090097Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
98 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090099
Jason Jeremy Imana7273a32020-08-04 11:25:31 +0900100Datapath::Datapath(MinijailedProcessRunner* process_runner,
101 Firewall* firewall,
102 ioctl_t ioctl_hook)
103 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900104 CHECK(process_runner_);
105}
106
Garrick Evans260ff302019-07-25 11:22:50 +0900107MinijailedProcessRunner& Datapath::runner() const {
108 return *process_runner_;
109}
110
Hugo Benichibf811c62020-09-07 17:30:45 +0900111void Datapath::Start() {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900112 // Restart from a clean iptables state in case of an unordered shutdown.
113 ResetIptables();
114
Hugo Benichibf811c62020-09-07 17:30:45 +0900115 // Enable IPv4 packet forwarding
116 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
117 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
118 << " Guest connectivity will not work correctly.";
119
120 // Limit local port range: Android owns 47104-61000.
121 // TODO(garrick): The original history behind this tweak is gone. Some
122 // investigation is needed to see if it is still applicable.
123 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
124 "32768 47103") != 0)
125 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
126 << " apps may not work correctly.";
127
128 // Enable IPv6 packet forwarding
129 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
130 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
131 << " IPv6 functionality may be broken.";
132
Hugo Benichi58125d32020-09-09 11:25:45 +0900133 // Create a FORWARD ACCEPT rule for connections already established.
134 if (process_runner_->iptables(
135 "filter", {"-A", "FORWARD", "-m", "state", "--state",
136 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900137 LOG(ERROR) << "Failed to install forwarding rule for established"
138 << " connections.";
139
Hugo Benichiac799a82021-03-25 00:16:16 +0900140 // Create a FORWARD rule for accepting any ARC originated traffic regardless
141 // of the output interface. This enables for ARC certain multihoming
142 // scenarios (b/182594063).
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900143 if (!ModifyJumpRule(IpFamily::IPv4, "filter", "-A", "FORWARD", "ACCEPT",
144 "arc+", "" /*oif*/))
Hugo Benichiac799a82021-03-25 00:16:16 +0900145 LOG(ERROR) << "Failed to install forwarding rule for ARC traffic";
146
Hugo Benichibf811c62020-09-07 17:30:45 +0900147 // chromium:898210: Drop any locally originated traffic that would exit a
148 // physical interface with a source IPv4 address from the subnet of IPs used
149 // for VMs, containers, and connected namespaces This is needed to prevent
150 // packets leaking with an incorrect src IP when a local process binds to the
151 // wrong interface.
Hugo Benichif0f55562021-04-02 15:25:02 +0900152 if (!AddChain(IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain))
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900153 LOG(ERROR) << "Failed to create " << kDropGuestIpv4PrefixChain
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900154 << " filter chain";
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900155 if (!ModifyJumpRule(IpFamily::IPv4, "filter", "-I", "OUTPUT",
156 kDropGuestIpv4PrefixChain, "" /*iif*/, "" /*oif*/))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900157 LOG(ERROR) << "Failed to set up jump rule from filter OUTPUT to "
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900158 << kDropGuestIpv4PrefixChain;
Hugo Benichibf811c62020-09-07 17:30:45 +0900159 for (const auto& oif : kPhysicalIfnamePrefixes) {
160 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
161 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
162 << kGuestIPv4Subnet << " exiting " << oif;
163 }
164
Hugo Benichibb38bdd2021-05-14 10:36:11 +0900165 // Create filter subchains for managing the egress firewall rules associated
166 // with VPN lockdown. When VPN lockdown is enabled, a REJECT rule must stop
167 // any egress traffic tagged with the |kFwmarkRouteOnVpn| intent mark. This
168 // REJECT rule is added to |kVpnLockdownChain|. In addition, when VPN lockdown
169 // is enabled and a VPN is connected, an ACCEPT rule protects the traffic
170 // tagged with the VPN routing mark from being reject by the VPN lockdown
171 // rule. This ACCEPT rule is added to |kVpnAcceptChain|. Therefore, egress
172 // traffic must:
173 // - traverse kVpnAcceptChain before kVpnLockdownChain,
174 // - traverse kVpnLockdownChain before other ACCEPT rules in OUTPUT and
175 // FORWARD.
176 std::vector<std::string> vpn_chains = {kVpnLockdownChain, kVpnAcceptChain};
177 for (const auto& chain : vpn_chains) {
178 if (!AddChain(IpFamily::Dual, "filter", chain))
179 LOG(ERROR) << "Failed to create " << chain << " filter chain";
180 if (!ModifyJumpRule(IpFamily::Dual, "filter", "-I", "OUTPUT", chain,
181 "" /*iif*/, "" /*oif*/))
182 LOG(ERROR) << "Failed to set up jump rule from filter OUTPUT to "
183 << chain;
184 if (!ModifyJumpRule(IpFamily::Dual, "filter", "-I", "FORWARD", chain,
185 "" /*iif*/, "" /*oif*/))
186 LOG(ERROR) << "Failed to set up jump rule from filter FORWARD to "
187 << chain;
188 }
189
Hugo Benichi561fae42021-01-22 15:28:40 +0900190 // Set static SNAT rules for any IPv4 traffic originated from a guest (ARC,
191 // Crostini, ...) or a connected namespace.
192 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
193 // need to be explicitly dropped as SNAT cannot be applied to them.
Hugo Benichi7a066242021-04-07 23:47:32 +0900194 std::string snatMark =
195 kFwmarkLegacySNAT.ToString() + "/" + kFwmarkLegacySNAT.ToString();
Hugo Benichi561fae42021-01-22 15:28:40 +0900196 if (process_runner_->iptables(
Hugo Benichi7a066242021-04-07 23:47:32 +0900197 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", snatMark, "-m",
Hugo Benichi561fae42021-01-22 15:28:40 +0900198 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0)
199 LOG(ERROR) << "Failed to install SNAT mark rules.";
200 if (process_runner_->iptables(
Hugo Benichi7a066242021-04-07 23:47:32 +0900201 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", snatMark, "-j",
Hugo Benichi561fae42021-01-22 15:28:40 +0900202 "MASQUERADE", "-w"}) != 0)
203 LOG(ERROR) << "Failed to install SNAT mark rules.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900204
Hugo Benichi2a940542020-10-26 18:50:49 +0900205 // Applies the routing tag saved in conntrack for any established connection
206 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900207 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
208 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900209 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
210
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900211 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
212 // tag and tagging the local traffic that should be routed through a VPN.
Hugo Benichif0f55562021-04-02 15:25:02 +0900213 if (!AddChain(IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900214 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
215 << " mangle chain";
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900216 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "OUTPUT",
217 kApplyLocalSourceMarkChain, "" /*iif*/, "" /*oif*/))
218
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900219 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
220 << " to mangle OUTPUT";
221 // Create rules for tagging local sources with the source tag and the vpn
222 // policy tag.
223 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900224 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900225 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
226 << " in " << kApplyLocalSourceMarkChain;
227 }
228 // Finally add a catch-all rule for tagging any remaining local sources with
229 // the SYSTEM source tag
230 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
231 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
232
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900233 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
234 // traffic that should be routed through a VPN.
Hugo Benichif0f55562021-04-02 15:25:02 +0900235 if (!AddChain(IpFamily::Dual, "mangle", kApplyVpnMarkChain))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900236 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900237 // All local outgoing traffic eligible to VPN routing should traverse the VPN
238 // marking chain.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900239 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", kFwmarkRouteOnVpn,
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900240 kFwmarkVpnMask))
241 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
Hugo Benichi155de002021-01-19 16:45:46 +0900242
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900243 // b/178331695 Sets up a nat chain used in OUTPUT for redirecting DNS queries
244 // of system services. When a VPN is connected, a query routed through a
245 // physical network is redirected to the primary nameserver of that network.
Hugo Benichif0f55562021-04-02 15:25:02 +0900246 if (!AddChain(IpFamily::IPv4, "nat", kRedirectDnsChain))
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900247 LOG(ERROR) << "Failed to set up " << kRedirectDnsChain << " nat chain";
248
Hugo Benichi52a64992021-01-28 17:47:33 +0900249 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
250 // incorrectly cause neighbor discovery icmpv6 packets to be dropped. Add
251 // these rules to bypass connmark rule for those packets.
252 for (const auto& type : kNeighborDiscoveryTypes) {
253 if (!ModifyIptables(IpFamily::IPv6, "mangle",
254 {"-I", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
255 "-j", "ACCEPT", "-w"}))
256 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
257 << " packets in OUTPUT";
Hugo Benichi52a64992021-01-28 17:47:33 +0900258 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900259}
260
261void Datapath::Stop() {
Hugo Benichibf811c62020-09-07 17:30:45 +0900262 // Restore original local port range.
263 // TODO(garrick): The original history behind this tweak is gone. Some
264 // investigation is needed to see if it is still applicable.
265 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
266 "32768 61000") != 0)
267 LOG(ERROR) << "Failed to restore local port range";
268
269 // Disable packet forwarding
270 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
271 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
272
273 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
274 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900275
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900276 ResetIptables();
277}
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900278
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900279void Datapath::ResetIptables() {
Hugo Benichibb38bdd2021-05-14 10:36:11 +0900280 // If they exists, remove jump rules from built-in chains to custom chains
281 // for any built-in chains that is not explicitly flushed.
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900282 ModifyJumpRule(IpFamily::IPv4, "filter", "-D", "OUTPUT",
283 kDropGuestIpv4PrefixChain, "" /*iif*/, "" /*oif*/,
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900284 false /*log_failures*/);
Hugo Benichibb38bdd2021-05-14 10:36:11 +0900285 std::vector<std::string> vpn_chains = {kVpnAcceptChain, kVpnLockdownChain};
286 for (const auto& chain : vpn_chains) {
287 ModifyJumpRule(IpFamily::Dual, "filter", "-D", "OUTPUT", chain, "" /*iif*/,
288 "" /*oif*/, false /*log_failures*/);
289 ModifyJumpRule(IpFamily::Dual, "filter", "-D", "FORWARD", chain, "" /*iif*/,
290 "" /*oif*/, false /*log_failures*/);
291 }
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.
Hugo Benichibb38bdd2021-05-14 10:36:11 +0900297 // If there is any jump rule between from a chain to another chain that must
298 // be removed, the first chain must be flushed first.
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900299 static struct {
300 IpFamily family;
301 std::string table;
302 std::string chain;
303 bool should_delete;
304 } resetOps[] = {
305 {IpFamily::Dual, "filter", "FORWARD", false},
306 {IpFamily::Dual, "mangle", "FORWARD", false},
307 {IpFamily::Dual, "mangle", "INPUT", false},
308 {IpFamily::Dual, "mangle", "OUTPUT", false},
309 {IpFamily::Dual, "mangle", "POSTROUTING", false},
310 {IpFamily::Dual, "mangle", "PREROUTING", false},
311 {IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain, true},
312 {IpFamily::Dual, "mangle", kApplyVpnMarkChain, true},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900313 {IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain, true},
Hugo Benichibb38bdd2021-05-14 10:36:11 +0900314 {IpFamily::Dual, "filter", kVpnAcceptChain, true},
315 {IpFamily::Dual, "filter", kVpnLockdownChain, true},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900316 {IpFamily::IPv4, "nat", "POSTROUTING", false},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900317 {IpFamily::IPv4, "nat", "OUTPUT", false},
Hugo Benichibb38bdd2021-05-14 10:36:11 +0900318 {IpFamily::IPv4, "nat", kRedirectDnsChain, true},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900319 };
320 for (const auto& op : resetOps) {
321 // Chains to delete are custom chains and will not exist the first time
322 // patchpanel starts after boot. Skip flushing and delete these chains if
323 // they do not exist to avoid logging spurious error messages.
324 if (op.should_delete && !ModifyChain(op.family, op.table, "-L", op.chain,
325 false /*log_failures*/))
326 continue;
Hugo Benichi155de002021-01-19 16:45:46 +0900327
Hugo Benichif0f55562021-04-02 15:25:02 +0900328 if (!FlushChain(op.family, op.table, op.chain))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900329 LOG(ERROR) << "Failed to flush " << op.chain << " chain in table "
330 << op.table;
Hugo Benichi2a940542020-10-26 18:50:49 +0900331
Hugo Benichif0f55562021-04-02 15:25:02 +0900332 if (op.should_delete && !RemoveChain(op.family, op.table, op.chain))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900333 LOG(ERROR) << "Failed to delete " << op.chain << " chain in table "
334 << op.table;
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900335 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900336}
337
Hugo Benichi33860d72020-07-09 16:34:01 +0900338bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
339 // Try first to delete any netns with name |netns_name| in case patchpanel
340 // did not exit cleanly.
341 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
342 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
Jie Jiangf6799312021-05-14 16:27:03 +0900343
344 if (netns_pid == ConnectedNamespace::kNewNetnsPid)
345 return process_runner_->ip_netns_add(netns_name) == 0;
346 else
347 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
Hugo Benichi33860d72020-07-09 16:34:01 +0900348}
349
350bool Datapath::NetnsDeleteName(const std::string& netns_name) {
351 return process_runner_->ip_netns_delete(netns_name) == 0;
352}
353
Garrick Evans8a949dc2019-07-18 16:17:53 +0900354bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900355 uint32_t ipv4_addr,
356 uint32_t ipv4_prefix_len) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900357 if (!Ioctl(ioctl_, SIOCBRADDBR, ifname.c_str())) {
358 LOG(ERROR) << "Failed to create bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900359 return false;
360 }
361
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900362 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900363 if (process_runner_->ip(
364 "addr", "add",
365 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
366 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
367 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900368 RemoveBridge(ifname);
369 return false;
370 }
371
372 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900373 RemoveBridge(ifname);
374 return false;
375 }
376
Garrick Evans8a949dc2019-07-18 16:17:53 +0900377 return true;
378}
379
380void Datapath::RemoveBridge(const std::string& 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 {
Jie Jiangf6799312021-05-14 16:27:03 +0900527 auto ns = ScopedNS::EnterNetworkNS(netns_name);
528 if (!ns && 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
Hugo Benichifcf81022020-12-04 11:01:37 +0900602bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900603 // Veth interface configuration and client routing configuration:
Jie Jiangf6799312021-05-14 16:27:03 +0900604 // - attach a name to the client namespace (or create a new named namespace
605 // if no client is specified).
Hugo Benichi7c342672020-09-08 09:18:14 +0900606 // - create veth pair across the current namespace and the client namespace.
607 // - configure IPv4 address on remote veth inside client namespace.
608 // - configure IPv4 address on local veth inside host namespace.
609 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900610 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
611 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
612 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900613 return false;
614 }
615
Hugo Benichifcf81022020-12-04 11:01:37 +0900616 if (!ConnectVethPair(
617 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
618 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
619 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900620 LOG(ERROR) << "Failed to create veth pair for"
621 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900622 << nsinfo.pid;
623 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900624 return false;
625 }
626
Hugo Benichifcf81022020-12-04 11:01:37 +0900627 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
628 nsinfo.peer_subnet->AddressAtOffset(0),
629 nsinfo.peer_subnet->PrefixLength(),
630 true /* link up */, false /* enable_multicast */)) {
631 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
632 RemoveInterface(nsinfo.host_ifname);
633 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900634 return false;
635 }
636
637 {
Jie Jiangf6799312021-05-14 16:27:03 +0900638 auto ns = ScopedNS::EnterNetworkNS(nsinfo.netns_name);
639 if (!ns && nsinfo.pid != kTestPID) {
Hugo Benichifcf81022020-12-04 11:01:37 +0900640 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
641 RemoveInterface(nsinfo.host_ifname);
642 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900643 return false;
644 }
645
Hugo Benichifcf81022020-12-04 11:01:37 +0900646 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
647 INADDR_ANY)) {
648 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
649 << " inside namespace pid " << nsinfo.pid;
650 RemoveInterface(nsinfo.host_ifname);
651 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900652 return false;
653 }
654 }
655
656 // Host namespace routing configuration
657 // - ingress: add route to client subnet via |host_ifname|.
658 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
659 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
660 // Note that by default unsolicited ingress traffic is not forwarded to the
661 // client namespace unless the client specifically set port forwarding
662 // through permission_broker DBus APIs.
663 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
664 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900665 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
666 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
667 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900668 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900669 RemoveInterface(nsinfo.host_ifname);
670 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900671 return false;
672 }
673
Hugo Benichi93306e52020-12-04 16:08:00 +0900674 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
675 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
676 nsinfo.route_on_vpn);
Hugo Benichi7c342672020-09-08 09:18:14 +0900677 return true;
678}
679
Hugo Benichifcf81022020-12-04 11:01:37 +0900680void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900681 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
682 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
683 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900684 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900685 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
686 nsinfo.peer_subnet->BaseAddress(),
687 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
688 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900689}
690
Hugo Benichi8d622b52020-08-13 15:24:12 +0900691void Datapath::StartRoutingDevice(const std::string& ext_ifname,
692 const std::string& int_ifname,
693 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900694 TrafficSource source,
695 bool route_on_vpn) {
696 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900697 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900698 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
699 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
700 << "->" << int_ifname;
701
Hugo Benichi954bae62021-04-09 09:12:30 +0900702 if (!ModifyIpForwarding(IpFamily::IPv4, "-A", ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900703 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
704 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900705
Hugo Benichi954bae62021-04-09 09:12:30 +0900706 if (!ModifyIpForwarding(IpFamily::IPv4, "-A", int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900707 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
708 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900709
Hugo Benichid872d3d2021-03-29 10:20:53 +0900710 std::string subchain = "PREROUTING_" + int_ifname;
711 // This can fail if patchpanel did not stopped correctly or failed to cleanup
712 // the chain when |int_ifname| was previously deleted.
713 if (!AddChain(IpFamily::Dual, "mangle", subchain))
714 LOG(ERROR) << "Failed to create mangle chain " << subchain;
715 // Make sure the chain is empty if patchpanel did not cleaned correctly that
716 // chain before.
717 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
718 LOG(ERROR) << "Could not flush " << subchain;
719 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "PREROUTING", subchain,
720 int_ifname, "" /*oif*/))
721 LOG(ERROR) << "Could not add jump rule from mangle PREROUTING to "
722 << subchain;
Hugo Benichi7a066242021-04-07 23:47:32 +0900723 // IPv4 traffic from all downstream devices should be tagged to go through
724 // SNAT.
725 if (!ModifyFwmark(IpFamily::IPv4, subchain, "-A", "", "", 0,
726 kFwmarkLegacySNAT, kFwmarkLegacySNAT))
727 LOG(ERROR) << "Failed to add fwmark SNAT tagging rule for " << int_ifname;
Hugo Benichid872d3d2021-03-29 10:20:53 +0900728 if (!ModifyFwmarkSourceTag(subchain, "-A", source))
729 LOG(ERROR) << "Failed to add fwmark tagging rule for source " << source
730 << " in " << subchain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900731
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900732 if (!ext_ifname.empty()) {
733 // If |ext_ifname| is not null, mark egress traffic with the
734 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900735 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900736 if (ifindex == 0) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900737 LOG(ERROR) << "Failed to retrieve interface index of " << ext_ifname;
Hugo Benichid872d3d2021-03-29 10:20:53 +0900738 return;
Hugo Benichi8c526e92021-03-25 14:59:59 +0900739 }
Hugo Benichid872d3d2021-03-29 10:20:53 +0900740 if (!ModifyFwmarkRoutingTag(subchain, "-A", Fwmark::FromIfIndex(ifindex)))
741 LOG(ERROR) << "Failed to add fwmark routing tag for " << ext_ifname
742 << "<-" << int_ifname << " in " << subchain;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900743 } else {
744 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
745 // PREROUTING to apply any fwmark routing tag saved for the current
746 // connection, and rely on implicit routing to the default logical network
747 // otherwise.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900748 if (!ModifyConnmarkRestore(IpFamily::Dual, subchain, "-A", "" /*iif*/,
Hugo Benichi1af52392020-11-27 18:09:32 +0900749 kFwmarkRoutingMask))
Hugo Benichid872d3d2021-03-29 10:20:53 +0900750 LOG(ERROR) << "Failed to add CONNMARK restore rule in " << subchain;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900751
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900752 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900753 // default network is eligible to be routed through a VPN if |route_on_vpn|
754 // is true.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900755 if (route_on_vpn && !ModifyFwmarkVpnJumpRule(subchain, "-A", {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900756 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900757 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900758}
759
760void Datapath::StopRoutingDevice(const std::string& ext_ifname,
761 const std::string& int_ifname,
762 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900763 TrafficSource source,
764 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900765 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900766 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichi954bae62021-04-09 09:12:30 +0900767 ModifyIpForwarding(IpFamily::IPv4, "-D", ext_ifname, int_ifname);
768 ModifyIpForwarding(IpFamily::IPv4, "-D", int_ifname, ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900769
770 std::string subchain = "PREROUTING_" + int_ifname;
771 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "PREROUTING", subchain,
772 int_ifname, "" /*oif*/);
773 FlushChain(IpFamily::Dual, "mangle", subchain);
774 RemoveChain(IpFamily::Dual, "mangle", subchain);
Hugo Benichi8d622b52020-08-13 15:24:12 +0900775}
776
Garrick Evansf0ab7132019-06-18 14:50:42 +0900777bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
778 const std::string& ipv4_addr) {
779 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900780 if (process_runner_->iptables(
781 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
782 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900783 return false;
784
785 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900786 if (process_runner_->iptables(
787 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
788 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900789 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
790 return false;
791 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900792 if (process_runner_->iptables(
793 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
794 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900795 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
796 return false;
797 }
798
799 return true;
800}
801
802void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
803 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900804 process_runner_->iptables(
805 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
806 "--to-destination", ipv4_addr, "-w"});
807 process_runner_->iptables(
808 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
809 "--to-destination", ipv4_addr, "-w"});
810 process_runner_->iptables(
811 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
812 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900813}
814
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900815bool Datapath::AddRedirectDnsRule(const std::string& ifname,
816 const std::string dns_ipv4_addr) {
817 bool success = true;
818 success &= RemoveRedirectDnsRule(ifname);
819 // Use Insert operation to ensure that the new DNS address is used first.
820 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
821 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
822 physical_dns_addresses_[ifname] = dns_ipv4_addr;
823 return success;
824}
825
826bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
827 const auto it = physical_dns_addresses_.find(ifname);
828 if (it == physical_dns_addresses_.end())
829 return true;
830
831 bool success = true;
832 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
833 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
834 physical_dns_addresses_.erase(it);
835 return success;
836}
837
838bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
839 const std::string& protocol,
840 const std::string& ifname,
841 const std::string& dns_ipv4_addr) {
842 std::vector<std::string> args = {op,
843 kRedirectDnsChain,
844 "-p",
845 protocol,
846 "--dport",
847 "53",
848 "-o",
849 ifname,
850 "-j",
851 "DNAT",
852 "--to-destination",
853 dns_ipv4_addr,
854 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900855 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900856}
857
858bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
859 std::vector<std::string> args = {
860 op,
861 "OUTPUT",
862 "-m",
863 "mark",
864 "!",
865 "--mark",
866 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
867 "-j",
868 kRedirectDnsChain,
869 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900870 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900871}
872
Garrick Evans664a82f2019-12-17 12:18:05 +0900873bool Datapath::MaskInterfaceFlags(const std::string& ifname,
874 uint16_t on,
875 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900876 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
877 if (!sock.is_valid()) {
878 PLOG(ERROR) << "Failed to create control socket";
879 return false;
880 }
881 ifreq ifr;
882 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
883 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
884 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
885 return false;
886 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900887 ifr.ifr_flags |= on;
888 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900889 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900890 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
891 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900892 return false;
893 }
894 return true;
895}
896
Garrick Evans260ff302019-07-25 11:22:50 +0900897bool Datapath::AddIPv6HostRoute(const std::string& ifname,
898 const std::string& ipv6_addr,
899 int ipv6_prefix_len) {
900 std::string ipv6_addr_cidr =
901 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
902
Garrick Evans8e8e3472020-01-23 14:03:50 +0900903 return process_runner_->ip6("route", "replace",
904 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900905}
906
907void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
908 const std::string& ipv6_addr,
909 int ipv6_prefix_len) {
910 std::string ipv6_addr_cidr =
911 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
912
Garrick Evans8e8e3472020-01-23 14:03:50 +0900913 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900914}
915
Taoyu Lia0727dc2020-09-24 19:54:59 +0900916bool Datapath::AddIPv6Address(const std::string& ifname,
917 const std::string& ipv6_addr) {
918 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900919}
920
Taoyu Lia0727dc2020-09-24 19:54:59 +0900921void Datapath::RemoveIPv6Address(const std::string& ifname,
922 const std::string& ipv6_addr) {
923 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900924}
925
Hugo Benichi76be34a2020-08-26 22:35:54 +0900926void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900927 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +0900928 if (ifindex == 0) {
929 // Can happen if the interface has already been removed (b/183679000).
930 LOG(ERROR) << "Failed to set up connection pinning on " << ext_ifname;
931 return;
932 }
933
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900934 std::string subchain = "POSTROUTING_" + ext_ifname;
935 // This can fail if patchpanel did not stopped correctly or failed to cleanup
936 // the chain when |ext_ifname| was previously deleted.
937 if (!AddChain(IpFamily::Dual, "mangle", subchain))
938 LOG(ERROR) << "Failed to create mangle chain " << subchain;
939 // Make sure the chain is empty if patchpanel did not cleaned correctly that
940 // chain before.
941 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
942 LOG(ERROR) << "Could not flush " << subchain;
943 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "POSTROUTING", subchain,
944 "" /*iif*/, ext_ifname))
945 LOG(ERROR) << "Could not add jump rule from mangle POSTROUTING to "
946 << subchain;
947
Hugo Benichi8c526e92021-03-25 14:59:59 +0900948 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
949 LOG(INFO) << "Start connection pinning on " << ext_ifname
950 << " fwmark=" << routing_mark.ToString();
Hugo Benichi1af52392020-11-27 18:09:32 +0900951 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900952 if (!ModifyConnmarkSet(IpFamily::Dual, subchain, "-A", routing_mark,
953 kFwmarkRoutingMask))
Hugo Benichi76be34a2020-08-26 22:35:54 +0900954 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900955 // Save in CONNMARK the source tag for egress traffic of this connection.
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900956 if (!ModifyConnmarkSave(IpFamily::Dual, subchain, "-A",
Hugo Benichi1af52392020-11-27 18:09:32 +0900957 kFwmarkAllSourcesMask))
958 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
959 "source tag on "
960 << ext_ifname;
961 // Restore from CONNMARK the source tag for ingress traffic of this connection
962 // (returned traffic).
963 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
964 kFwmarkAllSourcesMask))
965 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
966 "traffic received on "
967 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900968}
969
970void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900971 std::string subchain = "POSTROUTING_" + ext_ifname;
972 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "POSTROUTING", subchain,
973 "" /*iif*/, ext_ifname);
974 FlushChain(IpFamily::Dual, "mangle", subchain);
975 RemoveChain(IpFamily::Dual, "mangle", subchain);
976 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
977 kFwmarkAllSourcesMask))
978 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
979 "traffic received on "
980 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900981}
982
Hugo Benichi2a940542020-10-26 18:50:49 +0900983void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900984 int ifindex = FindIfIndex(vpn_ifname);
985 if (ifindex == 0) {
986 // Can happen if the interface has already been removed (b/183679000).
987 LOG(ERROR) << "Failed to start VPN routing on " << vpn_ifname;
988 return;
989 }
990
991 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
992 LOG(INFO) << "Start VPN routing on " << vpn_ifname
993 << " fwmark=" << routing_mark.ToString();
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900994 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-A", "POSTROUTING", "MASQUERADE",
995 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +0900996 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900997 StartConnectionPinning(vpn_ifname);
Hugo Benichi3540c7f2021-03-29 13:14:42 +0900998
999 // Any traffic that already has a routing tag applied is accepted.
1000 if (!ModifyIptables(
1001 IpFamily::Dual, "mangle",
1002 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
1003 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
1004 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
1005 "connections";
1006 // Otherwise, any new traffic from a new connection gets marked with the
1007 // VPN routing tag.
Hugo Benichid872d3d2021-03-29 10:20:53 +09001008 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", routing_mark))
Hugo Benichi2a940542020-10-26 18:50:49 +09001009 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichi3540c7f2021-03-29 13:14:42 +09001010
1011 // When the VPN client runs on the host, also route arcbr0 to that VPN so
1012 // that ARC can access the VPN network through arc0.
Hugo Benichibfc49112020-12-14 12:54:44 +09001013 if (vpn_ifname != kArcBridge)
1014 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
1015 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001016 if (!ModifyRedirectDnsJumpRule("-A"))
1017 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichibb38bdd2021-05-14 10:36:11 +09001018
1019 // All traffic with the VPN routing tag are explicitly accepted in the filter
1020 // table. This prevents the VPN lockdown chain to reject that traffic when VPN
1021 // lockdown is enabled.
1022 if (!ModifyIptables(
1023 IpFamily::Dual, "filter",
1024 {"-A", kVpnAcceptChain, "-m", "mark", "--mark",
1025 routing_mark.ToString() + "/" + kFwmarkRoutingMask.ToString(), "-j",
1026 "ACCEPT", "-w"}))
1027 LOG(ERROR) << "Failed to set filter rule for accepting VPN marked traffic";
Hugo Benichi2a940542020-10-26 18:50:49 +09001028}
1029
1030void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi3540c7f2021-03-29 13:14:42 +09001031 LOG(INFO) << "Stop VPN routing on " << vpn_ifname;
Hugo Benichibb38bdd2021-05-14 10:36:11 +09001032 if (!FlushChain(IpFamily::Dual, "filter", kVpnAcceptChain))
1033 LOG(ERROR) << "Could not flush " << kVpnAcceptChain;
Hugo Benichibfc49112020-12-14 12:54:44 +09001034 if (vpn_ifname != kArcBridge)
1035 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
1036 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi3540c7f2021-03-29 13:14:42 +09001037 if (!FlushChain(IpFamily::Dual, "mangle", kApplyVpnMarkChain))
1038 LOG(ERROR) << "Could not flush " << kApplyVpnMarkChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001039 StopConnectionPinning(vpn_ifname);
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001040 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-D", "POSTROUTING", "MASQUERADE",
1041 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +09001042 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001043 if (!ModifyRedirectDnsJumpRule("-D"))
1044 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001045}
1046
Hugo Benichibb38bdd2021-05-14 10:36:11 +09001047void Datapath::SetVpnLockdown(bool enable_vpn_lockdown) {
1048 if (enable_vpn_lockdown) {
1049 if (!ModifyIptables(
1050 IpFamily::Dual, "filter",
1051 {"-A", kVpnLockdownChain, "-m", "mark", "--mark",
1052 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
1053 "-j", "REJECT", "-w"}))
1054 LOG(ERROR) << "Failed to start VPN lockdown mode";
1055 } else {
1056 if (!FlushChain(IpFamily::Dual, "filter", kVpnLockdownChain))
1057 LOG(ERROR) << "Failed to stop VPN lockdown mode";
1058 }
1059}
1060
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001061bool Datapath::ModifyConnmarkSet(IpFamily family,
1062 const std::string& chain,
1063 const std::string& op,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001064 Fwmark mark,
1065 Fwmark mask) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +09001066 return ModifyIptables(family, "mangle",
1067 {op, chain, "-j", "CONNMARK", "--set-mark",
1068 mark.ToString() + "/" + mask.ToString(), "-w"});
Hugo Benichi76be34a2020-08-26 22:35:54 +09001069}
1070
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001071bool Datapath::ModifyConnmarkRestore(IpFamily family,
1072 const std::string& chain,
1073 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001074 const std::string& iif,
1075 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001076 std::vector<std::string> args = {op, chain};
1077 if (!iif.empty()) {
1078 args.push_back("-i");
1079 args.push_back(iif);
1080 }
1081 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001082 mask.ToString(), "-w"});
1083 return ModifyIptables(family, "mangle", args);
1084}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001085
Hugo Benichi1af52392020-11-27 18:09:32 +09001086bool Datapath::ModifyConnmarkSave(IpFamily family,
1087 const std::string& chain,
1088 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001089 Fwmark mask) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +09001090 std::vector<std::string> args = {
1091 op, chain, "-j", "CONNMARK", "--save-mark",
1092 "--mask", mask.ToString(), "-w"};
Hugo Benichi58f264a2020-10-16 18:16:05 +09001093 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001094}
1095
Hugo Benichi2a940542020-10-26 18:50:49 +09001096bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1097 const std::string& op,
Hugo Benichid872d3d2021-03-29 10:20:53 +09001098 Fwmark routing_mark) {
1099 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*int_ifname*/,
1100 "" /*uid_name*/, 0 /*classid*/, routing_mark,
1101 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001102}
1103
Hugo Benichid872d3d2021-03-29 10:20:53 +09001104bool Datapath::ModifyFwmarkSourceTag(const std::string& chain,
1105 const std::string& op,
Hugo Benichi9be19b12020-08-14 15:33:40 +09001106 TrafficSource source) {
Hugo Benichid872d3d2021-03-29 10:20:53 +09001107 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*iif*/, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001108 0 /*classid*/, Fwmark::FromSource(source),
1109 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001110}
1111
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001112bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1113 TrafficSource source) {
1114 std::vector<std::string> args = {"-A",
1115 kApplyLocalSourceMarkChain,
1116 "-m",
1117 "mark",
1118 "--mark",
1119 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1120 "-j",
1121 "MARK",
1122 "--set-mark",
1123 Fwmark::FromSource(source).ToString() + "/" +
1124 kFwmarkAllSourcesMask.ToString(),
1125 "-w"};
1126 return ModifyIptables(IpFamily::Dual, "mangle", args);
1127}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001128
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001129bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1130 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001131 if (std::string(source.uid_name).empty() && source.classid == 0)
1132 return false;
1133
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001134 Fwmark mark = Fwmark::FromSource(source.source_type);
1135 if (source.is_on_vpn)
1136 mark = mark | kFwmarkRouteOnVpn;
1137
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001138 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1139 "" /*iif*/, source.uid_name, source.classid, mark,
1140 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001141}
1142
1143bool Datapath::ModifyFwmark(IpFamily family,
1144 const std::string& chain,
1145 const std::string& op,
1146 const std::string& iif,
1147 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001148 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001149 Fwmark mark,
1150 Fwmark mask,
1151 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001152 std::vector<std::string> args = {op, chain};
1153 if (!iif.empty()) {
1154 args.push_back("-i");
1155 args.push_back(iif);
1156 }
1157 if (!uid_name.empty()) {
1158 args.push_back("-m");
1159 args.push_back("owner");
1160 args.push_back("--uid-owner");
1161 args.push_back(uid_name);
1162 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001163 if (classid != 0) {
1164 args.push_back("-m");
1165 args.push_back("cgroup");
1166 args.push_back("--cgroup");
1167 args.push_back(base::StringPrintf("0x%08x", classid));
1168 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001169 args.push_back("-j");
1170 args.push_back("MARK");
1171 args.push_back("--set-mark");
1172 args.push_back(mark.ToString() + "/" + mask.ToString());
1173 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001174
Hugo Benichi58f264a2020-10-16 18:16:05 +09001175 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001176}
1177
Hugo Benichid82d8832020-08-14 10:05:03 +09001178bool Datapath::ModifyIpForwarding(IpFamily family,
1179 const std::string& op,
1180 const std::string& iif,
1181 const std::string& oif,
1182 bool log_failures) {
1183 if (iif.empty() && oif.empty()) {
1184 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1185 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001186 return false;
1187 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001188 return ModifyJumpRule(family, "filter", op, "FORWARD", "ACCEPT", iif, oif,
1189 log_failures);
1190}
Garrick Evans260ff302019-07-25 11:22:50 +09001191
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001192bool Datapath::ModifyJumpRule(IpFamily family,
1193 const std::string& table,
1194 const std::string& op,
1195 const std::string& chain,
1196 const std::string& target,
1197 const std::string& iif,
1198 const std::string& oif,
1199 bool log_failures) {
1200 std::vector<std::string> args = {op, chain};
Hugo Benichid82d8832020-08-14 10:05:03 +09001201 if (!iif.empty()) {
1202 args.push_back("-i");
1203 args.push_back(iif);
1204 }
1205 if (!oif.empty()) {
1206 args.push_back("-o");
1207 args.push_back(oif);
1208 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001209 args.insert(args.end(), {"-j", target, "-w"});
1210 return ModifyIptables(family, table, args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001211}
1212
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001213bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1214 const std::string& op,
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001215 Fwmark mark,
1216 Fwmark mask) {
1217 std::vector<std::string> args = {op, chain};
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001218 if (mark.Value() != 0 && mask.Value() != 0) {
1219 args.push_back("-m");
1220 args.push_back("mark");
1221 args.push_back("--mark");
1222 args.push_back(mark.ToString() + "/" + mask.ToString());
1223 }
1224 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1225 return ModifyIptables(IpFamily::Dual, "mangle", args);
1226}
1227
Hugo Benichif0f55562021-04-02 15:25:02 +09001228bool Datapath::AddChain(IpFamily family,
1229 const std::string& table,
1230 const std::string& name) {
1231 DCHECK(name.size() <= kIptablesMaxChainLength);
1232 return ModifyChain(family, table, "-N", name);
1233}
1234
1235bool Datapath::RemoveChain(IpFamily family,
1236 const std::string& table,
1237 const std::string& name) {
1238 return ModifyChain(family, table, "-X", name);
1239}
1240
1241bool Datapath::FlushChain(IpFamily family,
1242 const std::string& table,
1243 const std::string& name) {
1244 return ModifyChain(family, table, "-F", name);
1245}
1246
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001247bool Datapath::ModifyChain(IpFamily family,
1248 const std::string& table,
1249 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001250 const std::string& chain,
1251 bool log_failures) {
1252 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001253}
1254
1255bool Datapath::ModifyIptables(IpFamily family,
1256 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001257 const std::vector<std::string>& argv,
1258 bool log_failures) {
1259 switch (family) {
1260 case IPv4:
1261 case IPv6:
1262 case Dual:
1263 break;
1264 default:
1265 LOG(ERROR) << "Could not execute iptables command " << table
1266 << base::JoinString(argv, " ") << ": incorrect IP family "
1267 << family;
1268 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001269 }
1270
1271 bool success = true;
1272 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001273 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001274 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001275 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001276 return success;
1277}
1278
Hugo Benichid82d8832020-08-14 10:05:03 +09001279bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1280 const std::string& ifname2) {
1281 // Only start Ipv6 forwarding if -C returns false and it had not been
1282 // started yet.
1283 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1284 false /*log_failures*/) &&
Hugo Benichi954bae62021-04-09 09:12:30 +09001285 !ModifyIpForwarding(IpFamily::IPv6, "-A", ifname1, ifname2)) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001286 return false;
1287 }
1288
1289 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1290 false /*log_failures*/) &&
Hugo Benichi954bae62021-04-09 09:12:30 +09001291 !ModifyIpForwarding(IpFamily::IPv6, "-A", ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001292 RemoveIPv6Forwarding(ifname1, ifname2);
1293 return false;
1294 }
1295
1296 return true;
1297}
1298
1299void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1300 const std::string& ifname2) {
Hugo Benichi954bae62021-04-09 09:12:30 +09001301 ModifyIpForwarding(IpFamily::IPv6, "-D", ifname1, ifname2);
1302 ModifyIpForwarding(IpFamily::IPv6, "-D", ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001303}
1304
Garrick Evans3d97a392020-02-21 15:24:37 +09001305bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1306 uint32_t addr,
1307 uint32_t netmask) {
1308 struct rtentry route;
1309 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001310 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1311 SetSockaddrIn(&route.rt_dst, addr & netmask);
1312 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001313 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001314 return ModifyRtentry(SIOCADDRT, &route);
1315}
Garrick Evans3d97a392020-02-21 15:24:37 +09001316
Hugo Benichie8758b52020-04-03 14:49:01 +09001317bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1318 uint32_t addr,
1319 uint32_t netmask) {
1320 struct rtentry route;
1321 memset(&route, 0, sizeof(route));
1322 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1323 SetSockaddrIn(&route.rt_dst, addr & netmask);
1324 SetSockaddrIn(&route.rt_genmask, netmask);
1325 route.rt_flags = RTF_UP | RTF_GATEWAY;
1326 return ModifyRtentry(SIOCDELRT, &route);
1327}
1328
1329bool Datapath::AddIPv4Route(const std::string& ifname,
1330 uint32_t addr,
1331 uint32_t netmask) {
1332 struct rtentry route;
1333 memset(&route, 0, sizeof(route));
1334 SetSockaddrIn(&route.rt_dst, addr & netmask);
1335 SetSockaddrIn(&route.rt_genmask, netmask);
1336 char rt_dev[IFNAMSIZ];
1337 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1338 rt_dev[IFNAMSIZ - 1] = '\0';
1339 route.rt_dev = rt_dev;
1340 route.rt_flags = RTF_UP | RTF_GATEWAY;
1341 return ModifyRtentry(SIOCADDRT, &route);
1342}
1343
1344bool Datapath::DeleteIPv4Route(const std::string& ifname,
1345 uint32_t addr,
1346 uint32_t netmask) {
1347 struct rtentry route;
1348 memset(&route, 0, sizeof(route));
1349 SetSockaddrIn(&route.rt_dst, addr & netmask);
1350 SetSockaddrIn(&route.rt_genmask, netmask);
1351 char rt_dev[IFNAMSIZ];
1352 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1353 rt_dev[IFNAMSIZ - 1] = '\0';
1354 route.rt_dev = rt_dev;
1355 route.rt_flags = RTF_UP | RTF_GATEWAY;
1356 return ModifyRtentry(SIOCDELRT, &route);
1357}
1358
Taoyu Lia0727dc2020-09-24 19:54:59 +09001359bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001360 DCHECK(route);
1361 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001362 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001363 return false;
1364 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001365 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1366 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001367 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001368 return false;
1369 }
1370 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1371 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001372 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001373 return false;
1374 }
1375 return true;
1376}
1377
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001378bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1379 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1380 kArcAddr, kAdbServerPort, ifname,
1381 kLocalhostAddr, kAdbProxyTcpListenPort);
1382}
1383
1384void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1385 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1386 kArcAddr, kAdbServerPort, ifname,
1387 kLocalhostAddr, kAdbProxyTcpListenPort);
1388}
1389
1390bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1391 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1392 kAdbProxyTcpListenPort, ifname);
1393}
1394
1395void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1396 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1397 kAdbProxyTcpListenPort, ifname);
1398}
1399
Damien Dejean61eccae2021-05-21 07:11:53 +00001400bool Datapath::SetConntrackHelpers(const bool enable_helpers) {
1401 if (process_runner_->sysctl_w("net.netfilter.nf_conntrack_helper",
1402 enable_helpers ? "1" : "0") != 0) {
1403 LOG(ERROR) << "Failed to " << (enable_helpers ? "enable" : "disable")
1404 << " netfilter conntrack helpers";
1405 return false;
1406 }
1407 return true;
1408}
1409
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001410void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1411 if_nametoindex_[ifname] = ifindex;
1412}
1413
1414int Datapath::FindIfIndex(const std::string& ifname) {
1415 uint32_t ifindex = if_nametoindex(ifname.c_str());
1416 if (ifindex > 0) {
1417 if_nametoindex_[ifname] = ifindex;
1418 return ifindex;
1419 }
1420
1421 const auto it = if_nametoindex_.find(ifname);
1422 if (it != if_nametoindex_.end())
1423 return it->second;
1424
1425 return 0;
1426}
1427
Hugo Benichifcf81022020-12-04 11:01:37 +09001428std::ostream& operator<<(std::ostream& stream,
1429 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001430 stream << "{ pid: " << nsinfo.pid
1431 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001432 if (!nsinfo.outbound_ifname.empty()) {
1433 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1434 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001435 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1436 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001437 << ", peer_ifname: " << nsinfo.peer_ifname
1438 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1439 return stream;
1440}
1441
Garrick Evans3388a032020-03-24 11:25:55 +09001442} // namespace patchpanel