blob: 7335a259a2d865641a1bfff4fc425e7572d684f4 [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;
343 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
344}
345
346bool Datapath::NetnsDeleteName(const std::string& netns_name) {
347 return process_runner_->ip_netns_delete(netns_name) == 0;
348}
349
Garrick Evans8a949dc2019-07-18 16:17:53 +0900350bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900351 uint32_t ipv4_addr,
352 uint32_t ipv4_prefix_len) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900353 if (!Ioctl(ioctl_, SIOCBRADDBR, ifname.c_str())) {
354 LOG(ERROR) << "Failed to create bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900355 return false;
356 }
357
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900358 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900359 if (process_runner_->ip(
360 "addr", "add",
361 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
362 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
363 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900364 RemoveBridge(ifname);
365 return false;
366 }
367
368 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900369 RemoveBridge(ifname);
370 return false;
371 }
372
Garrick Evans8a949dc2019-07-18 16:17:53 +0900373 return true;
374}
375
376void Datapath::RemoveBridge(const std::string& ifname) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900377 process_runner_->ip("link", "set", {ifname, "down"});
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900378 if (!Ioctl(ioctl_, SIOCBRDELBR, ifname.c_str()))
379 LOG(ERROR) << "Failed to destroy bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900380}
381
Garrick Evans621ed262019-11-13 12:28:43 +0900382bool Datapath::AddToBridge(const std::string& br_ifname,
383 const std::string& ifname) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900384 struct ifreq ifr;
385 memset(&ifr, 0, sizeof(ifr));
386 strncpy(ifr.ifr_name, br_ifname.c_str(), sizeof(ifr.ifr_name));
387 ifr.ifr_ifindex = FindIfIndex(ifname);
388
389 if (!Ioctl(ioctl_, SIOCBRADDIF, reinterpret_cast<const char*>(&ifr))) {
390 LOG(ERROR) << "Failed to add " << ifname << " to bridge " << br_ifname;
391 return false;
392 }
393
394 return true;
Garrick Evans621ed262019-11-13 12:28:43 +0900395}
396
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900397std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900398 const MacAddress* mac_addr,
399 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900400 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900401 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
402 if (!dev.is_valid()) {
403 PLOG(ERROR) << "Failed to open " << kTunDev;
404 return "";
405 }
406
407 struct ifreq ifr;
408 memset(&ifr, 0, sizeof(ifr));
409 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
410 sizeof(ifr.ifr_name));
411 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
412
413 // If a template was given as the name, ifr_name will be updated with the
414 // actual interface name.
415 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900416 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900417 return "";
418 }
419 const char* ifname = ifr.ifr_name;
420
421 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900422 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900423 return "";
424 }
425
Garrick Evans4f9f5572019-11-26 10:25:16 +0900426 if (!user.empty()) {
427 uid_t uid = -1;
428 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
429 PLOG(ERROR) << "Unable to look up UID for " << user;
430 RemoveTAP(ifname);
431 return "";
432 }
433 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
434 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
435 << ifname;
436 RemoveTAP(ifname);
437 return "";
438 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900439 }
440
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900441 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900442 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
443 if (!sock.is_valid()) {
444 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900445 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900446 RemoveTAP(ifname);
447 return "";
448 }
449
Garrick Evans621ed262019-11-13 12:28:43 +0900450 if (ipv4_addr) {
451 struct sockaddr_in* addr =
452 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
453 addr->sin_family = AF_INET;
454 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
455 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
456 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
457 << " {" << ipv4_addr->ToCidrString() << "}";
458 RemoveTAP(ifname);
459 return "";
460 }
461
462 struct sockaddr_in* netmask =
463 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
464 netmask->sin_family = AF_INET;
465 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
466 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
467 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
468 << " {" << ipv4_addr->ToCidrString() << "}";
469 RemoveTAP(ifname);
470 return "";
471 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900472 }
473
Garrick Evans621ed262019-11-13 12:28:43 +0900474 if (mac_addr) {
475 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
476 hwaddr->sa_family = ARPHRD_ETHER;
477 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
478 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
479 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
480 << " {" << MacAddressToString(*mac_addr) << "}";
481 RemoveTAP(ifname);
482 return "";
483 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900484 }
485
486 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900487 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900488 RemoveTAP(ifname);
489 return "";
490 }
491
492 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
493 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900494 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900495 RemoveTAP(ifname);
496 return "";
497 }
498
499 return ifname;
500}
501
502void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900503 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900504}
505
Hugo Benichi33860d72020-07-09 16:34:01 +0900506bool Datapath::ConnectVethPair(pid_t netns_pid,
507 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900508 const std::string& veth_ifname,
509 const std::string& peer_ifname,
510 const MacAddress& remote_mac_addr,
511 uint32_t remote_ipv4_addr,
512 uint32_t remote_ipv4_prefix_len,
513 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900514 // Set up the virtual pair across the current namespace and |netns_name|.
515 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
516 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
517 << peer_ifname;
518 return false;
519 }
520
521 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900522 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900523 ScopedNS ns(netns_pid, ScopedNS::Type::Network);
Hugo Benichi33860d72020-07-09 16:34:01 +0900524 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900525 LOG(ERROR)
526 << "Cannot create virtual link -- invalid container namespace?";
527 return false;
528 }
529
Hugo Benichi76675592020-04-08 14:29:57 +0900530 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
531 remote_ipv4_prefix_len, true /* link up */,
532 remote_multicast_flag)) {
533 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
534 RemoveInterface(peer_ifname);
535 return false;
536 }
537 }
538
Hugo Benichi76675592020-04-08 14:29:57 +0900539 if (!ToggleInterface(veth_ifname, true /*up*/)) {
540 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
541 RemoveInterface(veth_ifname);
542 return false;
543 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900544
Hugo Benichi76675592020-04-08 14:29:57 +0900545 return true;
546}
547
Hugo Benichi33860d72020-07-09 16:34:01 +0900548bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
549 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900550 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900551 return process_runner_->ip("link", "add",
552 {veth_ifname, "type", "veth", "peer", "name",
553 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900554}
Garrick Evans54861622019-07-19 09:05:09 +0900555
Garrick Evans2470caa2020-03-04 14:15:41 +0900556bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
557 const std::string link = up ? "up" : "down";
558 return process_runner_->ip("link", "set", {ifname, link}) == 0;
559}
Garrick Evans54861622019-07-19 09:05:09 +0900560
Garrick Evans2470caa2020-03-04 14:15:41 +0900561bool Datapath::ConfigureInterface(const std::string& ifname,
562 const MacAddress& mac_addr,
563 uint32_t ipv4_addr,
564 uint32_t ipv4_prefix_len,
565 bool up,
566 bool enable_multicast) {
567 const std::string link = up ? "up" : "down";
568 const std::string multicast = enable_multicast ? "on" : "off";
569 return (process_runner_->ip(
570 "addr", "add",
571 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
572 IPv4AddressToString(
573 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
574 "dev", ifname}) == 0) &&
575 (process_runner_->ip("link", "set",
576 {
577 "dev",
578 ifname,
579 link,
580 "addr",
581 MacAddressToString(mac_addr),
582 "multicast",
583 multicast,
584 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900585}
586
587void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900588 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900589}
590
Hugo Benichi321f23b2020-09-25 15:42:05 +0900591bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
592 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900593 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900594 "filter", {"-I", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
595 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900596}
597
Hugo Benichifcf81022020-12-04 11:01:37 +0900598bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900599 // Veth interface configuration and client routing configuration:
600 // - attach a name to the client namespace.
601 // - create veth pair across the current namespace and the client namespace.
602 // - configure IPv4 address on remote veth inside client namespace.
603 // - configure IPv4 address on local veth inside host namespace.
604 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900605 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
606 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
607 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900608 return false;
609 }
610
Hugo Benichifcf81022020-12-04 11:01:37 +0900611 if (!ConnectVethPair(
612 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
613 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
614 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900615 LOG(ERROR) << "Failed to create veth pair for"
616 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900617 << nsinfo.pid;
618 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900619 return false;
620 }
621
Hugo Benichifcf81022020-12-04 11:01:37 +0900622 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
623 nsinfo.peer_subnet->AddressAtOffset(0),
624 nsinfo.peer_subnet->PrefixLength(),
625 true /* link up */, false /* enable_multicast */)) {
626 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
627 RemoveInterface(nsinfo.host_ifname);
628 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900629 return false;
630 }
631
632 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900633 ScopedNS ns(nsinfo.pid, ScopedNS::Type::Network);
Hugo Benichifcf81022020-12-04 11:01:37 +0900634 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
635 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
636 RemoveInterface(nsinfo.host_ifname);
637 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900638 return false;
639 }
640
Hugo Benichifcf81022020-12-04 11:01:37 +0900641 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
642 INADDR_ANY)) {
643 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
644 << " inside namespace pid " << nsinfo.pid;
645 RemoveInterface(nsinfo.host_ifname);
646 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900647 return false;
648 }
649 }
650
651 // Host namespace routing configuration
652 // - ingress: add route to client subnet via |host_ifname|.
653 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
654 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
655 // Note that by default unsolicited ingress traffic is not forwarded to the
656 // client namespace unless the client specifically set port forwarding
657 // through permission_broker DBus APIs.
658 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
659 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900660 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
661 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
662 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900663 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900664 RemoveInterface(nsinfo.host_ifname);
665 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900666 return false;
667 }
668
Hugo Benichi93306e52020-12-04 16:08:00 +0900669 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
670 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
671 nsinfo.route_on_vpn);
Hugo Benichi7c342672020-09-08 09:18:14 +0900672 return true;
673}
674
Hugo Benichifcf81022020-12-04 11:01:37 +0900675void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900676 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
677 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
678 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900679 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900680 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
681 nsinfo.peer_subnet->BaseAddress(),
682 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
683 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900684}
685
Hugo Benichi8d622b52020-08-13 15:24:12 +0900686void Datapath::StartRoutingDevice(const std::string& ext_ifname,
687 const std::string& int_ifname,
688 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900689 TrafficSource source,
690 bool route_on_vpn) {
691 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900692 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900693 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
694 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
695 << "->" << int_ifname;
696
Hugo Benichi954bae62021-04-09 09:12:30 +0900697 if (!ModifyIpForwarding(IpFamily::IPv4, "-A", ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900698 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
699 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900700
Hugo Benichi954bae62021-04-09 09:12:30 +0900701 if (!ModifyIpForwarding(IpFamily::IPv4, "-A", int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900702 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
703 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900704
Hugo Benichid872d3d2021-03-29 10:20:53 +0900705 std::string subchain = "PREROUTING_" + int_ifname;
706 // This can fail if patchpanel did not stopped correctly or failed to cleanup
707 // the chain when |int_ifname| was previously deleted.
708 if (!AddChain(IpFamily::Dual, "mangle", subchain))
709 LOG(ERROR) << "Failed to create mangle chain " << subchain;
710 // Make sure the chain is empty if patchpanel did not cleaned correctly that
711 // chain before.
712 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
713 LOG(ERROR) << "Could not flush " << subchain;
714 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "PREROUTING", subchain,
715 int_ifname, "" /*oif*/))
716 LOG(ERROR) << "Could not add jump rule from mangle PREROUTING to "
717 << subchain;
Hugo Benichi7a066242021-04-07 23:47:32 +0900718 // IPv4 traffic from all downstream devices should be tagged to go through
719 // SNAT.
720 if (!ModifyFwmark(IpFamily::IPv4, subchain, "-A", "", "", 0,
721 kFwmarkLegacySNAT, kFwmarkLegacySNAT))
722 LOG(ERROR) << "Failed to add fwmark SNAT tagging rule for " << int_ifname;
Hugo Benichid872d3d2021-03-29 10:20:53 +0900723 if (!ModifyFwmarkSourceTag(subchain, "-A", source))
724 LOG(ERROR) << "Failed to add fwmark tagging rule for source " << source
725 << " in " << subchain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900726
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900727 if (!ext_ifname.empty()) {
728 // If |ext_ifname| is not null, mark egress traffic with the
729 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900730 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900731 if (ifindex == 0) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900732 LOG(ERROR) << "Failed to retrieve interface index of " << ext_ifname;
Hugo Benichid872d3d2021-03-29 10:20:53 +0900733 return;
Hugo Benichi8c526e92021-03-25 14:59:59 +0900734 }
Hugo Benichid872d3d2021-03-29 10:20:53 +0900735 if (!ModifyFwmarkRoutingTag(subchain, "-A", Fwmark::FromIfIndex(ifindex)))
736 LOG(ERROR) << "Failed to add fwmark routing tag for " << ext_ifname
737 << "<-" << int_ifname << " in " << subchain;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900738 } else {
739 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
740 // PREROUTING to apply any fwmark routing tag saved for the current
741 // connection, and rely on implicit routing to the default logical network
742 // otherwise.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900743 if (!ModifyConnmarkRestore(IpFamily::Dual, subchain, "-A", "" /*iif*/,
Hugo Benichi1af52392020-11-27 18:09:32 +0900744 kFwmarkRoutingMask))
Hugo Benichid872d3d2021-03-29 10:20:53 +0900745 LOG(ERROR) << "Failed to add CONNMARK restore rule in " << subchain;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900746
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900747 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900748 // default network is eligible to be routed through a VPN if |route_on_vpn|
749 // is true.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900750 if (route_on_vpn && !ModifyFwmarkVpnJumpRule(subchain, "-A", {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900751 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900752 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900753}
754
755void Datapath::StopRoutingDevice(const std::string& ext_ifname,
756 const std::string& int_ifname,
757 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900758 TrafficSource source,
759 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900760 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900761 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichi954bae62021-04-09 09:12:30 +0900762 ModifyIpForwarding(IpFamily::IPv4, "-D", ext_ifname, int_ifname);
763 ModifyIpForwarding(IpFamily::IPv4, "-D", int_ifname, ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900764
765 std::string subchain = "PREROUTING_" + int_ifname;
766 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "PREROUTING", subchain,
767 int_ifname, "" /*oif*/);
768 FlushChain(IpFamily::Dual, "mangle", subchain);
769 RemoveChain(IpFamily::Dual, "mangle", subchain);
Hugo Benichi8d622b52020-08-13 15:24:12 +0900770}
771
Garrick Evansf0ab7132019-06-18 14:50:42 +0900772bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
773 const std::string& ipv4_addr) {
774 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900775 if (process_runner_->iptables(
776 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
777 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900778 return false;
779
780 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900781 if (process_runner_->iptables(
782 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
783 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900784 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
785 return false;
786 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900787 if (process_runner_->iptables(
788 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
789 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900790 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
791 return false;
792 }
793
794 return true;
795}
796
797void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
798 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900799 process_runner_->iptables(
800 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
801 "--to-destination", ipv4_addr, "-w"});
802 process_runner_->iptables(
803 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
804 "--to-destination", ipv4_addr, "-w"});
805 process_runner_->iptables(
806 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
807 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900808}
809
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900810bool Datapath::AddRedirectDnsRule(const std::string& ifname,
811 const std::string dns_ipv4_addr) {
812 bool success = true;
813 success &= RemoveRedirectDnsRule(ifname);
814 // Use Insert operation to ensure that the new DNS address is used first.
815 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
816 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
817 physical_dns_addresses_[ifname] = dns_ipv4_addr;
818 return success;
819}
820
821bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
822 const auto it = physical_dns_addresses_.find(ifname);
823 if (it == physical_dns_addresses_.end())
824 return true;
825
826 bool success = true;
827 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
828 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
829 physical_dns_addresses_.erase(it);
830 return success;
831}
832
833bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
834 const std::string& protocol,
835 const std::string& ifname,
836 const std::string& dns_ipv4_addr) {
837 std::vector<std::string> args = {op,
838 kRedirectDnsChain,
839 "-p",
840 protocol,
841 "--dport",
842 "53",
843 "-o",
844 ifname,
845 "-j",
846 "DNAT",
847 "--to-destination",
848 dns_ipv4_addr,
849 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900850 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900851}
852
853bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
854 std::vector<std::string> args = {
855 op,
856 "OUTPUT",
857 "-m",
858 "mark",
859 "!",
860 "--mark",
861 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
862 "-j",
863 kRedirectDnsChain,
864 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900865 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900866}
867
Garrick Evans664a82f2019-12-17 12:18:05 +0900868bool Datapath::MaskInterfaceFlags(const std::string& ifname,
869 uint16_t on,
870 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900871 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
872 if (!sock.is_valid()) {
873 PLOG(ERROR) << "Failed to create control socket";
874 return false;
875 }
876 ifreq ifr;
877 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
878 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
879 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
880 return false;
881 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900882 ifr.ifr_flags |= on;
883 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900884 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900885 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
886 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900887 return false;
888 }
889 return true;
890}
891
Garrick Evans260ff302019-07-25 11:22:50 +0900892bool Datapath::AddIPv6HostRoute(const std::string& ifname,
893 const std::string& ipv6_addr,
894 int ipv6_prefix_len) {
895 std::string ipv6_addr_cidr =
896 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
897
Garrick Evans8e8e3472020-01-23 14:03:50 +0900898 return process_runner_->ip6("route", "replace",
899 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900900}
901
902void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
903 const std::string& ipv6_addr,
904 int ipv6_prefix_len) {
905 std::string ipv6_addr_cidr =
906 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
907
Garrick Evans8e8e3472020-01-23 14:03:50 +0900908 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900909}
910
Taoyu Lia0727dc2020-09-24 19:54:59 +0900911bool Datapath::AddIPv6Address(const std::string& ifname,
912 const std::string& ipv6_addr) {
913 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900914}
915
Taoyu Lia0727dc2020-09-24 19:54:59 +0900916void Datapath::RemoveIPv6Address(const std::string& ifname,
917 const std::string& ipv6_addr) {
918 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900919}
920
Hugo Benichi76be34a2020-08-26 22:35:54 +0900921void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900922 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +0900923 if (ifindex == 0) {
924 // Can happen if the interface has already been removed (b/183679000).
925 LOG(ERROR) << "Failed to set up connection pinning on " << ext_ifname;
926 return;
927 }
928
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900929 std::string subchain = "POSTROUTING_" + ext_ifname;
930 // This can fail if patchpanel did not stopped correctly or failed to cleanup
931 // the chain when |ext_ifname| was previously deleted.
932 if (!AddChain(IpFamily::Dual, "mangle", subchain))
933 LOG(ERROR) << "Failed to create mangle chain " << subchain;
934 // Make sure the chain is empty if patchpanel did not cleaned correctly that
935 // chain before.
936 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
937 LOG(ERROR) << "Could not flush " << subchain;
938 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "POSTROUTING", subchain,
939 "" /*iif*/, ext_ifname))
940 LOG(ERROR) << "Could not add jump rule from mangle POSTROUTING to "
941 << subchain;
942
Hugo Benichi8c526e92021-03-25 14:59:59 +0900943 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
944 LOG(INFO) << "Start connection pinning on " << ext_ifname
945 << " fwmark=" << routing_mark.ToString();
Hugo Benichi1af52392020-11-27 18:09:32 +0900946 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900947 if (!ModifyConnmarkSet(IpFamily::Dual, subchain, "-A", routing_mark,
948 kFwmarkRoutingMask))
Hugo Benichi76be34a2020-08-26 22:35:54 +0900949 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900950 // Save in CONNMARK the source tag for egress traffic of this connection.
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900951 if (!ModifyConnmarkSave(IpFamily::Dual, subchain, "-A",
Hugo Benichi1af52392020-11-27 18:09:32 +0900952 kFwmarkAllSourcesMask))
953 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
954 "source tag on "
955 << ext_ifname;
956 // Restore from CONNMARK the source tag for ingress traffic of this connection
957 // (returned traffic).
958 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
959 kFwmarkAllSourcesMask))
960 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
961 "traffic received on "
962 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900963}
964
965void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900966 std::string subchain = "POSTROUTING_" + ext_ifname;
967 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "POSTROUTING", subchain,
968 "" /*iif*/, ext_ifname);
969 FlushChain(IpFamily::Dual, "mangle", subchain);
970 RemoveChain(IpFamily::Dual, "mangle", subchain);
971 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
972 kFwmarkAllSourcesMask))
973 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
974 "traffic received on "
975 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900976}
977
Hugo Benichi2a940542020-10-26 18:50:49 +0900978void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900979 int ifindex = FindIfIndex(vpn_ifname);
980 if (ifindex == 0) {
981 // Can happen if the interface has already been removed (b/183679000).
982 LOG(ERROR) << "Failed to start VPN routing on " << vpn_ifname;
983 return;
984 }
985
986 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
987 LOG(INFO) << "Start VPN routing on " << vpn_ifname
988 << " fwmark=" << routing_mark.ToString();
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900989 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-A", "POSTROUTING", "MASQUERADE",
990 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +0900991 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900992 StartConnectionPinning(vpn_ifname);
Hugo Benichi3540c7f2021-03-29 13:14:42 +0900993
994 // Any traffic that already has a routing tag applied is accepted.
995 if (!ModifyIptables(
996 IpFamily::Dual, "mangle",
997 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
998 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
999 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
1000 "connections";
1001 // Otherwise, any new traffic from a new connection gets marked with the
1002 // VPN routing tag.
Hugo Benichid872d3d2021-03-29 10:20:53 +09001003 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", routing_mark))
Hugo Benichi2a940542020-10-26 18:50:49 +09001004 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichi3540c7f2021-03-29 13:14:42 +09001005
1006 // When the VPN client runs on the host, also route arcbr0 to that VPN so
1007 // that ARC can access the VPN network through arc0.
Hugo Benichibfc49112020-12-14 12:54:44 +09001008 if (vpn_ifname != kArcBridge)
1009 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
1010 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001011 if (!ModifyRedirectDnsJumpRule("-A"))
1012 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichibb38bdd2021-05-14 10:36:11 +09001013
1014 // All traffic with the VPN routing tag are explicitly accepted in the filter
1015 // table. This prevents the VPN lockdown chain to reject that traffic when VPN
1016 // lockdown is enabled.
1017 if (!ModifyIptables(
1018 IpFamily::Dual, "filter",
1019 {"-A", kVpnAcceptChain, "-m", "mark", "--mark",
1020 routing_mark.ToString() + "/" + kFwmarkRoutingMask.ToString(), "-j",
1021 "ACCEPT", "-w"}))
1022 LOG(ERROR) << "Failed to set filter rule for accepting VPN marked traffic";
Hugo Benichi2a940542020-10-26 18:50:49 +09001023}
1024
1025void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi3540c7f2021-03-29 13:14:42 +09001026 LOG(INFO) << "Stop VPN routing on " << vpn_ifname;
Hugo Benichibb38bdd2021-05-14 10:36:11 +09001027 if (!FlushChain(IpFamily::Dual, "filter", kVpnAcceptChain))
1028 LOG(ERROR) << "Could not flush " << kVpnAcceptChain;
Hugo Benichibfc49112020-12-14 12:54:44 +09001029 if (vpn_ifname != kArcBridge)
1030 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
1031 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi3540c7f2021-03-29 13:14:42 +09001032 if (!FlushChain(IpFamily::Dual, "mangle", kApplyVpnMarkChain))
1033 LOG(ERROR) << "Could not flush " << kApplyVpnMarkChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001034 StopConnectionPinning(vpn_ifname);
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001035 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-D", "POSTROUTING", "MASQUERADE",
1036 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +09001037 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001038 if (!ModifyRedirectDnsJumpRule("-D"))
1039 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001040}
1041
Hugo Benichibb38bdd2021-05-14 10:36:11 +09001042void Datapath::SetVpnLockdown(bool enable_vpn_lockdown) {
1043 if (enable_vpn_lockdown) {
1044 if (!ModifyIptables(
1045 IpFamily::Dual, "filter",
1046 {"-A", kVpnLockdownChain, "-m", "mark", "--mark",
1047 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
1048 "-j", "REJECT", "-w"}))
1049 LOG(ERROR) << "Failed to start VPN lockdown mode";
1050 } else {
1051 if (!FlushChain(IpFamily::Dual, "filter", kVpnLockdownChain))
1052 LOG(ERROR) << "Failed to stop VPN lockdown mode";
1053 }
1054}
1055
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001056bool Datapath::ModifyConnmarkSet(IpFamily family,
1057 const std::string& chain,
1058 const std::string& op,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001059 Fwmark mark,
1060 Fwmark mask) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +09001061 return ModifyIptables(family, "mangle",
1062 {op, chain, "-j", "CONNMARK", "--set-mark",
1063 mark.ToString() + "/" + mask.ToString(), "-w"});
Hugo Benichi76be34a2020-08-26 22:35:54 +09001064}
1065
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001066bool Datapath::ModifyConnmarkRestore(IpFamily family,
1067 const std::string& chain,
1068 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001069 const std::string& iif,
1070 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001071 std::vector<std::string> args = {op, chain};
1072 if (!iif.empty()) {
1073 args.push_back("-i");
1074 args.push_back(iif);
1075 }
1076 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001077 mask.ToString(), "-w"});
1078 return ModifyIptables(family, "mangle", args);
1079}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001080
Hugo Benichi1af52392020-11-27 18:09:32 +09001081bool Datapath::ModifyConnmarkSave(IpFamily family,
1082 const std::string& chain,
1083 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001084 Fwmark mask) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +09001085 std::vector<std::string> args = {
1086 op, chain, "-j", "CONNMARK", "--save-mark",
1087 "--mask", mask.ToString(), "-w"};
Hugo Benichi58f264a2020-10-16 18:16:05 +09001088 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001089}
1090
Hugo Benichi2a940542020-10-26 18:50:49 +09001091bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1092 const std::string& op,
Hugo Benichid872d3d2021-03-29 10:20:53 +09001093 Fwmark routing_mark) {
1094 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*int_ifname*/,
1095 "" /*uid_name*/, 0 /*classid*/, routing_mark,
1096 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001097}
1098
Hugo Benichid872d3d2021-03-29 10:20:53 +09001099bool Datapath::ModifyFwmarkSourceTag(const std::string& chain,
1100 const std::string& op,
Hugo Benichi9be19b12020-08-14 15:33:40 +09001101 TrafficSource source) {
Hugo Benichid872d3d2021-03-29 10:20:53 +09001102 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*iif*/, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001103 0 /*classid*/, Fwmark::FromSource(source),
1104 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001105}
1106
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001107bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1108 TrafficSource source) {
1109 std::vector<std::string> args = {"-A",
1110 kApplyLocalSourceMarkChain,
1111 "-m",
1112 "mark",
1113 "--mark",
1114 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1115 "-j",
1116 "MARK",
1117 "--set-mark",
1118 Fwmark::FromSource(source).ToString() + "/" +
1119 kFwmarkAllSourcesMask.ToString(),
1120 "-w"};
1121 return ModifyIptables(IpFamily::Dual, "mangle", args);
1122}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001123
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001124bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1125 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001126 if (std::string(source.uid_name).empty() && source.classid == 0)
1127 return false;
1128
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001129 Fwmark mark = Fwmark::FromSource(source.source_type);
1130 if (source.is_on_vpn)
1131 mark = mark | kFwmarkRouteOnVpn;
1132
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001133 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1134 "" /*iif*/, source.uid_name, source.classid, mark,
1135 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001136}
1137
1138bool Datapath::ModifyFwmark(IpFamily family,
1139 const std::string& chain,
1140 const std::string& op,
1141 const std::string& iif,
1142 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001143 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001144 Fwmark mark,
1145 Fwmark mask,
1146 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001147 std::vector<std::string> args = {op, chain};
1148 if (!iif.empty()) {
1149 args.push_back("-i");
1150 args.push_back(iif);
1151 }
1152 if (!uid_name.empty()) {
1153 args.push_back("-m");
1154 args.push_back("owner");
1155 args.push_back("--uid-owner");
1156 args.push_back(uid_name);
1157 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001158 if (classid != 0) {
1159 args.push_back("-m");
1160 args.push_back("cgroup");
1161 args.push_back("--cgroup");
1162 args.push_back(base::StringPrintf("0x%08x", classid));
1163 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001164 args.push_back("-j");
1165 args.push_back("MARK");
1166 args.push_back("--set-mark");
1167 args.push_back(mark.ToString() + "/" + mask.ToString());
1168 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001169
Hugo Benichi58f264a2020-10-16 18:16:05 +09001170 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001171}
1172
Hugo Benichid82d8832020-08-14 10:05:03 +09001173bool Datapath::ModifyIpForwarding(IpFamily family,
1174 const std::string& op,
1175 const std::string& iif,
1176 const std::string& oif,
1177 bool log_failures) {
1178 if (iif.empty() && oif.empty()) {
1179 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1180 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001181 return false;
1182 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001183 return ModifyJumpRule(family, "filter", op, "FORWARD", "ACCEPT", iif, oif,
1184 log_failures);
1185}
Garrick Evans260ff302019-07-25 11:22:50 +09001186
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001187bool Datapath::ModifyJumpRule(IpFamily family,
1188 const std::string& table,
1189 const std::string& op,
1190 const std::string& chain,
1191 const std::string& target,
1192 const std::string& iif,
1193 const std::string& oif,
1194 bool log_failures) {
1195 std::vector<std::string> args = {op, chain};
Hugo Benichid82d8832020-08-14 10:05:03 +09001196 if (!iif.empty()) {
1197 args.push_back("-i");
1198 args.push_back(iif);
1199 }
1200 if (!oif.empty()) {
1201 args.push_back("-o");
1202 args.push_back(oif);
1203 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001204 args.insert(args.end(), {"-j", target, "-w"});
1205 return ModifyIptables(family, table, args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001206}
1207
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001208bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1209 const std::string& op,
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001210 Fwmark mark,
1211 Fwmark mask) {
1212 std::vector<std::string> args = {op, chain};
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001213 if (mark.Value() != 0 && mask.Value() != 0) {
1214 args.push_back("-m");
1215 args.push_back("mark");
1216 args.push_back("--mark");
1217 args.push_back(mark.ToString() + "/" + mask.ToString());
1218 }
1219 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1220 return ModifyIptables(IpFamily::Dual, "mangle", args);
1221}
1222
Hugo Benichif0f55562021-04-02 15:25:02 +09001223bool Datapath::AddChain(IpFamily family,
1224 const std::string& table,
1225 const std::string& name) {
1226 DCHECK(name.size() <= kIptablesMaxChainLength);
1227 return ModifyChain(family, table, "-N", name);
1228}
1229
1230bool Datapath::RemoveChain(IpFamily family,
1231 const std::string& table,
1232 const std::string& name) {
1233 return ModifyChain(family, table, "-X", name);
1234}
1235
1236bool Datapath::FlushChain(IpFamily family,
1237 const std::string& table,
1238 const std::string& name) {
1239 return ModifyChain(family, table, "-F", name);
1240}
1241
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001242bool Datapath::ModifyChain(IpFamily family,
1243 const std::string& table,
1244 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001245 const std::string& chain,
1246 bool log_failures) {
1247 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001248}
1249
1250bool Datapath::ModifyIptables(IpFamily family,
1251 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001252 const std::vector<std::string>& argv,
1253 bool log_failures) {
1254 switch (family) {
1255 case IPv4:
1256 case IPv6:
1257 case Dual:
1258 break;
1259 default:
1260 LOG(ERROR) << "Could not execute iptables command " << table
1261 << base::JoinString(argv, " ") << ": incorrect IP family "
1262 << family;
1263 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001264 }
1265
1266 bool success = true;
1267 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001268 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001269 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001270 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001271 return success;
1272}
1273
Hugo Benichid82d8832020-08-14 10:05:03 +09001274bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1275 const std::string& ifname2) {
1276 // Only start Ipv6 forwarding if -C returns false and it had not been
1277 // started yet.
1278 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1279 false /*log_failures*/) &&
Hugo Benichi954bae62021-04-09 09:12:30 +09001280 !ModifyIpForwarding(IpFamily::IPv6, "-A", ifname1, ifname2)) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001281 return false;
1282 }
1283
1284 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1285 false /*log_failures*/) &&
Hugo Benichi954bae62021-04-09 09:12:30 +09001286 !ModifyIpForwarding(IpFamily::IPv6, "-A", ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001287 RemoveIPv6Forwarding(ifname1, ifname2);
1288 return false;
1289 }
1290
1291 return true;
1292}
1293
1294void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1295 const std::string& ifname2) {
Hugo Benichi954bae62021-04-09 09:12:30 +09001296 ModifyIpForwarding(IpFamily::IPv6, "-D", ifname1, ifname2);
1297 ModifyIpForwarding(IpFamily::IPv6, "-D", ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001298}
1299
Garrick Evans3d97a392020-02-21 15:24:37 +09001300bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1301 uint32_t addr,
1302 uint32_t netmask) {
1303 struct rtentry route;
1304 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001305 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1306 SetSockaddrIn(&route.rt_dst, addr & netmask);
1307 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001308 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001309 return ModifyRtentry(SIOCADDRT, &route);
1310}
Garrick Evans3d97a392020-02-21 15:24:37 +09001311
Hugo Benichie8758b52020-04-03 14:49:01 +09001312bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1313 uint32_t addr,
1314 uint32_t netmask) {
1315 struct rtentry route;
1316 memset(&route, 0, sizeof(route));
1317 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1318 SetSockaddrIn(&route.rt_dst, addr & netmask);
1319 SetSockaddrIn(&route.rt_genmask, netmask);
1320 route.rt_flags = RTF_UP | RTF_GATEWAY;
1321 return ModifyRtentry(SIOCDELRT, &route);
1322}
1323
1324bool Datapath::AddIPv4Route(const std::string& ifname,
1325 uint32_t addr,
1326 uint32_t netmask) {
1327 struct rtentry route;
1328 memset(&route, 0, sizeof(route));
1329 SetSockaddrIn(&route.rt_dst, addr & netmask);
1330 SetSockaddrIn(&route.rt_genmask, netmask);
1331 char rt_dev[IFNAMSIZ];
1332 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1333 rt_dev[IFNAMSIZ - 1] = '\0';
1334 route.rt_dev = rt_dev;
1335 route.rt_flags = RTF_UP | RTF_GATEWAY;
1336 return ModifyRtentry(SIOCADDRT, &route);
1337}
1338
1339bool Datapath::DeleteIPv4Route(const std::string& ifname,
1340 uint32_t addr,
1341 uint32_t netmask) {
1342 struct rtentry route;
1343 memset(&route, 0, sizeof(route));
1344 SetSockaddrIn(&route.rt_dst, addr & netmask);
1345 SetSockaddrIn(&route.rt_genmask, netmask);
1346 char rt_dev[IFNAMSIZ];
1347 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1348 rt_dev[IFNAMSIZ - 1] = '\0';
1349 route.rt_dev = rt_dev;
1350 route.rt_flags = RTF_UP | RTF_GATEWAY;
1351 return ModifyRtentry(SIOCDELRT, &route);
1352}
1353
Taoyu Lia0727dc2020-09-24 19:54:59 +09001354bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001355 DCHECK(route);
1356 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001357 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001358 return false;
1359 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001360 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1361 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001362 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001363 return false;
1364 }
1365 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1366 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001367 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001368 return false;
1369 }
1370 return true;
1371}
1372
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001373bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1374 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1375 kArcAddr, kAdbServerPort, ifname,
1376 kLocalhostAddr, kAdbProxyTcpListenPort);
1377}
1378
1379void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1380 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1381 kArcAddr, kAdbServerPort, ifname,
1382 kLocalhostAddr, kAdbProxyTcpListenPort);
1383}
1384
1385bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1386 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1387 kAdbProxyTcpListenPort, ifname);
1388}
1389
1390void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1391 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1392 kAdbProxyTcpListenPort, ifname);
1393}
1394
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001395void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1396 if_nametoindex_[ifname] = ifindex;
1397}
1398
1399int Datapath::FindIfIndex(const std::string& ifname) {
1400 uint32_t ifindex = if_nametoindex(ifname.c_str());
1401 if (ifindex > 0) {
1402 if_nametoindex_[ifname] = ifindex;
1403 return ifindex;
1404 }
1405
1406 const auto it = if_nametoindex_.find(ifname);
1407 if (it != if_nametoindex_.end())
1408 return it->second;
1409
1410 return 0;
1411}
1412
Hugo Benichifcf81022020-12-04 11:01:37 +09001413std::ostream& operator<<(std::ostream& stream,
1414 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001415 stream << "{ pid: " << nsinfo.pid
1416 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001417 if (!nsinfo.outbound_ifname.empty()) {
1418 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1419 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001420 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1421 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001422 << ", peer_ifname: " << nsinfo.peer_ifname
1423 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1424 return stream;
1425}
1426
Garrick Evans3388a032020-03-24 11:25:55 +09001427} // namespace patchpanel