blob: 220b701f4b30877791812a7635b33bf1be57b34e [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 Benichi2a940542020-10-26 18:50:49 +090055
Hugo Benichif0f55562021-04-02 15:25:02 +090056// Maximum length of an iptables chain name.
57constexpr int kIptablesMaxChainLength = 28;
58
Garrick Evans8a067562020-05-11 12:47:30 +090059std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
60 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090061 if (n.length() < IFNAMSIZ)
62 return n;
Garrick Evans54861622019-07-19 09:05:09 +090063
Garrick Evans2f581a02020-05-11 10:43:35 +090064 // Best effort attempt to preserve the interface number, assuming it's the
65 // last char in the name.
66 auto c = ifname[ifname.length() - 1];
67 n.resize(IFNAMSIZ - 1);
68 n[n.length() - 1] = c;
69 return n;
Garrick Evans54861622019-07-19 09:05:09 +090070}
Garrick Evansf0ab7132019-06-18 14:50:42 +090071
Hugo Benichiaba7e2e2021-02-22 14:47:11 +090072bool Ioctl(ioctl_t ioctl_h, unsigned long req, const char* arg) {
73 base::ScopedFD control_fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
74 if (!control_fd.is_valid()) {
75 PLOG(ERROR) << "Failed to create control socket for ioctl request=" << req;
76 return false;
77 }
78 if ((*ioctl_h)(control_fd.get(), req, arg) != 0) {
79 PLOG(ERROR) << "ioctl request=" << req << " failed";
80 return false;
81 }
82 return true;
83}
84
Garrick Evans8a067562020-05-11 12:47:30 +090085} // namespace
86
87std::string ArcVethHostName(const std::string& ifname) {
88 return PrefixIfname("veth", ifname);
89}
90
91std::string ArcBridgeName(const std::string& ifname) {
92 return PrefixIfname("arc_", ifname);
93}
94
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090095Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
96 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090097
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090098Datapath::Datapath(MinijailedProcessRunner* process_runner,
99 Firewall* firewall,
100 ioctl_t ioctl_hook)
101 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900102 CHECK(process_runner_);
103}
104
Garrick Evans260ff302019-07-25 11:22:50 +0900105MinijailedProcessRunner& Datapath::runner() const {
106 return *process_runner_;
107}
108
Hugo Benichibf811c62020-09-07 17:30:45 +0900109void Datapath::Start() {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900110 // Restart from a clean iptables state in case of an unordered shutdown.
111 ResetIptables();
112
Hugo Benichibf811c62020-09-07 17:30:45 +0900113 // Enable IPv4 packet forwarding
114 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
115 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
116 << " Guest connectivity will not work correctly.";
117
118 // Limit local port range: Android owns 47104-61000.
119 // TODO(garrick): The original history behind this tweak is gone. Some
120 // investigation is needed to see if it is still applicable.
121 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
122 "32768 47103") != 0)
123 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
124 << " apps may not work correctly.";
125
126 // Enable IPv6 packet forwarding
127 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
128 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
129 << " IPv6 functionality may be broken.";
130
Hugo Benichi58125d32020-09-09 11:25:45 +0900131 // Create a FORWARD ACCEPT rule for connections already established.
132 if (process_runner_->iptables(
133 "filter", {"-A", "FORWARD", "-m", "state", "--state",
134 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900135 LOG(ERROR) << "Failed to install forwarding rule for established"
136 << " connections.";
137
Hugo Benichiac799a82021-03-25 00:16:16 +0900138 // Create a FORWARD rule for accepting any ARC originated traffic regardless
139 // of the output interface. This enables for ARC certain multihoming
140 // scenarios (b/182594063).
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900141 if (!ModifyJumpRule(IpFamily::IPv4, "filter", "-A", "FORWARD", "ACCEPT",
142 "arc+", "" /*oif*/))
Hugo Benichiac799a82021-03-25 00:16:16 +0900143 LOG(ERROR) << "Failed to install forwarding rule for ARC traffic";
144
Hugo Benichibf811c62020-09-07 17:30:45 +0900145 // chromium:898210: Drop any locally originated traffic that would exit a
146 // physical interface with a source IPv4 address from the subnet of IPs used
147 // for VMs, containers, and connected namespaces This is needed to prevent
148 // packets leaking with an incorrect src IP when a local process binds to the
149 // wrong interface.
Hugo Benichif0f55562021-04-02 15:25:02 +0900150 if (!AddChain(IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain))
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900151 LOG(ERROR) << "Failed to create " << kDropGuestIpv4PrefixChain
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900152 << " filter chain";
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900153 if (!ModifyJumpRule(IpFamily::IPv4, "filter", "-I", "OUTPUT",
154 kDropGuestIpv4PrefixChain, "" /*iif*/, "" /*oif*/))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900155 LOG(ERROR) << "Failed to set up jump rule from filter OUTPUT to "
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900156 << kDropGuestIpv4PrefixChain;
Hugo Benichibf811c62020-09-07 17:30:45 +0900157 for (const auto& oif : kPhysicalIfnamePrefixes) {
158 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
159 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
160 << kGuestIPv4Subnet << " exiting " << oif;
161 }
162
Hugo Benichi561fae42021-01-22 15:28:40 +0900163 // Set static SNAT rules for any IPv4 traffic originated from a guest (ARC,
164 // Crostini, ...) or a connected namespace.
165 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
166 // need to be explicitly dropped as SNAT cannot be applied to them.
Hugo Benichi7a066242021-04-07 23:47:32 +0900167 std::string snatMark =
168 kFwmarkLegacySNAT.ToString() + "/" + kFwmarkLegacySNAT.ToString();
Hugo Benichi561fae42021-01-22 15:28:40 +0900169 if (process_runner_->iptables(
Hugo Benichi7a066242021-04-07 23:47:32 +0900170 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", snatMark, "-m",
Hugo Benichi561fae42021-01-22 15:28:40 +0900171 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0)
172 LOG(ERROR) << "Failed to install SNAT mark rules.";
173 if (process_runner_->iptables(
Hugo Benichi7a066242021-04-07 23:47:32 +0900174 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", snatMark, "-j",
Hugo Benichi561fae42021-01-22 15:28:40 +0900175 "MASQUERADE", "-w"}) != 0)
176 LOG(ERROR) << "Failed to install SNAT mark rules.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900177
Hugo Benichi2a940542020-10-26 18:50:49 +0900178 // Applies the routing tag saved in conntrack for any established connection
179 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900180 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
181 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900182 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
183
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900184 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
185 // tag and tagging the local traffic that should be routed through a VPN.
Hugo Benichif0f55562021-04-02 15:25:02 +0900186 if (!AddChain(IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900187 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
188 << " mangle chain";
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900189 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "OUTPUT",
190 kApplyLocalSourceMarkChain, "" /*iif*/, "" /*oif*/))
191
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900192 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
193 << " to mangle OUTPUT";
194 // Create rules for tagging local sources with the source tag and the vpn
195 // policy tag.
196 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900197 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900198 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
199 << " in " << kApplyLocalSourceMarkChain;
200 }
201 // Finally add a catch-all rule for tagging any remaining local sources with
202 // the SYSTEM source tag
203 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
204 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
205
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900206 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
207 // traffic that should be routed through a VPN.
Hugo Benichif0f55562021-04-02 15:25:02 +0900208 if (!AddChain(IpFamily::Dual, "mangle", kApplyVpnMarkChain))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900209 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900210 // All local outgoing traffic eligible to VPN routing should traverse the VPN
211 // marking chain.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900212 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", kFwmarkRouteOnVpn,
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900213 kFwmarkVpnMask))
214 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
Hugo Benichi155de002021-01-19 16:45:46 +0900215
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900216 // b/178331695 Sets up a nat chain used in OUTPUT for redirecting DNS queries
217 // of system services. When a VPN is connected, a query routed through a
218 // physical network is redirected to the primary nameserver of that network.
Hugo Benichif0f55562021-04-02 15:25:02 +0900219 if (!AddChain(IpFamily::IPv4, "nat", kRedirectDnsChain))
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900220 LOG(ERROR) << "Failed to set up " << kRedirectDnsChain << " nat chain";
221
Hugo Benichi52a64992021-01-28 17:47:33 +0900222 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
223 // incorrectly cause neighbor discovery icmpv6 packets to be dropped. Add
224 // these rules to bypass connmark rule for those packets.
225 for (const auto& type : kNeighborDiscoveryTypes) {
226 if (!ModifyIptables(IpFamily::IPv6, "mangle",
227 {"-I", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
228 "-j", "ACCEPT", "-w"}))
229 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
230 << " packets in OUTPUT";
Hugo Benichi52a64992021-01-28 17:47:33 +0900231 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900232}
233
234void Datapath::Stop() {
Hugo Benichibf811c62020-09-07 17:30:45 +0900235 // Restore original local port range.
236 // TODO(garrick): The original history behind this tweak is gone. Some
237 // investigation is needed to see if it is still applicable.
238 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
239 "32768 61000") != 0)
240 LOG(ERROR) << "Failed to restore local port range";
241
242 // Disable packet forwarding
243 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
244 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
245
246 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
247 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900248
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900249 ResetIptables();
250}
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900251
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900252void Datapath::ResetIptables() {
253 // If it exists, remove jump rules from a built-in chain to a custom routing
254 // or tagging chain.
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900255 ModifyJumpRule(IpFamily::IPv4, "filter", "-D", "OUTPUT",
256 kDropGuestIpv4PrefixChain, "" /*iif*/, "" /*oif*/,
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900257 false /*log_failures*/);
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900258
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900259 // Flush chains used for routing and fwmark tagging. Also delete additional
260 // chains made by patchpanel. Chains used by permission broker (nat
261 // PREROUTING, filter INPUT) and chains used for traffic counters (mangle
262 // {rx,tx}_{<iface>, vpn}) are not flushed.
263 static struct {
264 IpFamily family;
265 std::string table;
266 std::string chain;
267 bool should_delete;
268 } resetOps[] = {
269 {IpFamily::Dual, "filter", "FORWARD", false},
270 {IpFamily::Dual, "mangle", "FORWARD", false},
271 {IpFamily::Dual, "mangle", "INPUT", false},
272 {IpFamily::Dual, "mangle", "OUTPUT", false},
273 {IpFamily::Dual, "mangle", "POSTROUTING", false},
274 {IpFamily::Dual, "mangle", "PREROUTING", false},
275 {IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain, true},
276 {IpFamily::Dual, "mangle", kApplyVpnMarkChain, true},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900277 {IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain, true},
278 {IpFamily::IPv4, "nat", kRedirectDnsChain, true},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900279 {IpFamily::IPv4, "nat", "POSTROUTING", false},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900280 {IpFamily::IPv4, "nat", "OUTPUT", false},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900281 };
282 for (const auto& op : resetOps) {
283 // Chains to delete are custom chains and will not exist the first time
284 // patchpanel starts after boot. Skip flushing and delete these chains if
285 // they do not exist to avoid logging spurious error messages.
286 if (op.should_delete && !ModifyChain(op.family, op.table, "-L", op.chain,
287 false /*log_failures*/))
288 continue;
Hugo Benichi155de002021-01-19 16:45:46 +0900289
Hugo Benichif0f55562021-04-02 15:25:02 +0900290 if (!FlushChain(op.family, op.table, op.chain))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900291 LOG(ERROR) << "Failed to flush " << op.chain << " chain in table "
292 << op.table;
Hugo Benichi2a940542020-10-26 18:50:49 +0900293
Hugo Benichif0f55562021-04-02 15:25:02 +0900294 if (op.should_delete && !RemoveChain(op.family, op.table, op.chain))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900295 LOG(ERROR) << "Failed to delete " << op.chain << " chain in table "
296 << op.table;
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900297 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900298}
299
Hugo Benichi33860d72020-07-09 16:34:01 +0900300bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
301 // Try first to delete any netns with name |netns_name| in case patchpanel
302 // did not exit cleanly.
303 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
304 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
305 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
306}
307
308bool Datapath::NetnsDeleteName(const std::string& netns_name) {
309 return process_runner_->ip_netns_delete(netns_name) == 0;
310}
311
Garrick Evans8a949dc2019-07-18 16:17:53 +0900312bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900313 uint32_t ipv4_addr,
314 uint32_t ipv4_prefix_len) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900315 if (!Ioctl(ioctl_, SIOCBRADDBR, ifname.c_str())) {
316 LOG(ERROR) << "Failed to create bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900317 return false;
318 }
319
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900320 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900321 if (process_runner_->ip(
322 "addr", "add",
323 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
324 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
325 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900326 RemoveBridge(ifname);
327 return false;
328 }
329
330 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900331 RemoveBridge(ifname);
332 return false;
333 }
334
Garrick Evans8a949dc2019-07-18 16:17:53 +0900335 return true;
336}
337
338void Datapath::RemoveBridge(const std::string& ifname) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900339 process_runner_->ip("link", "set", {ifname, "down"});
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900340 if (!Ioctl(ioctl_, SIOCBRDELBR, ifname.c_str()))
341 LOG(ERROR) << "Failed to destroy bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900342}
343
Garrick Evans621ed262019-11-13 12:28:43 +0900344bool Datapath::AddToBridge(const std::string& br_ifname,
345 const std::string& ifname) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900346 struct ifreq ifr;
347 memset(&ifr, 0, sizeof(ifr));
348 strncpy(ifr.ifr_name, br_ifname.c_str(), sizeof(ifr.ifr_name));
349 ifr.ifr_ifindex = FindIfIndex(ifname);
350
351 if (!Ioctl(ioctl_, SIOCBRADDIF, reinterpret_cast<const char*>(&ifr))) {
352 LOG(ERROR) << "Failed to add " << ifname << " to bridge " << br_ifname;
353 return false;
354 }
355
356 return true;
Garrick Evans621ed262019-11-13 12:28:43 +0900357}
358
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900359std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900360 const MacAddress* mac_addr,
361 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900362 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900363 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
364 if (!dev.is_valid()) {
365 PLOG(ERROR) << "Failed to open " << kTunDev;
366 return "";
367 }
368
369 struct ifreq ifr;
370 memset(&ifr, 0, sizeof(ifr));
371 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
372 sizeof(ifr.ifr_name));
373 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
374
375 // If a template was given as the name, ifr_name will be updated with the
376 // actual interface name.
377 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900378 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900379 return "";
380 }
381 const char* ifname = ifr.ifr_name;
382
383 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900384 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900385 return "";
386 }
387
Garrick Evans4f9f5572019-11-26 10:25:16 +0900388 if (!user.empty()) {
389 uid_t uid = -1;
390 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
391 PLOG(ERROR) << "Unable to look up UID for " << user;
392 RemoveTAP(ifname);
393 return "";
394 }
395 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
396 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
397 << ifname;
398 RemoveTAP(ifname);
399 return "";
400 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900401 }
402
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900403 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900404 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
405 if (!sock.is_valid()) {
406 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900407 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900408 RemoveTAP(ifname);
409 return "";
410 }
411
Garrick Evans621ed262019-11-13 12:28:43 +0900412 if (ipv4_addr) {
413 struct sockaddr_in* addr =
414 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
415 addr->sin_family = AF_INET;
416 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
417 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
418 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
419 << " {" << ipv4_addr->ToCidrString() << "}";
420 RemoveTAP(ifname);
421 return "";
422 }
423
424 struct sockaddr_in* netmask =
425 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
426 netmask->sin_family = AF_INET;
427 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
428 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
429 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
430 << " {" << ipv4_addr->ToCidrString() << "}";
431 RemoveTAP(ifname);
432 return "";
433 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900434 }
435
Garrick Evans621ed262019-11-13 12:28:43 +0900436 if (mac_addr) {
437 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
438 hwaddr->sa_family = ARPHRD_ETHER;
439 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
440 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
441 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
442 << " {" << MacAddressToString(*mac_addr) << "}";
443 RemoveTAP(ifname);
444 return "";
445 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900446 }
447
448 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900449 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900450 RemoveTAP(ifname);
451 return "";
452 }
453
454 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
455 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900456 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900457 RemoveTAP(ifname);
458 return "";
459 }
460
461 return ifname;
462}
463
464void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900465 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900466}
467
Hugo Benichi33860d72020-07-09 16:34:01 +0900468bool Datapath::ConnectVethPair(pid_t netns_pid,
469 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900470 const std::string& veth_ifname,
471 const std::string& peer_ifname,
472 const MacAddress& remote_mac_addr,
473 uint32_t remote_ipv4_addr,
474 uint32_t remote_ipv4_prefix_len,
475 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900476 // Set up the virtual pair across the current namespace and |netns_name|.
477 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
478 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
479 << peer_ifname;
480 return false;
481 }
482
483 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900484 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900485 ScopedNS ns(netns_pid, ScopedNS::Type::Network);
Hugo Benichi33860d72020-07-09 16:34:01 +0900486 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900487 LOG(ERROR)
488 << "Cannot create virtual link -- invalid container namespace?";
489 return false;
490 }
491
Hugo Benichi76675592020-04-08 14:29:57 +0900492 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
493 remote_ipv4_prefix_len, true /* link up */,
494 remote_multicast_flag)) {
495 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
496 RemoveInterface(peer_ifname);
497 return false;
498 }
499 }
500
Hugo Benichi76675592020-04-08 14:29:57 +0900501 if (!ToggleInterface(veth_ifname, true /*up*/)) {
502 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
503 RemoveInterface(veth_ifname);
504 return false;
505 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900506
Hugo Benichi76675592020-04-08 14:29:57 +0900507 return true;
508}
509
Hugo Benichi33860d72020-07-09 16:34:01 +0900510bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
511 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900512 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900513 return process_runner_->ip("link", "add",
514 {veth_ifname, "type", "veth", "peer", "name",
515 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900516}
Garrick Evans54861622019-07-19 09:05:09 +0900517
Garrick Evans2470caa2020-03-04 14:15:41 +0900518bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
519 const std::string link = up ? "up" : "down";
520 return process_runner_->ip("link", "set", {ifname, link}) == 0;
521}
Garrick Evans54861622019-07-19 09:05:09 +0900522
Garrick Evans2470caa2020-03-04 14:15:41 +0900523bool Datapath::ConfigureInterface(const std::string& ifname,
524 const MacAddress& mac_addr,
525 uint32_t ipv4_addr,
526 uint32_t ipv4_prefix_len,
527 bool up,
528 bool enable_multicast) {
529 const std::string link = up ? "up" : "down";
530 const std::string multicast = enable_multicast ? "on" : "off";
531 return (process_runner_->ip(
532 "addr", "add",
533 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
534 IPv4AddressToString(
535 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
536 "dev", ifname}) == 0) &&
537 (process_runner_->ip("link", "set",
538 {
539 "dev",
540 ifname,
541 link,
542 "addr",
543 MacAddressToString(mac_addr),
544 "multicast",
545 multicast,
546 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900547}
548
549void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900550 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900551}
552
Hugo Benichi321f23b2020-09-25 15:42:05 +0900553bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
554 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900555 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900556 "filter", {"-I", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
557 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900558}
559
Hugo Benichifcf81022020-12-04 11:01:37 +0900560bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900561 // Veth interface configuration and client routing configuration:
562 // - attach a name to the client namespace.
563 // - create veth pair across the current namespace and the client namespace.
564 // - configure IPv4 address on remote veth inside client namespace.
565 // - configure IPv4 address on local veth inside host namespace.
566 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900567 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
568 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
569 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900570 return false;
571 }
572
Hugo Benichifcf81022020-12-04 11:01:37 +0900573 if (!ConnectVethPair(
574 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
575 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
576 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900577 LOG(ERROR) << "Failed to create veth pair for"
578 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900579 << nsinfo.pid;
580 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900581 return false;
582 }
583
Hugo Benichifcf81022020-12-04 11:01:37 +0900584 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
585 nsinfo.peer_subnet->AddressAtOffset(0),
586 nsinfo.peer_subnet->PrefixLength(),
587 true /* link up */, false /* enable_multicast */)) {
588 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
589 RemoveInterface(nsinfo.host_ifname);
590 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900591 return false;
592 }
593
594 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900595 ScopedNS ns(nsinfo.pid, ScopedNS::Type::Network);
Hugo Benichifcf81022020-12-04 11:01:37 +0900596 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
597 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
598 RemoveInterface(nsinfo.host_ifname);
599 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900600 return false;
601 }
602
Hugo Benichifcf81022020-12-04 11:01:37 +0900603 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
604 INADDR_ANY)) {
605 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
606 << " inside namespace pid " << nsinfo.pid;
607 RemoveInterface(nsinfo.host_ifname);
608 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900609 return false;
610 }
611 }
612
613 // Host namespace routing configuration
614 // - ingress: add route to client subnet via |host_ifname|.
615 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
616 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
617 // Note that by default unsolicited ingress traffic is not forwarded to the
618 // client namespace unless the client specifically set port forwarding
619 // through permission_broker DBus APIs.
620 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
621 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900622 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
623 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
624 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900625 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900626 RemoveInterface(nsinfo.host_ifname);
627 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900628 return false;
629 }
630
Hugo Benichi93306e52020-12-04 16:08:00 +0900631 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
632 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
633 nsinfo.route_on_vpn);
Hugo Benichi7c342672020-09-08 09:18:14 +0900634 return true;
635}
636
Hugo Benichifcf81022020-12-04 11:01:37 +0900637void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900638 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
639 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
640 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900641 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900642 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
643 nsinfo.peer_subnet->BaseAddress(),
644 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
645 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900646}
647
Hugo Benichi8d622b52020-08-13 15:24:12 +0900648void Datapath::StartRoutingDevice(const std::string& ext_ifname,
649 const std::string& int_ifname,
650 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900651 TrafficSource source,
652 bool route_on_vpn) {
653 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900654 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900655 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
656 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
657 << "->" << int_ifname;
658
Hugo Benichi954bae62021-04-09 09:12:30 +0900659 if (!ModifyIpForwarding(IpFamily::IPv4, "-A", ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900660 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
661 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900662
Hugo Benichi954bae62021-04-09 09:12:30 +0900663 if (!ModifyIpForwarding(IpFamily::IPv4, "-A", int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900664 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
665 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900666
Hugo Benichid872d3d2021-03-29 10:20:53 +0900667 std::string subchain = "PREROUTING_" + int_ifname;
668 // This can fail if patchpanel did not stopped correctly or failed to cleanup
669 // the chain when |int_ifname| was previously deleted.
670 if (!AddChain(IpFamily::Dual, "mangle", subchain))
671 LOG(ERROR) << "Failed to create mangle chain " << subchain;
672 // Make sure the chain is empty if patchpanel did not cleaned correctly that
673 // chain before.
674 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
675 LOG(ERROR) << "Could not flush " << subchain;
676 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "PREROUTING", subchain,
677 int_ifname, "" /*oif*/))
678 LOG(ERROR) << "Could not add jump rule from mangle PREROUTING to "
679 << subchain;
Hugo Benichi7a066242021-04-07 23:47:32 +0900680 // IPv4 traffic from all downstream devices should be tagged to go through
681 // SNAT.
682 if (!ModifyFwmark(IpFamily::IPv4, subchain, "-A", "", "", 0,
683 kFwmarkLegacySNAT, kFwmarkLegacySNAT))
684 LOG(ERROR) << "Failed to add fwmark SNAT tagging rule for " << int_ifname;
Hugo Benichid872d3d2021-03-29 10:20:53 +0900685 if (!ModifyFwmarkSourceTag(subchain, "-A", source))
686 LOG(ERROR) << "Failed to add fwmark tagging rule for source " << source
687 << " in " << subchain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900688
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900689 if (!ext_ifname.empty()) {
690 // If |ext_ifname| is not null, mark egress traffic with the
691 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900692 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900693 if (ifindex == 0) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900694 LOG(ERROR) << "Failed to retrieve interface index of " << ext_ifname;
Hugo Benichid872d3d2021-03-29 10:20:53 +0900695 return;
Hugo Benichi8c526e92021-03-25 14:59:59 +0900696 }
Hugo Benichid872d3d2021-03-29 10:20:53 +0900697 if (!ModifyFwmarkRoutingTag(subchain, "-A", Fwmark::FromIfIndex(ifindex)))
698 LOG(ERROR) << "Failed to add fwmark routing tag for " << ext_ifname
699 << "<-" << int_ifname << " in " << subchain;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900700 } else {
701 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
702 // PREROUTING to apply any fwmark routing tag saved for the current
703 // connection, and rely on implicit routing to the default logical network
704 // otherwise.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900705 if (!ModifyConnmarkRestore(IpFamily::Dual, subchain, "-A", "" /*iif*/,
Hugo Benichi1af52392020-11-27 18:09:32 +0900706 kFwmarkRoutingMask))
Hugo Benichid872d3d2021-03-29 10:20:53 +0900707 LOG(ERROR) << "Failed to add CONNMARK restore rule in " << subchain;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900708
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900709 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900710 // default network is eligible to be routed through a VPN if |route_on_vpn|
711 // is true.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900712 if (route_on_vpn && !ModifyFwmarkVpnJumpRule(subchain, "-A", {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900713 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900714 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900715}
716
717void Datapath::StopRoutingDevice(const std::string& ext_ifname,
718 const std::string& int_ifname,
719 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900720 TrafficSource source,
721 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900722 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900723 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichi954bae62021-04-09 09:12:30 +0900724 ModifyIpForwarding(IpFamily::IPv4, "-D", ext_ifname, int_ifname);
725 ModifyIpForwarding(IpFamily::IPv4, "-D", int_ifname, ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900726
727 std::string subchain = "PREROUTING_" + int_ifname;
728 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "PREROUTING", subchain,
729 int_ifname, "" /*oif*/);
730 FlushChain(IpFamily::Dual, "mangle", subchain);
731 RemoveChain(IpFamily::Dual, "mangle", subchain);
Hugo Benichi8d622b52020-08-13 15:24:12 +0900732}
733
Garrick Evansf0ab7132019-06-18 14:50:42 +0900734bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
735 const std::string& ipv4_addr) {
736 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900737 if (process_runner_->iptables(
738 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
739 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900740 return false;
741
742 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900743 if (process_runner_->iptables(
744 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
745 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900746 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
747 return false;
748 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900749 if (process_runner_->iptables(
750 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
751 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900752 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
753 return false;
754 }
755
756 return true;
757}
758
759void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
760 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900761 process_runner_->iptables(
762 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
763 "--to-destination", ipv4_addr, "-w"});
764 process_runner_->iptables(
765 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
766 "--to-destination", ipv4_addr, "-w"});
767 process_runner_->iptables(
768 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
769 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900770}
771
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900772bool Datapath::AddRedirectDnsRule(const std::string& ifname,
773 const std::string dns_ipv4_addr) {
774 bool success = true;
775 success &= RemoveRedirectDnsRule(ifname);
776 // Use Insert operation to ensure that the new DNS address is used first.
777 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
778 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
779 physical_dns_addresses_[ifname] = dns_ipv4_addr;
780 return success;
781}
782
783bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
784 const auto it = physical_dns_addresses_.find(ifname);
785 if (it == physical_dns_addresses_.end())
786 return true;
787
788 bool success = true;
789 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
790 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
791 physical_dns_addresses_.erase(it);
792 return success;
793}
794
795bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
796 const std::string& protocol,
797 const std::string& ifname,
798 const std::string& dns_ipv4_addr) {
799 std::vector<std::string> args = {op,
800 kRedirectDnsChain,
801 "-p",
802 protocol,
803 "--dport",
804 "53",
805 "-o",
806 ifname,
807 "-j",
808 "DNAT",
809 "--to-destination",
810 dns_ipv4_addr,
811 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900812 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900813}
814
815bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
816 std::vector<std::string> args = {
817 op,
818 "OUTPUT",
819 "-m",
820 "mark",
821 "!",
822 "--mark",
823 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
824 "-j",
825 kRedirectDnsChain,
826 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900827 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900828}
829
Garrick Evans664a82f2019-12-17 12:18:05 +0900830bool Datapath::MaskInterfaceFlags(const std::string& ifname,
831 uint16_t on,
832 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900833 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
834 if (!sock.is_valid()) {
835 PLOG(ERROR) << "Failed to create control socket";
836 return false;
837 }
838 ifreq ifr;
839 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
840 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
841 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
842 return false;
843 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900844 ifr.ifr_flags |= on;
845 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900846 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900847 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
848 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900849 return false;
850 }
851 return true;
852}
853
Garrick Evans260ff302019-07-25 11:22:50 +0900854bool Datapath::AddIPv6HostRoute(const std::string& ifname,
855 const std::string& ipv6_addr,
856 int ipv6_prefix_len) {
857 std::string ipv6_addr_cidr =
858 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
859
Garrick Evans8e8e3472020-01-23 14:03:50 +0900860 return process_runner_->ip6("route", "replace",
861 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900862}
863
864void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
865 const std::string& ipv6_addr,
866 int ipv6_prefix_len) {
867 std::string ipv6_addr_cidr =
868 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
869
Garrick Evans8e8e3472020-01-23 14:03:50 +0900870 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900871}
872
Taoyu Lia0727dc2020-09-24 19:54:59 +0900873bool Datapath::AddIPv6Address(const std::string& ifname,
874 const std::string& ipv6_addr) {
875 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900876}
877
Taoyu Lia0727dc2020-09-24 19:54:59 +0900878void Datapath::RemoveIPv6Address(const std::string& ifname,
879 const std::string& ipv6_addr) {
880 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900881}
882
Hugo Benichi76be34a2020-08-26 22:35:54 +0900883void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900884 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +0900885 if (ifindex == 0) {
886 // Can happen if the interface has already been removed (b/183679000).
887 LOG(ERROR) << "Failed to set up connection pinning on " << ext_ifname;
888 return;
889 }
890
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900891 std::string subchain = "POSTROUTING_" + ext_ifname;
892 // This can fail if patchpanel did not stopped correctly or failed to cleanup
893 // the chain when |ext_ifname| was previously deleted.
894 if (!AddChain(IpFamily::Dual, "mangle", subchain))
895 LOG(ERROR) << "Failed to create mangle chain " << subchain;
896 // Make sure the chain is empty if patchpanel did not cleaned correctly that
897 // chain before.
898 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
899 LOG(ERROR) << "Could not flush " << subchain;
900 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "POSTROUTING", subchain,
901 "" /*iif*/, ext_ifname))
902 LOG(ERROR) << "Could not add jump rule from mangle POSTROUTING to "
903 << subchain;
904
Hugo Benichi8c526e92021-03-25 14:59:59 +0900905 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
906 LOG(INFO) << "Start connection pinning on " << ext_ifname
907 << " fwmark=" << routing_mark.ToString();
Hugo Benichi1af52392020-11-27 18:09:32 +0900908 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900909 if (!ModifyConnmarkSet(IpFamily::Dual, subchain, "-A", routing_mark,
910 kFwmarkRoutingMask))
Hugo Benichi76be34a2020-08-26 22:35:54 +0900911 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900912 // Save in CONNMARK the source tag for egress traffic of this connection.
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900913 if (!ModifyConnmarkSave(IpFamily::Dual, subchain, "-A",
Hugo Benichi1af52392020-11-27 18:09:32 +0900914 kFwmarkAllSourcesMask))
915 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
916 "source tag on "
917 << ext_ifname;
918 // Restore from CONNMARK the source tag for ingress traffic of this connection
919 // (returned traffic).
920 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
921 kFwmarkAllSourcesMask))
922 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
923 "traffic received on "
924 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900925}
926
927void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900928 std::string subchain = "POSTROUTING_" + ext_ifname;
929 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "POSTROUTING", subchain,
930 "" /*iif*/, ext_ifname);
931 FlushChain(IpFamily::Dual, "mangle", subchain);
932 RemoveChain(IpFamily::Dual, "mangle", subchain);
933 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
934 kFwmarkAllSourcesMask))
935 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
936 "traffic received on "
937 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900938}
939
Hugo Benichi2a940542020-10-26 18:50:49 +0900940void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900941 int ifindex = FindIfIndex(vpn_ifname);
942 if (ifindex == 0) {
943 // Can happen if the interface has already been removed (b/183679000).
944 LOG(ERROR) << "Failed to start VPN routing on " << vpn_ifname;
945 return;
946 }
947
948 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
949 LOG(INFO) << "Start VPN routing on " << vpn_ifname
950 << " fwmark=" << routing_mark.ToString();
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900951 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-A", "POSTROUTING", "MASQUERADE",
952 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +0900953 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900954 StartConnectionPinning(vpn_ifname);
Hugo Benichi3540c7f2021-03-29 13:14:42 +0900955
956 // Any traffic that already has a routing tag applied is accepted.
957 if (!ModifyIptables(
958 IpFamily::Dual, "mangle",
959 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
960 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
961 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
962 "connections";
963 // Otherwise, any new traffic from a new connection gets marked with the
964 // VPN routing tag.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900965 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", routing_mark))
Hugo Benichi2a940542020-10-26 18:50:49 +0900966 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichi3540c7f2021-03-29 13:14:42 +0900967
968 // When the VPN client runs on the host, also route arcbr0 to that VPN so
969 // that ARC can access the VPN network through arc0.
Hugo Benichibfc49112020-12-14 12:54:44 +0900970 if (vpn_ifname != kArcBridge)
971 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
972 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900973 if (!ModifyRedirectDnsJumpRule("-A"))
974 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900975}
976
977void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi3540c7f2021-03-29 13:14:42 +0900978 LOG(INFO) << "Stop VPN routing on " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +0900979 if (vpn_ifname != kArcBridge)
980 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
981 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi3540c7f2021-03-29 13:14:42 +0900982 if (!FlushChain(IpFamily::Dual, "mangle", kApplyVpnMarkChain))
983 LOG(ERROR) << "Could not flush " << kApplyVpnMarkChain;
984
Hugo Benichi2a940542020-10-26 18:50:49 +0900985 StopConnectionPinning(vpn_ifname);
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900986 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-D", "POSTROUTING", "MASQUERADE",
987 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +0900988 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900989 if (!ModifyRedirectDnsJumpRule("-D"))
990 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900991}
992
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900993bool Datapath::ModifyConnmarkSet(IpFamily family,
994 const std::string& chain,
995 const std::string& op,
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900996 Fwmark mark,
997 Fwmark mask) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900998 return ModifyIptables(family, "mangle",
999 {op, chain, "-j", "CONNMARK", "--set-mark",
1000 mark.ToString() + "/" + mask.ToString(), "-w"});
Hugo Benichi76be34a2020-08-26 22:35:54 +09001001}
1002
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001003bool Datapath::ModifyConnmarkRestore(IpFamily family,
1004 const std::string& chain,
1005 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001006 const std::string& iif,
1007 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001008 std::vector<std::string> args = {op, chain};
1009 if (!iif.empty()) {
1010 args.push_back("-i");
1011 args.push_back(iif);
1012 }
1013 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001014 mask.ToString(), "-w"});
1015 return ModifyIptables(family, "mangle", args);
1016}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001017
Hugo Benichi1af52392020-11-27 18:09:32 +09001018bool Datapath::ModifyConnmarkSave(IpFamily family,
1019 const std::string& chain,
1020 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001021 Fwmark mask) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +09001022 std::vector<std::string> args = {
1023 op, chain, "-j", "CONNMARK", "--save-mark",
1024 "--mask", mask.ToString(), "-w"};
Hugo Benichi58f264a2020-10-16 18:16:05 +09001025 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001026}
1027
Hugo Benichi2a940542020-10-26 18:50:49 +09001028bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1029 const std::string& op,
Hugo Benichid872d3d2021-03-29 10:20:53 +09001030 Fwmark routing_mark) {
1031 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*int_ifname*/,
1032 "" /*uid_name*/, 0 /*classid*/, routing_mark,
1033 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001034}
1035
Hugo Benichid872d3d2021-03-29 10:20:53 +09001036bool Datapath::ModifyFwmarkSourceTag(const std::string& chain,
1037 const std::string& op,
Hugo Benichi9be19b12020-08-14 15:33:40 +09001038 TrafficSource source) {
Hugo Benichid872d3d2021-03-29 10:20:53 +09001039 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*iif*/, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001040 0 /*classid*/, Fwmark::FromSource(source),
1041 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001042}
1043
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001044bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1045 TrafficSource source) {
1046 std::vector<std::string> args = {"-A",
1047 kApplyLocalSourceMarkChain,
1048 "-m",
1049 "mark",
1050 "--mark",
1051 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1052 "-j",
1053 "MARK",
1054 "--set-mark",
1055 Fwmark::FromSource(source).ToString() + "/" +
1056 kFwmarkAllSourcesMask.ToString(),
1057 "-w"};
1058 return ModifyIptables(IpFamily::Dual, "mangle", args);
1059}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001060
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001061bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1062 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001063 if (std::string(source.uid_name).empty() && source.classid == 0)
1064 return false;
1065
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001066 Fwmark mark = Fwmark::FromSource(source.source_type);
1067 if (source.is_on_vpn)
1068 mark = mark | kFwmarkRouteOnVpn;
1069
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001070 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1071 "" /*iif*/, source.uid_name, source.classid, mark,
1072 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001073}
1074
1075bool Datapath::ModifyFwmark(IpFamily family,
1076 const std::string& chain,
1077 const std::string& op,
1078 const std::string& iif,
1079 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001080 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001081 Fwmark mark,
1082 Fwmark mask,
1083 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001084 std::vector<std::string> args = {op, chain};
1085 if (!iif.empty()) {
1086 args.push_back("-i");
1087 args.push_back(iif);
1088 }
1089 if (!uid_name.empty()) {
1090 args.push_back("-m");
1091 args.push_back("owner");
1092 args.push_back("--uid-owner");
1093 args.push_back(uid_name);
1094 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001095 if (classid != 0) {
1096 args.push_back("-m");
1097 args.push_back("cgroup");
1098 args.push_back("--cgroup");
1099 args.push_back(base::StringPrintf("0x%08x", classid));
1100 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001101 args.push_back("-j");
1102 args.push_back("MARK");
1103 args.push_back("--set-mark");
1104 args.push_back(mark.ToString() + "/" + mask.ToString());
1105 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001106
Hugo Benichi58f264a2020-10-16 18:16:05 +09001107 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001108}
1109
Hugo Benichid82d8832020-08-14 10:05:03 +09001110bool Datapath::ModifyIpForwarding(IpFamily family,
1111 const std::string& op,
1112 const std::string& iif,
1113 const std::string& oif,
1114 bool log_failures) {
1115 if (iif.empty() && oif.empty()) {
1116 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1117 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001118 return false;
1119 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001120 return ModifyJumpRule(family, "filter", op, "FORWARD", "ACCEPT", iif, oif,
1121 log_failures);
1122}
Garrick Evans260ff302019-07-25 11:22:50 +09001123
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001124bool Datapath::ModifyJumpRule(IpFamily family,
1125 const std::string& table,
1126 const std::string& op,
1127 const std::string& chain,
1128 const std::string& target,
1129 const std::string& iif,
1130 const std::string& oif,
1131 bool log_failures) {
1132 std::vector<std::string> args = {op, chain};
Hugo Benichid82d8832020-08-14 10:05:03 +09001133 if (!iif.empty()) {
1134 args.push_back("-i");
1135 args.push_back(iif);
1136 }
1137 if (!oif.empty()) {
1138 args.push_back("-o");
1139 args.push_back(oif);
1140 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001141 args.insert(args.end(), {"-j", target, "-w"});
1142 return ModifyIptables(family, table, args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001143}
1144
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001145bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1146 const std::string& op,
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001147 Fwmark mark,
1148 Fwmark mask) {
1149 std::vector<std::string> args = {op, chain};
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001150 if (mark.Value() != 0 && mask.Value() != 0) {
1151 args.push_back("-m");
1152 args.push_back("mark");
1153 args.push_back("--mark");
1154 args.push_back(mark.ToString() + "/" + mask.ToString());
1155 }
1156 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1157 return ModifyIptables(IpFamily::Dual, "mangle", args);
1158}
1159
Hugo Benichif0f55562021-04-02 15:25:02 +09001160bool Datapath::AddChain(IpFamily family,
1161 const std::string& table,
1162 const std::string& name) {
1163 DCHECK(name.size() <= kIptablesMaxChainLength);
1164 return ModifyChain(family, table, "-N", name);
1165}
1166
1167bool Datapath::RemoveChain(IpFamily family,
1168 const std::string& table,
1169 const std::string& name) {
1170 return ModifyChain(family, table, "-X", name);
1171}
1172
1173bool Datapath::FlushChain(IpFamily family,
1174 const std::string& table,
1175 const std::string& name) {
1176 return ModifyChain(family, table, "-F", name);
1177}
1178
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001179bool Datapath::ModifyChain(IpFamily family,
1180 const std::string& table,
1181 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001182 const std::string& chain,
1183 bool log_failures) {
1184 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001185}
1186
1187bool Datapath::ModifyIptables(IpFamily family,
1188 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001189 const std::vector<std::string>& argv,
1190 bool log_failures) {
1191 switch (family) {
1192 case IPv4:
1193 case IPv6:
1194 case Dual:
1195 break;
1196 default:
1197 LOG(ERROR) << "Could not execute iptables command " << table
1198 << base::JoinString(argv, " ") << ": incorrect IP family "
1199 << family;
1200 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001201 }
1202
1203 bool success = true;
1204 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001205 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001206 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001207 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001208 return success;
1209}
1210
Hugo Benichid82d8832020-08-14 10:05:03 +09001211bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1212 const std::string& ifname2) {
1213 // Only start Ipv6 forwarding if -C returns false and it had not been
1214 // started yet.
1215 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1216 false /*log_failures*/) &&
Hugo Benichi954bae62021-04-09 09:12:30 +09001217 !ModifyIpForwarding(IpFamily::IPv6, "-A", ifname1, ifname2)) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001218 return false;
1219 }
1220
1221 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1222 false /*log_failures*/) &&
Hugo Benichi954bae62021-04-09 09:12:30 +09001223 !ModifyIpForwarding(IpFamily::IPv6, "-A", ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001224 RemoveIPv6Forwarding(ifname1, ifname2);
1225 return false;
1226 }
1227
1228 return true;
1229}
1230
1231void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1232 const std::string& ifname2) {
Hugo Benichi954bae62021-04-09 09:12:30 +09001233 ModifyIpForwarding(IpFamily::IPv6, "-D", ifname1, ifname2);
1234 ModifyIpForwarding(IpFamily::IPv6, "-D", ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001235}
1236
Garrick Evans3d97a392020-02-21 15:24:37 +09001237bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1238 uint32_t addr,
1239 uint32_t netmask) {
1240 struct rtentry route;
1241 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001242 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1243 SetSockaddrIn(&route.rt_dst, addr & netmask);
1244 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001245 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001246 return ModifyRtentry(SIOCADDRT, &route);
1247}
Garrick Evans3d97a392020-02-21 15:24:37 +09001248
Hugo Benichie8758b52020-04-03 14:49:01 +09001249bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1250 uint32_t addr,
1251 uint32_t netmask) {
1252 struct rtentry route;
1253 memset(&route, 0, sizeof(route));
1254 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1255 SetSockaddrIn(&route.rt_dst, addr & netmask);
1256 SetSockaddrIn(&route.rt_genmask, netmask);
1257 route.rt_flags = RTF_UP | RTF_GATEWAY;
1258 return ModifyRtentry(SIOCDELRT, &route);
1259}
1260
1261bool Datapath::AddIPv4Route(const std::string& ifname,
1262 uint32_t addr,
1263 uint32_t netmask) {
1264 struct rtentry route;
1265 memset(&route, 0, sizeof(route));
1266 SetSockaddrIn(&route.rt_dst, addr & netmask);
1267 SetSockaddrIn(&route.rt_genmask, netmask);
1268 char rt_dev[IFNAMSIZ];
1269 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1270 rt_dev[IFNAMSIZ - 1] = '\0';
1271 route.rt_dev = rt_dev;
1272 route.rt_flags = RTF_UP | RTF_GATEWAY;
1273 return ModifyRtentry(SIOCADDRT, &route);
1274}
1275
1276bool Datapath::DeleteIPv4Route(const std::string& ifname,
1277 uint32_t addr,
1278 uint32_t netmask) {
1279 struct rtentry route;
1280 memset(&route, 0, sizeof(route));
1281 SetSockaddrIn(&route.rt_dst, addr & netmask);
1282 SetSockaddrIn(&route.rt_genmask, netmask);
1283 char rt_dev[IFNAMSIZ];
1284 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1285 rt_dev[IFNAMSIZ - 1] = '\0';
1286 route.rt_dev = rt_dev;
1287 route.rt_flags = RTF_UP | RTF_GATEWAY;
1288 return ModifyRtentry(SIOCDELRT, &route);
1289}
1290
Taoyu Lia0727dc2020-09-24 19:54:59 +09001291bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001292 DCHECK(route);
1293 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001294 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001295 return false;
1296 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001297 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1298 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001299 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001300 return false;
1301 }
1302 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1303 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001304 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001305 return false;
1306 }
1307 return true;
1308}
1309
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001310bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1311 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1312 kArcAddr, kAdbServerPort, ifname,
1313 kLocalhostAddr, kAdbProxyTcpListenPort);
1314}
1315
1316void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1317 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1318 kArcAddr, kAdbServerPort, ifname,
1319 kLocalhostAddr, kAdbProxyTcpListenPort);
1320}
1321
1322bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1323 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1324 kAdbProxyTcpListenPort, ifname);
1325}
1326
1327void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1328 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1329 kAdbProxyTcpListenPort, ifname);
1330}
1331
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001332void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1333 if_nametoindex_[ifname] = ifindex;
1334}
1335
1336int Datapath::FindIfIndex(const std::string& ifname) {
1337 uint32_t ifindex = if_nametoindex(ifname.c_str());
1338 if (ifindex > 0) {
1339 if_nametoindex_[ifname] = ifindex;
1340 return ifindex;
1341 }
1342
1343 const auto it = if_nametoindex_.find(ifname);
1344 if (it != if_nametoindex_.end())
1345 return it->second;
1346
1347 return 0;
1348}
1349
Hugo Benichifcf81022020-12-04 11:01:37 +09001350std::ostream& operator<<(std::ostream& stream,
1351 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001352 stream << "{ pid: " << nsinfo.pid
1353 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001354 if (!nsinfo.outbound_ifname.empty()) {
1355 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1356 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001357 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1358 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001359 << ", peer_ifname: " << nsinfo.peer_ifname
1360 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1361 return stream;
1362}
1363
Garrick Evans3388a032020-03-24 11:25:55 +09001364} // namespace patchpanel