blob: 04707cb9376a730109719c96c4dc811c4ccb3757 [file] [log] [blame]
Garrick Evansf0ab7132019-06-18 14:50:42 +09001// Copyright 2019 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Garrick Evans3388a032020-03-24 11:25:55 +09005#include "patchpanel/datapath.h"
Garrick Evansf0ab7132019-06-18 14:50:42 +09006
Garrick Evans3d97a392020-02-21 15:24:37 +09007#include <arpa/inet.h>
Garrick Evansc7ae82c2019-09-04 16:25:10 +09008#include <fcntl.h>
9#include <linux/if_tun.h>
10#include <linux/sockios.h>
11#include <net/if.h>
12#include <net/if_arp.h>
13#include <netinet/in.h>
14#include <string.h>
15#include <sys/ioctl.h>
16#include <sys/socket.h>
17
Hugo Benichi2a940542020-10-26 18:50:49 +090018#include <algorithm>
Hugo Benichid82d8832020-08-14 10:05:03 +090019
Qijiang Fan713061e2021-03-08 15:45:12 +090020#include <base/check.h>
Garrick Evansc7ae82c2019-09-04 16:25:10 +090021#include <base/files/scoped_file.h>
22#include <base/logging.h>
Taoyu Li79871c92020-07-02 16:09:39 +090023#include <base/posix/eintr_wrapper.h>
Garrick Evans54861622019-07-19 09:05:09 +090024#include <base/strings/string_number_conversions.h>
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +090025#include <base/strings/string_util.h>
26#include <base/strings/stringprintf.h>
Garrick Evans4f9f5572019-11-26 10:25:16 +090027#include <brillo/userdb_utils.h>
Garrick Evans54861622019-07-19 09:05:09 +090028
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090029#include "patchpanel/adb_proxy.h"
Hugo Benichibfc49112020-12-14 12:54:44 +090030#include "patchpanel/arc_service.h"
Garrick Evans3388a032020-03-24 11:25:55 +090031#include "patchpanel/net_util.h"
32#include "patchpanel/scoped_ns.h"
Garrick Evansc7ae82c2019-09-04 16:25:10 +090033
Garrick Evans3388a032020-03-24 11:25:55 +090034namespace patchpanel {
Garrick Evans54861622019-07-19 09:05:09 +090035
Garrick Evansc7ae82c2019-09-04 16:25:10 +090036namespace {
Hugo Benichi76675592020-04-08 14:29:57 +090037// TODO(hugobenichi) Consolidate this constant definition in a single place.
38constexpr pid_t kTestPID = -2;
Garrick Evansc7ae82c2019-09-04 16:25:10 +090039constexpr char kDefaultIfname[] = "vmtap%d";
40constexpr char kTunDev[] = "/dev/net/tun";
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090041constexpr char kArcAddr[] = "100.115.92.2";
42constexpr char kLocalhostAddr[] = "127.0.0.1";
43constexpr uint16_t kAdbServerPort = 5555;
Hugo Benichie8758b52020-04-03 14:49:01 +090044
Hugo Benichibf811c62020-09-07 17:30:45 +090045// Constants used for dropping locally originated traffic bound to an incorrect
46// source IPv4 address.
47constexpr char kGuestIPv4Subnet[] = "100.115.92.0/23";
48constexpr std::array<const char*, 6> kPhysicalIfnamePrefixes{
49 {"eth+", "wlan+", "mlan+", "usb+", "wwan+", "rmnet+"}};
50
Hugo Benichi3a9162b2020-09-09 15:47:40 +090051constexpr char kApplyLocalSourceMarkChain[] = "apply_local_source_mark";
Hugo Benichi3ef370b2020-11-16 19:07:17 +090052constexpr char kApplyVpnMarkChain[] = "apply_vpn_mark";
Hugo Benichi155de002021-01-19 16:45:46 +090053constexpr char kCheckRoutingMarkChain[] = "check_routing_mark";
Hugo Benichi1e0656f2021-02-15 15:43:38 +090054constexpr char kDropGuestIpv4PrefixChain[] = "drop_guest_ipv4_prefix";
55constexpr char kRedirectDnsChain[] = "redirect_dns";
Hugo Benichi2a940542020-10-26 18:50:49 +090056
Hugo Benichif0f55562021-04-02 15:25:02 +090057// Maximum length of an iptables chain name.
58constexpr int kIptablesMaxChainLength = 28;
59
Garrick Evans8a067562020-05-11 12:47:30 +090060std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
61 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090062 if (n.length() < IFNAMSIZ)
63 return n;
Garrick Evans54861622019-07-19 09:05:09 +090064
Garrick Evans2f581a02020-05-11 10:43:35 +090065 // Best effort attempt to preserve the interface number, assuming it's the
66 // last char in the name.
67 auto c = ifname[ifname.length() - 1];
68 n.resize(IFNAMSIZ - 1);
69 n[n.length() - 1] = c;
70 return n;
Garrick Evans54861622019-07-19 09:05:09 +090071}
Garrick Evansf0ab7132019-06-18 14:50:42 +090072
Hugo Benichiaba7e2e2021-02-22 14:47:11 +090073bool Ioctl(ioctl_t ioctl_h, unsigned long req, const char* arg) {
74 base::ScopedFD control_fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
75 if (!control_fd.is_valid()) {
76 PLOG(ERROR) << "Failed to create control socket for ioctl request=" << req;
77 return false;
78 }
79 if ((*ioctl_h)(control_fd.get(), req, arg) != 0) {
80 PLOG(ERROR) << "ioctl request=" << req << " failed";
81 return false;
82 }
83 return true;
84}
85
Garrick Evans8a067562020-05-11 12:47:30 +090086} // namespace
87
88std::string ArcVethHostName(const std::string& ifname) {
89 return PrefixIfname("veth", ifname);
90}
91
92std::string ArcBridgeName(const std::string& ifname) {
93 return PrefixIfname("arc_", ifname);
94}
95
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090096Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
97 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090098
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090099Datapath::Datapath(MinijailedProcessRunner* process_runner,
100 Firewall* firewall,
101 ioctl_t ioctl_hook)
102 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900103 CHECK(process_runner_);
104}
105
Garrick Evans260ff302019-07-25 11:22:50 +0900106MinijailedProcessRunner& Datapath::runner() const {
107 return *process_runner_;
108}
109
Hugo Benichibf811c62020-09-07 17:30:45 +0900110void Datapath::Start() {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900111 // Restart from a clean iptables state in case of an unordered shutdown.
112 ResetIptables();
113
Hugo Benichibf811c62020-09-07 17:30:45 +0900114 // Enable IPv4 packet forwarding
115 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
116 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
117 << " Guest connectivity will not work correctly.";
118
119 // Limit local port range: Android owns 47104-61000.
120 // TODO(garrick): The original history behind this tweak is gone. Some
121 // investigation is needed to see if it is still applicable.
122 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
123 "32768 47103") != 0)
124 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
125 << " apps may not work correctly.";
126
127 // Enable IPv6 packet forwarding
128 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
129 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
130 << " IPv6 functionality may be broken.";
131
Hugo Benichi58125d32020-09-09 11:25:45 +0900132 // Create a FORWARD ACCEPT rule for connections already established.
133 if (process_runner_->iptables(
134 "filter", {"-A", "FORWARD", "-m", "state", "--state",
135 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900136 LOG(ERROR) << "Failed to install forwarding rule for established"
137 << " connections.";
138
Hugo Benichiac799a82021-03-25 00:16:16 +0900139 // Create a FORWARD rule for accepting any ARC originated traffic regardless
140 // of the output interface. This enables for ARC certain multihoming
141 // scenarios (b/182594063).
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900142 if (!ModifyJumpRule(IpFamily::IPv4, "filter", "-A", "FORWARD", "ACCEPT",
143 "arc+", "" /*oif*/))
Hugo Benichiac799a82021-03-25 00:16:16 +0900144 LOG(ERROR) << "Failed to install forwarding rule for ARC traffic";
145
Hugo Benichibf811c62020-09-07 17:30:45 +0900146 // chromium:898210: Drop any locally originated traffic that would exit a
147 // physical interface with a source IPv4 address from the subnet of IPs used
148 // for VMs, containers, and connected namespaces This is needed to prevent
149 // packets leaking with an incorrect src IP when a local process binds to the
150 // wrong interface.
Hugo Benichif0f55562021-04-02 15:25:02 +0900151 if (!AddChain(IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain))
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900152 LOG(ERROR) << "Failed to create " << kDropGuestIpv4PrefixChain
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900153 << " filter chain";
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900154 if (!ModifyJumpRule(IpFamily::IPv4, "filter", "-I", "OUTPUT",
155 kDropGuestIpv4PrefixChain, "" /*iif*/, "" /*oif*/))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900156 LOG(ERROR) << "Failed to set up jump rule from filter OUTPUT to "
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900157 << kDropGuestIpv4PrefixChain;
Hugo Benichibf811c62020-09-07 17:30:45 +0900158 for (const auto& oif : kPhysicalIfnamePrefixes) {
159 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
160 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
161 << kGuestIPv4Subnet << " exiting " << oif;
162 }
163
Hugo Benichi561fae42021-01-22 15:28:40 +0900164 // Set static SNAT rules for any IPv4 traffic originated from a guest (ARC,
165 // Crostini, ...) or a connected namespace.
166 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
167 // need to be explicitly dropped as SNAT cannot be applied to them.
168 if (process_runner_->iptables(
169 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
170 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0)
171 LOG(ERROR) << "Failed to install SNAT mark rules.";
172 if (process_runner_->iptables(
173 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
174 "MASQUERADE", "-w"}) != 0)
175 LOG(ERROR) << "Failed to install SNAT mark rules.";
Hugo Benichibf811c62020-09-07 17:30:45 +0900176 if (!AddOutboundIPv4SNATMark("vmtap+"))
Hugo Benichi561fae42021-01-22 15:28:40 +0900177 LOG(ERROR) << "Failed to set up NAT for TAP devices.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900178
Hugo Benichi2a940542020-10-26 18:50:49 +0900179 // Applies the routing tag saved in conntrack for any established connection
180 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900181 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
182 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900183 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
Hugo Benichi155de002021-01-19 16:45:46 +0900184 // b/177787823 Also restore the routing tag after routing has taken place so
185 // that packets pre-tagged with the VPN routing tag are in sync with their
186 // associated CONNMARK routing tag. This is necessary to correctly identify
187 // packets exiting through the wrong interface.
188 if (!ModifyConnmarkRestore(IpFamily::Dual, "POSTROUTING", "-A", "" /*iif*/,
189 kFwmarkRoutingMask))
190 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK restore rule";
Hugo Benichi2a940542020-10-26 18:50:49 +0900191
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900192 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
193 // tag and tagging the local traffic that should be routed through a VPN.
Hugo Benichif0f55562021-04-02 15:25:02 +0900194 if (!AddChain(IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900195 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
196 << " mangle chain";
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900197 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "OUTPUT",
198 kApplyLocalSourceMarkChain, "" /*iif*/, "" /*oif*/))
199
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900200 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
201 << " to mangle OUTPUT";
202 // Create rules for tagging local sources with the source tag and the vpn
203 // policy tag.
204 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900205 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900206 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
207 << " in " << kApplyLocalSourceMarkChain;
208 }
209 // Finally add a catch-all rule for tagging any remaining local sources with
210 // the SYSTEM source tag
211 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
212 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
213
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900214 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
215 // traffic that should be routed through a VPN.
Hugo Benichif0f55562021-04-02 15:25:02 +0900216 if (!AddChain(IpFamily::Dual, "mangle", kApplyVpnMarkChain))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900217 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900218 // All local outgoing traffic eligible to VPN routing should traverse the VPN
219 // marking chain.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900220 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", kFwmarkRouteOnVpn,
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900221 kFwmarkVpnMask))
222 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
223 // Any traffic that already has a routing tag applied is accepted.
224 if (!ModifyIptables(
225 IpFamily::Dual, "mangle",
226 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
227 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
228 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
229 "connections";
Hugo Benichi155de002021-01-19 16:45:46 +0900230
231 // Sets up a mangle chain used in POSTROUTING for checking consistency between
232 // the routing tag and the output interface.
Hugo Benichif0f55562021-04-02 15:25:02 +0900233 if (!AddChain(IpFamily::Dual, "mangle", kCheckRoutingMarkChain))
Hugo Benichi155de002021-01-19 16:45:46 +0900234 LOG(ERROR) << "Failed to set up " << kCheckRoutingMarkChain
235 << " mangle chain";
Hugo Benichi155de002021-01-19 16:45:46 +0900236 // b/177787823 If it already exists, the routing tag of any traffic exiting an
237 // interface (physical or VPN) must match the routing tag of that interface.
238 if (!ModifyIptables(IpFamily::Dual, "mangle",
239 {"-A", "POSTROUTING", "-m", "mark", "!", "--mark",
240 "0x0/" + kFwmarkRoutingMask.ToString(), "-j",
241 kCheckRoutingMarkChain, "-w"}))
242 LOG(ERROR) << "Failed to add POSTROUTING jump rule to "
243 << kCheckRoutingMarkChain;
Hugo Benichi52a64992021-01-28 17:47:33 +0900244
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900245 // b/178331695 Sets up a nat chain used in OUTPUT for redirecting DNS queries
246 // of system services. When a VPN is connected, a query routed through a
247 // physical network is redirected to the primary nameserver of that network.
Hugo Benichif0f55562021-04-02 15:25:02 +0900248 if (!AddChain(IpFamily::IPv4, "nat", kRedirectDnsChain))
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900249 LOG(ERROR) << "Failed to set up " << kRedirectDnsChain << " nat chain";
250
Hugo Benichi52a64992021-01-28 17:47:33 +0900251 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
252 // incorrectly cause neighbor discovery icmpv6 packets to be dropped. Add
253 // these rules to bypass connmark rule for those packets.
254 for (const auto& type : kNeighborDiscoveryTypes) {
255 if (!ModifyIptables(IpFamily::IPv6, "mangle",
256 {"-I", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
257 "-j", "ACCEPT", "-w"}))
258 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
259 << " packets in OUTPUT";
260 if (!ModifyIptables(IpFamily::IPv6, "mangle",
261 {"-I", kCheckRoutingMarkChain, "-p", "icmpv6",
262 "--icmpv6-type", type, "-j", "RETURN", "-w"}))
263 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
264 << " packets in " << kCheckRoutingMarkChain;
265 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900266}
267
268void Datapath::Stop() {
Hugo Benichibf811c62020-09-07 17:30:45 +0900269 // Restore original local port range.
270 // TODO(garrick): The original history behind this tweak is gone. Some
271 // investigation is needed to see if it is still applicable.
272 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
273 "32768 61000") != 0)
274 LOG(ERROR) << "Failed to restore local port range";
275
276 // Disable packet forwarding
277 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
278 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
279
280 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
281 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900282
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900283 ResetIptables();
284}
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900285
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900286void Datapath::ResetIptables() {
287 // If it exists, remove jump rules from a built-in chain to a custom routing
288 // or tagging chain.
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900289 ModifyJumpRule(IpFamily::IPv4, "filter", "-D", "OUTPUT",
290 kDropGuestIpv4PrefixChain, "" /*iif*/, "" /*oif*/,
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900291 false /*log_failures*/);
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900292
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900293 // Flush chains used for routing and fwmark tagging. Also delete additional
294 // chains made by patchpanel. Chains used by permission broker (nat
295 // PREROUTING, filter INPUT) and chains used for traffic counters (mangle
296 // {rx,tx}_{<iface>, vpn}) are not flushed.
297 static struct {
298 IpFamily family;
299 std::string table;
300 std::string chain;
301 bool should_delete;
302 } resetOps[] = {
303 {IpFamily::Dual, "filter", "FORWARD", false},
304 {IpFamily::Dual, "mangle", "FORWARD", false},
305 {IpFamily::Dual, "mangle", "INPUT", false},
306 {IpFamily::Dual, "mangle", "OUTPUT", false},
307 {IpFamily::Dual, "mangle", "POSTROUTING", false},
308 {IpFamily::Dual, "mangle", "PREROUTING", false},
309 {IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain, true},
310 {IpFamily::Dual, "mangle", kApplyVpnMarkChain, true},
311 {IpFamily::Dual, "mangle", kCheckRoutingMarkChain, true},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900312 {IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain, true},
313 {IpFamily::IPv4, "nat", kRedirectDnsChain, true},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900314 {IpFamily::IPv4, "nat", "POSTROUTING", false},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900315 {IpFamily::IPv4, "nat", "OUTPUT", false},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900316 };
317 for (const auto& op : resetOps) {
318 // Chains to delete are custom chains and will not exist the first time
319 // patchpanel starts after boot. Skip flushing and delete these chains if
320 // they do not exist to avoid logging spurious error messages.
321 if (op.should_delete && !ModifyChain(op.family, op.table, "-L", op.chain,
322 false /*log_failures*/))
323 continue;
Hugo Benichi155de002021-01-19 16:45:46 +0900324
Hugo Benichif0f55562021-04-02 15:25:02 +0900325 if (!FlushChain(op.family, op.table, op.chain))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900326 LOG(ERROR) << "Failed to flush " << op.chain << " chain in table "
327 << op.table;
Hugo Benichi2a940542020-10-26 18:50:49 +0900328
Hugo Benichif0f55562021-04-02 15:25:02 +0900329 if (op.should_delete && !RemoveChain(op.family, op.table, op.chain))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900330 LOG(ERROR) << "Failed to delete " << op.chain << " chain in table "
331 << op.table;
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900332 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900333}
334
Hugo Benichi33860d72020-07-09 16:34:01 +0900335bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
336 // Try first to delete any netns with name |netns_name| in case patchpanel
337 // did not exit cleanly.
338 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
339 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
340 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
341}
342
343bool Datapath::NetnsDeleteName(const std::string& netns_name) {
344 return process_runner_->ip_netns_delete(netns_name) == 0;
345}
346
Garrick Evans8a949dc2019-07-18 16:17:53 +0900347bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900348 uint32_t ipv4_addr,
349 uint32_t ipv4_prefix_len) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900350 if (!Ioctl(ioctl_, SIOCBRADDBR, ifname.c_str())) {
351 LOG(ERROR) << "Failed to create bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900352 return false;
353 }
354
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900355 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900356 if (process_runner_->ip(
357 "addr", "add",
358 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
359 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
360 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900361 RemoveBridge(ifname);
362 return false;
363 }
364
365 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900366 RemoveBridge(ifname);
367 return false;
368 }
369
370 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900371 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900372 RemoveBridge(ifname);
373 return false;
374 }
375
376 return true;
377}
378
379void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900380 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900381 process_runner_->ip("link", "set", {ifname, "down"});
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900382 if (!Ioctl(ioctl_, SIOCBRDELBR, ifname.c_str()))
383 LOG(ERROR) << "Failed to destroy bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900384}
385
Garrick Evans621ed262019-11-13 12:28:43 +0900386bool Datapath::AddToBridge(const std::string& br_ifname,
387 const std::string& ifname) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900388 struct ifreq ifr;
389 memset(&ifr, 0, sizeof(ifr));
390 strncpy(ifr.ifr_name, br_ifname.c_str(), sizeof(ifr.ifr_name));
391 ifr.ifr_ifindex = FindIfIndex(ifname);
392
393 if (!Ioctl(ioctl_, SIOCBRADDIF, reinterpret_cast<const char*>(&ifr))) {
394 LOG(ERROR) << "Failed to add " << ifname << " to bridge " << br_ifname;
395 return false;
396 }
397
398 return true;
Garrick Evans621ed262019-11-13 12:28:43 +0900399}
400
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900401std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900402 const MacAddress* mac_addr,
403 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900404 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900405 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
406 if (!dev.is_valid()) {
407 PLOG(ERROR) << "Failed to open " << kTunDev;
408 return "";
409 }
410
411 struct ifreq ifr;
412 memset(&ifr, 0, sizeof(ifr));
413 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
414 sizeof(ifr.ifr_name));
415 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
416
417 // If a template was given as the name, ifr_name will be updated with the
418 // actual interface name.
419 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900420 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900421 return "";
422 }
423 const char* ifname = ifr.ifr_name;
424
425 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900426 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900427 return "";
428 }
429
Garrick Evans4f9f5572019-11-26 10:25:16 +0900430 if (!user.empty()) {
431 uid_t uid = -1;
432 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
433 PLOG(ERROR) << "Unable to look up UID for " << user;
434 RemoveTAP(ifname);
435 return "";
436 }
437 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
438 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
439 << ifname;
440 RemoveTAP(ifname);
441 return "";
442 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900443 }
444
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900445 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900446 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
447 if (!sock.is_valid()) {
448 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900449 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900450 RemoveTAP(ifname);
451 return "";
452 }
453
Garrick Evans621ed262019-11-13 12:28:43 +0900454 if (ipv4_addr) {
455 struct sockaddr_in* addr =
456 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
457 addr->sin_family = AF_INET;
458 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
459 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
460 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
461 << " {" << ipv4_addr->ToCidrString() << "}";
462 RemoveTAP(ifname);
463 return "";
464 }
465
466 struct sockaddr_in* netmask =
467 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
468 netmask->sin_family = AF_INET;
469 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
470 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
471 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
472 << " {" << ipv4_addr->ToCidrString() << "}";
473 RemoveTAP(ifname);
474 return "";
475 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900476 }
477
Garrick Evans621ed262019-11-13 12:28:43 +0900478 if (mac_addr) {
479 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
480 hwaddr->sa_family = ARPHRD_ETHER;
481 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
482 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
483 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
484 << " {" << MacAddressToString(*mac_addr) << "}";
485 RemoveTAP(ifname);
486 return "";
487 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900488 }
489
490 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900491 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900492 RemoveTAP(ifname);
493 return "";
494 }
495
496 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
497 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900498 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900499 RemoveTAP(ifname);
500 return "";
501 }
502
503 return ifname;
504}
505
506void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900507 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900508}
509
Hugo Benichi33860d72020-07-09 16:34:01 +0900510bool Datapath::ConnectVethPair(pid_t netns_pid,
511 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900512 const std::string& veth_ifname,
513 const std::string& peer_ifname,
514 const MacAddress& remote_mac_addr,
515 uint32_t remote_ipv4_addr,
516 uint32_t remote_ipv4_prefix_len,
517 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900518 // Set up the virtual pair across the current namespace and |netns_name|.
519 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
520 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
521 << peer_ifname;
522 return false;
523 }
524
525 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900526 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900527 ScopedNS ns(netns_pid, ScopedNS::Type::Network);
Hugo Benichi33860d72020-07-09 16:34:01 +0900528 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900529 LOG(ERROR)
530 << "Cannot create virtual link -- invalid container namespace?";
531 return false;
532 }
533
Hugo Benichi76675592020-04-08 14:29:57 +0900534 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
535 remote_ipv4_prefix_len, true /* link up */,
536 remote_multicast_flag)) {
537 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
538 RemoveInterface(peer_ifname);
539 return false;
540 }
541 }
542
Hugo Benichi76675592020-04-08 14:29:57 +0900543 if (!ToggleInterface(veth_ifname, true /*up*/)) {
544 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
545 RemoveInterface(veth_ifname);
546 return false;
547 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900548
Hugo Benichi76675592020-04-08 14:29:57 +0900549 return true;
550}
551
Hugo Benichi33860d72020-07-09 16:34:01 +0900552bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
553 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900554 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900555 return process_runner_->ip("link", "add",
556 {veth_ifname, "type", "veth", "peer", "name",
557 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900558}
Garrick Evans54861622019-07-19 09:05:09 +0900559
Garrick Evans2470caa2020-03-04 14:15:41 +0900560bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
561 const std::string link = up ? "up" : "down";
562 return process_runner_->ip("link", "set", {ifname, link}) == 0;
563}
Garrick Evans54861622019-07-19 09:05:09 +0900564
Garrick Evans2470caa2020-03-04 14:15:41 +0900565bool Datapath::ConfigureInterface(const std::string& ifname,
566 const MacAddress& mac_addr,
567 uint32_t ipv4_addr,
568 uint32_t ipv4_prefix_len,
569 bool up,
570 bool enable_multicast) {
571 const std::string link = up ? "up" : "down";
572 const std::string multicast = enable_multicast ? "on" : "off";
573 return (process_runner_->ip(
574 "addr", "add",
575 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
576 IPv4AddressToString(
577 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
578 "dev", ifname}) == 0) &&
579 (process_runner_->ip("link", "set",
580 {
581 "dev",
582 ifname,
583 link,
584 "addr",
585 MacAddressToString(mac_addr),
586 "multicast",
587 multicast,
588 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900589}
590
591void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900592 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900593}
594
Hugo Benichi321f23b2020-09-25 15:42:05 +0900595bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
596 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900597 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900598 "filter", {"-I", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
599 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900600}
601
602bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
603 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900604 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900605 "filter", {"-D", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
606 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900607}
608
Hugo Benichifcf81022020-12-04 11:01:37 +0900609bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900610 // Veth interface configuration and client routing configuration:
611 // - attach a name to the client namespace.
612 // - create veth pair across the current namespace and the client namespace.
613 // - configure IPv4 address on remote veth inside client namespace.
614 // - configure IPv4 address on local veth inside host namespace.
615 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900616 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
617 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
618 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900619 return false;
620 }
621
Hugo Benichifcf81022020-12-04 11:01:37 +0900622 if (!ConnectVethPair(
623 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
624 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
625 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900626 LOG(ERROR) << "Failed to create veth pair for"
627 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900628 << nsinfo.pid;
629 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900630 return false;
631 }
632
Hugo Benichifcf81022020-12-04 11:01:37 +0900633 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
634 nsinfo.peer_subnet->AddressAtOffset(0),
635 nsinfo.peer_subnet->PrefixLength(),
636 true /* link up */, false /* enable_multicast */)) {
637 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
638 RemoveInterface(nsinfo.host_ifname);
639 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900640 return false;
641 }
642
643 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900644 ScopedNS ns(nsinfo.pid, ScopedNS::Type::Network);
Hugo Benichifcf81022020-12-04 11:01:37 +0900645 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
646 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
647 RemoveInterface(nsinfo.host_ifname);
648 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900649 return false;
650 }
651
Hugo Benichifcf81022020-12-04 11:01:37 +0900652 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
653 INADDR_ANY)) {
654 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
655 << " inside namespace pid " << nsinfo.pid;
656 RemoveInterface(nsinfo.host_ifname);
657 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900658 return false;
659 }
660 }
661
662 // Host namespace routing configuration
663 // - ingress: add route to client subnet via |host_ifname|.
664 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
665 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
666 // Note that by default unsolicited ingress traffic is not forwarded to the
667 // client namespace unless the client specifically set port forwarding
668 // through permission_broker DBus APIs.
669 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
670 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900671 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
672 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
673 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900674 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900675 RemoveInterface(nsinfo.host_ifname);
676 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900677 return false;
678 }
679
Hugo Benichi7c342672020-09-08 09:18:14 +0900680 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900681 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900682 LOG(ERROR) << "Failed to set SNAT for traffic"
683 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900684 << nsinfo.host_ifname;
685 RemoveInterface(nsinfo.host_ifname);
686 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
687 nsinfo.peer_subnet->BaseAddress(), netmask);
688 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
689 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900690 return false;
691 }
692
Hugo Benichi93306e52020-12-04 16:08:00 +0900693 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
694 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
695 nsinfo.route_on_vpn);
696
Hugo Benichi7c342672020-09-08 09:18:14 +0900697 return true;
698}
699
Hugo Benichifcf81022020-12-04 11:01:37 +0900700void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900701 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
702 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
703 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900704 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900705 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
706 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
707 nsinfo.peer_subnet->BaseAddress(),
708 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
709 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900710}
711
Hugo Benichi8d622b52020-08-13 15:24:12 +0900712void Datapath::StartRoutingDevice(const std::string& ext_ifname,
713 const std::string& int_ifname,
714 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900715 TrafficSource source,
716 bool route_on_vpn) {
717 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900718 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900719 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
720 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
721 << "->" << int_ifname;
722
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900723 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900724 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
725 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900726
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900727 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900728 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
729 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900730
Hugo Benichid872d3d2021-03-29 10:20:53 +0900731 std::string subchain = "PREROUTING_" + int_ifname;
732 // This can fail if patchpanel did not stopped correctly or failed to cleanup
733 // the chain when |int_ifname| was previously deleted.
734 if (!AddChain(IpFamily::Dual, "mangle", subchain))
735 LOG(ERROR) << "Failed to create mangle chain " << subchain;
736 // Make sure the chain is empty if patchpanel did not cleaned correctly that
737 // chain before.
738 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
739 LOG(ERROR) << "Could not flush " << subchain;
740 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "PREROUTING", subchain,
741 int_ifname, "" /*oif*/))
742 LOG(ERROR) << "Could not add jump rule from mangle PREROUTING to "
743 << subchain;
744 if (!ModifyFwmarkSourceTag(subchain, "-A", source))
745 LOG(ERROR) << "Failed to add fwmark tagging rule for source " << source
746 << " in " << subchain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900747
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900748 if (!ext_ifname.empty()) {
749 // If |ext_ifname| is not null, mark egress traffic with the
750 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900751 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900752 if (ifindex == 0) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900753 LOG(ERROR) << "Failed to retrieve interface index of " << ext_ifname;
Hugo Benichid872d3d2021-03-29 10:20:53 +0900754 return;
Hugo Benichi8c526e92021-03-25 14:59:59 +0900755 }
Hugo Benichid872d3d2021-03-29 10:20:53 +0900756 if (!ModifyFwmarkRoutingTag(subchain, "-A", Fwmark::FromIfIndex(ifindex)))
757 LOG(ERROR) << "Failed to add fwmark routing tag for " << ext_ifname
758 << "<-" << int_ifname << " in " << subchain;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900759 } else {
760 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
761 // PREROUTING to apply any fwmark routing tag saved for the current
762 // connection, and rely on implicit routing to the default logical network
763 // otherwise.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900764 if (!ModifyConnmarkRestore(IpFamily::Dual, subchain, "-A", "" /*iif*/,
Hugo Benichi1af52392020-11-27 18:09:32 +0900765 kFwmarkRoutingMask))
Hugo Benichid872d3d2021-03-29 10:20:53 +0900766 LOG(ERROR) << "Failed to add CONNMARK restore rule in " << subchain;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900767
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900768 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900769 // default network is eligible to be routed through a VPN if |route_on_vpn|
770 // is true.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900771 if (route_on_vpn && !ModifyFwmarkVpnJumpRule(subchain, "-A", {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900772 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900773 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900774}
775
776void Datapath::StopRoutingDevice(const std::string& ext_ifname,
777 const std::string& int_ifname,
778 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900779 TrafficSource source,
780 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900781 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900782 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900783 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
784 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900785
786 std::string subchain = "PREROUTING_" + int_ifname;
787 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "PREROUTING", subchain,
788 int_ifname, "" /*oif*/);
789 FlushChain(IpFamily::Dual, "mangle", subchain);
790 RemoveChain(IpFamily::Dual, "mangle", subchain);
Hugo Benichi8d622b52020-08-13 15:24:12 +0900791}
792
Garrick Evansf0ab7132019-06-18 14:50:42 +0900793bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
794 const std::string& ipv4_addr) {
795 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900796 if (process_runner_->iptables(
797 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
798 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900799 return false;
800
801 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900802 if (process_runner_->iptables(
803 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
804 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900805 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
806 return false;
807 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900808 if (process_runner_->iptables(
809 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
810 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900811 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
812 return false;
813 }
814
815 return true;
816}
817
818void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
819 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900820 process_runner_->iptables(
821 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
822 "--to-destination", ipv4_addr, "-w"});
823 process_runner_->iptables(
824 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
825 "--to-destination", ipv4_addr, "-w"});
826 process_runner_->iptables(
827 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
828 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900829}
830
Hugo Benichid872d3d2021-03-29 10:20:53 +0900831// TODO(b/161060333) Migrate this rule to the PREROUTING_<iface> subchains
Hugo Benichie8758b52020-04-03 14:49:01 +0900832bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
833 return process_runner_->iptables(
834 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900835 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900836}
837
838void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
839 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900840 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900841}
842
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900843bool Datapath::AddRedirectDnsRule(const std::string& ifname,
844 const std::string dns_ipv4_addr) {
845 bool success = true;
846 success &= RemoveRedirectDnsRule(ifname);
847 // Use Insert operation to ensure that the new DNS address is used first.
848 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
849 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
850 physical_dns_addresses_[ifname] = dns_ipv4_addr;
851 return success;
852}
853
854bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
855 const auto it = physical_dns_addresses_.find(ifname);
856 if (it == physical_dns_addresses_.end())
857 return true;
858
859 bool success = true;
860 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
861 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
862 physical_dns_addresses_.erase(it);
863 return success;
864}
865
866bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
867 const std::string& protocol,
868 const std::string& ifname,
869 const std::string& dns_ipv4_addr) {
870 std::vector<std::string> args = {op,
871 kRedirectDnsChain,
872 "-p",
873 protocol,
874 "--dport",
875 "53",
876 "-o",
877 ifname,
878 "-j",
879 "DNAT",
880 "--to-destination",
881 dns_ipv4_addr,
882 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900883 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900884}
885
886bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
887 std::vector<std::string> args = {
888 op,
889 "OUTPUT",
890 "-m",
891 "mark",
892 "!",
893 "--mark",
894 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
895 "-j",
896 kRedirectDnsChain,
897 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900898 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900899}
900
Garrick Evans664a82f2019-12-17 12:18:05 +0900901bool Datapath::MaskInterfaceFlags(const std::string& ifname,
902 uint16_t on,
903 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900904 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
905 if (!sock.is_valid()) {
906 PLOG(ERROR) << "Failed to create control socket";
907 return false;
908 }
909 ifreq ifr;
910 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
911 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
912 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
913 return false;
914 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900915 ifr.ifr_flags |= on;
916 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900917 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900918 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
919 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900920 return false;
921 }
922 return true;
923}
924
Garrick Evans260ff302019-07-25 11:22:50 +0900925bool Datapath::AddIPv6HostRoute(const std::string& ifname,
926 const std::string& ipv6_addr,
927 int ipv6_prefix_len) {
928 std::string ipv6_addr_cidr =
929 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
930
Garrick Evans8e8e3472020-01-23 14:03:50 +0900931 return process_runner_->ip6("route", "replace",
932 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900933}
934
935void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
936 const std::string& ipv6_addr,
937 int ipv6_prefix_len) {
938 std::string ipv6_addr_cidr =
939 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
940
Garrick Evans8e8e3472020-01-23 14:03:50 +0900941 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900942}
943
Taoyu Lia0727dc2020-09-24 19:54:59 +0900944bool Datapath::AddIPv6Address(const std::string& ifname,
945 const std::string& ipv6_addr) {
946 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900947}
948
Taoyu Lia0727dc2020-09-24 19:54:59 +0900949void Datapath::RemoveIPv6Address(const std::string& ifname,
950 const std::string& ipv6_addr) {
951 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900952}
953
Hugo Benichi76be34a2020-08-26 22:35:54 +0900954void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900955 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +0900956 if (ifindex == 0) {
957 // Can happen if the interface has already been removed (b/183679000).
958 LOG(ERROR) << "Failed to set up connection pinning on " << ext_ifname;
959 return;
960 }
961
962 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
963 LOG(INFO) << "Start connection pinning on " << ext_ifname
964 << " fwmark=" << routing_mark.ToString();
965 if (!ModifyIptables(
966 IpFamily::Dual, "mangle",
967 {"-A", kCheckRoutingMarkChain, "-o", ext_ifname, "-m", "mark", "!",
968 "--mark",
Hugo Benichi0a110402021-03-25 11:32:52 +0900969 routing_mark.ToString() + "/" + kFwmarkRoutingMask.ToString(),
970 "-w"}))
Hugo Benichi155de002021-01-19 16:45:46 +0900971 LOG(ERROR) << "Could not set fwmark routing filter rule for " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900972 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900973 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname,
974 routing_mark))
Hugo Benichi76be34a2020-08-26 22:35:54 +0900975 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900976 // Save in CONNMARK the source tag for egress traffic of this connection.
977 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
978 kFwmarkAllSourcesMask))
979 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
980 "source tag on "
981 << ext_ifname;
982 // Restore from CONNMARK the source tag for ingress traffic of this connection
983 // (returned traffic).
984 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
985 kFwmarkAllSourcesMask))
986 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
987 "traffic received on "
988 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900989}
990
991void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900992 Fwmark routing_mark = CachedRoutingFwmark(ext_ifname);
993 LOG(INFO) << "Stop connection pinning on " << ext_ifname
994 << " fwmark=" << routing_mark.ToString();
995 if (!ModifyIptables(
996 IpFamily::Dual, "mangle",
997 {"-D", kCheckRoutingMarkChain, "-o", ext_ifname, "-m", "mark", "!",
998 "--mark",
Hugo Benichi0a110402021-03-25 11:32:52 +0900999 routing_mark.ToString() + "/" + kFwmarkRoutingMask.ToString(),
1000 "-w"}))
Hugo Benichi155de002021-01-19 16:45:46 +09001001 LOG(ERROR) << "Could not remove fwmark routing filter rule for "
1002 << ext_ifname;
Hugo Benichi8c526e92021-03-25 14:59:59 +09001003 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname,
1004 routing_mark))
Hugo Benichi76be34a2020-08-26 22:35:54 +09001005 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +09001006 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
1007 kFwmarkAllSourcesMask))
1008 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
1009 "fwmark source tag on "
1010 << ext_ifname;
1011 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
1012 kFwmarkAllSourcesMask))
1013 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
1014 "traffic received on "
1015 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +09001016}
1017
Hugo Benichi2a940542020-10-26 18:50:49 +09001018void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +09001019 int ifindex = FindIfIndex(vpn_ifname);
1020 if (ifindex == 0) {
1021 // Can happen if the interface has already been removed (b/183679000).
1022 LOG(ERROR) << "Failed to start VPN routing on " << vpn_ifname;
1023 return;
1024 }
1025
1026 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
1027 LOG(INFO) << "Start VPN routing on " << vpn_ifname
1028 << " fwmark=" << routing_mark.ToString();
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001029 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-A", "POSTROUTING", "MASQUERADE",
1030 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +09001031 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +09001032 StartConnectionPinning(vpn_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +09001033 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", routing_mark))
Hugo Benichi2a940542020-10-26 18:50:49 +09001034 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +09001035 if (vpn_ifname != kArcBridge)
1036 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
1037 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001038 if (!ModifyRedirectDnsJumpRule("-A"))
1039 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001040}
1041
1042void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +09001043 Fwmark routing_mark = CachedRoutingFwmark(vpn_ifname);
1044 LOG(INFO) << "Stop VPN routing on " << vpn_ifname
1045 << " fwmark=" << routing_mark.ToString();
Hugo Benichibfc49112020-12-14 12:54:44 +09001046 if (vpn_ifname != kArcBridge)
1047 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
1048 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichid872d3d2021-03-29 10:20:53 +09001049 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", routing_mark))
Hugo Benichi2a940542020-10-26 18:50:49 +09001050 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
1051 StopConnectionPinning(vpn_ifname);
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001052 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-D", "POSTROUTING", "MASQUERADE",
1053 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +09001054 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001055 if (!ModifyRedirectDnsJumpRule("-D"))
1056 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001057}
1058
Hugo Benichi76be34a2020-08-26 22:35:54 +09001059bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
1060 const std::string& op,
Hugo Benichi8c526e92021-03-25 14:59:59 +09001061 const std::string& oif,
1062 Fwmark routing_mark) {
1063 return ModifyConnmarkSet(family, "POSTROUTING", op, oif, routing_mark,
1064 kFwmarkRoutingMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001065}
1066
1067bool Datapath::ModifyConnmarkSet(IpFamily family,
1068 const std::string& chain,
1069 const std::string& op,
1070 const std::string& oif,
1071 Fwmark mark,
1072 Fwmark mask) {
1073 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
1074 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
1075 return false;
1076 }
1077
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001078 std::vector<std::string> args = {op, chain};
1079 if (!oif.empty()) {
1080 args.push_back("-o");
1081 args.push_back(oif);
1082 }
1083 args.push_back("-j");
1084 args.push_back("CONNMARK");
1085 args.push_back("--set-mark");
1086 args.push_back(mark.ToString() + "/" + mask.ToString());
1087 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +09001088
Hugo Benichi58f264a2020-10-16 18:16:05 +09001089 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +09001090}
1091
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001092bool Datapath::ModifyConnmarkRestore(IpFamily family,
1093 const std::string& chain,
1094 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001095 const std::string& iif,
1096 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001097 std::vector<std::string> args = {op, chain};
1098 if (!iif.empty()) {
1099 args.push_back("-i");
1100 args.push_back(iif);
1101 }
1102 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001103 mask.ToString(), "-w"});
1104 return ModifyIptables(family, "mangle", args);
1105}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001106
Hugo Benichi1af52392020-11-27 18:09:32 +09001107bool Datapath::ModifyConnmarkSave(IpFamily family,
1108 const std::string& chain,
1109 const std::string& op,
1110 const std::string& oif,
1111 Fwmark mask) {
1112 std::vector<std::string> args = {op, chain};
1113 if (!oif.empty()) {
1114 args.push_back("-o");
1115 args.push_back(oif);
1116 }
1117 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
1118 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +09001119 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001120}
1121
Hugo Benichi2a940542020-10-26 18:50:49 +09001122bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1123 const std::string& op,
Hugo Benichid872d3d2021-03-29 10:20:53 +09001124 Fwmark routing_mark) {
1125 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*int_ifname*/,
1126 "" /*uid_name*/, 0 /*classid*/, routing_mark,
1127 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001128}
1129
Hugo Benichid872d3d2021-03-29 10:20:53 +09001130bool Datapath::ModifyFwmarkSourceTag(const std::string& chain,
1131 const std::string& op,
Hugo Benichi9be19b12020-08-14 15:33:40 +09001132 TrafficSource source) {
Hugo Benichid872d3d2021-03-29 10:20:53 +09001133 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*iif*/, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001134 0 /*classid*/, Fwmark::FromSource(source),
1135 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001136}
1137
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001138bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1139 TrafficSource source) {
1140 std::vector<std::string> args = {"-A",
1141 kApplyLocalSourceMarkChain,
1142 "-m",
1143 "mark",
1144 "--mark",
1145 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1146 "-j",
1147 "MARK",
1148 "--set-mark",
1149 Fwmark::FromSource(source).ToString() + "/" +
1150 kFwmarkAllSourcesMask.ToString(),
1151 "-w"};
1152 return ModifyIptables(IpFamily::Dual, "mangle", args);
1153}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001154
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001155bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1156 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001157 if (std::string(source.uid_name).empty() && source.classid == 0)
1158 return false;
1159
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001160 Fwmark mark = Fwmark::FromSource(source.source_type);
1161 if (source.is_on_vpn)
1162 mark = mark | kFwmarkRouteOnVpn;
1163
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001164 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1165 "" /*iif*/, source.uid_name, source.classid, mark,
1166 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001167}
1168
1169bool Datapath::ModifyFwmark(IpFamily family,
1170 const std::string& chain,
1171 const std::string& op,
1172 const std::string& iif,
1173 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001174 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001175 Fwmark mark,
1176 Fwmark mask,
1177 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001178 std::vector<std::string> args = {op, chain};
1179 if (!iif.empty()) {
1180 args.push_back("-i");
1181 args.push_back(iif);
1182 }
1183 if (!uid_name.empty()) {
1184 args.push_back("-m");
1185 args.push_back("owner");
1186 args.push_back("--uid-owner");
1187 args.push_back(uid_name);
1188 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001189 if (classid != 0) {
1190 args.push_back("-m");
1191 args.push_back("cgroup");
1192 args.push_back("--cgroup");
1193 args.push_back(base::StringPrintf("0x%08x", classid));
1194 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001195 args.push_back("-j");
1196 args.push_back("MARK");
1197 args.push_back("--set-mark");
1198 args.push_back(mark.ToString() + "/" + mask.ToString());
1199 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001200
Hugo Benichi58f264a2020-10-16 18:16:05 +09001201 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001202}
1203
Hugo Benichid82d8832020-08-14 10:05:03 +09001204bool Datapath::ModifyIpForwarding(IpFamily family,
1205 const std::string& op,
1206 const std::string& iif,
1207 const std::string& oif,
1208 bool log_failures) {
1209 if (iif.empty() && oif.empty()) {
1210 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1211 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001212 return false;
1213 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001214 return ModifyJumpRule(family, "filter", op, "FORWARD", "ACCEPT", iif, oif,
1215 log_failures);
1216}
Garrick Evans260ff302019-07-25 11:22:50 +09001217
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001218bool Datapath::ModifyJumpRule(IpFamily family,
1219 const std::string& table,
1220 const std::string& op,
1221 const std::string& chain,
1222 const std::string& target,
1223 const std::string& iif,
1224 const std::string& oif,
1225 bool log_failures) {
1226 std::vector<std::string> args = {op, chain};
Hugo Benichid82d8832020-08-14 10:05:03 +09001227 if (!iif.empty()) {
1228 args.push_back("-i");
1229 args.push_back(iif);
1230 }
1231 if (!oif.empty()) {
1232 args.push_back("-o");
1233 args.push_back(oif);
1234 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001235 args.insert(args.end(), {"-j", target, "-w"});
1236 return ModifyIptables(family, table, args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001237}
1238
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001239bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1240 const std::string& op,
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001241 Fwmark mark,
1242 Fwmark mask) {
1243 std::vector<std::string> args = {op, chain};
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001244 if (mark.Value() != 0 && mask.Value() != 0) {
1245 args.push_back("-m");
1246 args.push_back("mark");
1247 args.push_back("--mark");
1248 args.push_back(mark.ToString() + "/" + mask.ToString());
1249 }
1250 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1251 return ModifyIptables(IpFamily::Dual, "mangle", args);
1252}
1253
Hugo Benichif0f55562021-04-02 15:25:02 +09001254bool Datapath::AddChain(IpFamily family,
1255 const std::string& table,
1256 const std::string& name) {
1257 DCHECK(name.size() <= kIptablesMaxChainLength);
1258 return ModifyChain(family, table, "-N", name);
1259}
1260
1261bool Datapath::RemoveChain(IpFamily family,
1262 const std::string& table,
1263 const std::string& name) {
1264 return ModifyChain(family, table, "-X", name);
1265}
1266
1267bool Datapath::FlushChain(IpFamily family,
1268 const std::string& table,
1269 const std::string& name) {
1270 return ModifyChain(family, table, "-F", name);
1271}
1272
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001273bool Datapath::ModifyChain(IpFamily family,
1274 const std::string& table,
1275 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001276 const std::string& chain,
1277 bool log_failures) {
1278 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001279}
1280
1281bool Datapath::ModifyIptables(IpFamily family,
1282 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001283 const std::vector<std::string>& argv,
1284 bool log_failures) {
1285 switch (family) {
1286 case IPv4:
1287 case IPv6:
1288 case Dual:
1289 break;
1290 default:
1291 LOG(ERROR) << "Could not execute iptables command " << table
1292 << base::JoinString(argv, " ") << ": incorrect IP family "
1293 << family;
1294 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001295 }
1296
1297 bool success = true;
1298 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001299 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001300 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001301 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001302 return success;
1303}
1304
Hugo Benichid82d8832020-08-14 10:05:03 +09001305bool Datapath::StartIpForwarding(IpFamily family,
1306 const std::string& iif,
1307 const std::string& oif) {
1308 return ModifyIpForwarding(family, "-A", iif, oif);
1309}
1310
1311bool Datapath::StopIpForwarding(IpFamily family,
1312 const std::string& iif,
1313 const std::string& oif) {
1314 return ModifyIpForwarding(family, "-D", iif, oif);
1315}
1316
1317bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1318 const std::string& ifname2) {
1319 // Only start Ipv6 forwarding if -C returns false and it had not been
1320 // started yet.
1321 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1322 false /*log_failures*/) &&
1323 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1324 return false;
1325 }
1326
1327 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1328 false /*log_failures*/) &&
1329 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001330 RemoveIPv6Forwarding(ifname1, ifname2);
1331 return false;
1332 }
1333
1334 return true;
1335}
1336
1337void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1338 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001339 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1340 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001341}
1342
Garrick Evans3d97a392020-02-21 15:24:37 +09001343bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1344 uint32_t addr,
1345 uint32_t netmask) {
1346 struct rtentry route;
1347 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001348 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1349 SetSockaddrIn(&route.rt_dst, addr & netmask);
1350 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001351 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001352 return ModifyRtentry(SIOCADDRT, &route);
1353}
Garrick Evans3d97a392020-02-21 15:24:37 +09001354
Hugo Benichie8758b52020-04-03 14:49:01 +09001355bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1356 uint32_t addr,
1357 uint32_t netmask) {
1358 struct rtentry route;
1359 memset(&route, 0, sizeof(route));
1360 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1361 SetSockaddrIn(&route.rt_dst, addr & netmask);
1362 SetSockaddrIn(&route.rt_genmask, netmask);
1363 route.rt_flags = RTF_UP | RTF_GATEWAY;
1364 return ModifyRtentry(SIOCDELRT, &route);
1365}
1366
1367bool Datapath::AddIPv4Route(const std::string& ifname,
1368 uint32_t addr,
1369 uint32_t netmask) {
1370 struct rtentry route;
1371 memset(&route, 0, sizeof(route));
1372 SetSockaddrIn(&route.rt_dst, addr & netmask);
1373 SetSockaddrIn(&route.rt_genmask, netmask);
1374 char rt_dev[IFNAMSIZ];
1375 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1376 rt_dev[IFNAMSIZ - 1] = '\0';
1377 route.rt_dev = rt_dev;
1378 route.rt_flags = RTF_UP | RTF_GATEWAY;
1379 return ModifyRtentry(SIOCADDRT, &route);
1380}
1381
1382bool Datapath::DeleteIPv4Route(const std::string& ifname,
1383 uint32_t addr,
1384 uint32_t netmask) {
1385 struct rtentry route;
1386 memset(&route, 0, sizeof(route));
1387 SetSockaddrIn(&route.rt_dst, addr & netmask);
1388 SetSockaddrIn(&route.rt_genmask, netmask);
1389 char rt_dev[IFNAMSIZ];
1390 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1391 rt_dev[IFNAMSIZ - 1] = '\0';
1392 route.rt_dev = rt_dev;
1393 route.rt_flags = RTF_UP | RTF_GATEWAY;
1394 return ModifyRtentry(SIOCDELRT, &route);
1395}
1396
Taoyu Lia0727dc2020-09-24 19:54:59 +09001397bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001398 DCHECK(route);
1399 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001400 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001401 return false;
1402 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001403 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1404 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001405 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001406 return false;
1407 }
1408 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1409 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001410 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001411 return false;
1412 }
1413 return true;
1414}
1415
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001416bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1417 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1418 kArcAddr, kAdbServerPort, ifname,
1419 kLocalhostAddr, kAdbProxyTcpListenPort);
1420}
1421
1422void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1423 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1424 kArcAddr, kAdbServerPort, ifname,
1425 kLocalhostAddr, kAdbProxyTcpListenPort);
1426}
1427
1428bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1429 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1430 kAdbProxyTcpListenPort, ifname);
1431}
1432
1433void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1434 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1435 kAdbProxyTcpListenPort, ifname);
1436}
1437
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001438void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1439 if_nametoindex_[ifname] = ifindex;
1440}
1441
1442int Datapath::FindIfIndex(const std::string& ifname) {
1443 uint32_t ifindex = if_nametoindex(ifname.c_str());
1444 if (ifindex > 0) {
1445 if_nametoindex_[ifname] = ifindex;
1446 return ifindex;
1447 }
1448
1449 const auto it = if_nametoindex_.find(ifname);
1450 if (it != if_nametoindex_.end())
1451 return it->second;
1452
1453 return 0;
1454}
1455
Hugo Benichi8c526e92021-03-25 14:59:59 +09001456Fwmark Datapath::CachedRoutingFwmark(const std::string& ifname) {
1457 const auto it = if_nametoindex_.find(ifname);
1458 if (it != if_nametoindex_.end())
1459 return Fwmark::FromIfIndex(it->second);
1460
1461 LOG(WARNING) << "No interface index known for " << ifname;
1462 return Fwmark();
1463}
1464
Hugo Benichifcf81022020-12-04 11:01:37 +09001465std::ostream& operator<<(std::ostream& stream,
1466 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001467 stream << "{ pid: " << nsinfo.pid
1468 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001469 if (!nsinfo.outbound_ifname.empty()) {
1470 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1471 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001472 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1473 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001474 << ", peer_ifname: " << nsinfo.peer_ifname
1475 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1476 return stream;
1477}
1478
Garrick Evans3388a032020-03-24 11:25:55 +09001479} // namespace patchpanel