blob: 18f18e85502615d4f6a271a3b18bfb3a3b72aeb9 [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
560bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
561 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900562 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900563 "filter", {"-D", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
564 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900565}
566
Hugo Benichifcf81022020-12-04 11:01:37 +0900567bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900568 // Veth interface configuration and client routing configuration:
569 // - attach a name to the client namespace.
570 // - create veth pair across the current namespace and the client namespace.
571 // - configure IPv4 address on remote veth inside client namespace.
572 // - configure IPv4 address on local veth inside host namespace.
573 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900574 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
575 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
576 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900577 return false;
578 }
579
Hugo Benichifcf81022020-12-04 11:01:37 +0900580 if (!ConnectVethPair(
581 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
582 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
583 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900584 LOG(ERROR) << "Failed to create veth pair for"
585 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900586 << nsinfo.pid;
587 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900588 return false;
589 }
590
Hugo Benichifcf81022020-12-04 11:01:37 +0900591 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
592 nsinfo.peer_subnet->AddressAtOffset(0),
593 nsinfo.peer_subnet->PrefixLength(),
594 true /* link up */, false /* enable_multicast */)) {
595 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
596 RemoveInterface(nsinfo.host_ifname);
597 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900598 return false;
599 }
600
601 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900602 ScopedNS ns(nsinfo.pid, ScopedNS::Type::Network);
Hugo Benichifcf81022020-12-04 11:01:37 +0900603 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
604 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
605 RemoveInterface(nsinfo.host_ifname);
606 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900607 return false;
608 }
609
Hugo Benichifcf81022020-12-04 11:01:37 +0900610 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
611 INADDR_ANY)) {
612 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
613 << " inside namespace pid " << nsinfo.pid;
614 RemoveInterface(nsinfo.host_ifname);
615 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900616 return false;
617 }
618 }
619
620 // Host namespace routing configuration
621 // - ingress: add route to client subnet via |host_ifname|.
622 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
623 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
624 // Note that by default unsolicited ingress traffic is not forwarded to the
625 // client namespace unless the client specifically set port forwarding
626 // through permission_broker DBus APIs.
627 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
628 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900629 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
630 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
631 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900632 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900633 RemoveInterface(nsinfo.host_ifname);
634 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900635 return false;
636 }
637
Hugo Benichi93306e52020-12-04 16:08:00 +0900638 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
639 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
640 nsinfo.route_on_vpn);
Hugo Benichi7c342672020-09-08 09:18:14 +0900641 return true;
642}
643
Hugo Benichifcf81022020-12-04 11:01:37 +0900644void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900645 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
646 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
647 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900648 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900649 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
650 nsinfo.peer_subnet->BaseAddress(),
651 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
652 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900653}
654
Hugo Benichi8d622b52020-08-13 15:24:12 +0900655void Datapath::StartRoutingDevice(const std::string& ext_ifname,
656 const std::string& int_ifname,
657 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900658 TrafficSource source,
659 bool route_on_vpn) {
660 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900661 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900662 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
663 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
664 << "->" << int_ifname;
665
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900666 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900667 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
668 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900669
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900670 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900671 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
672 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900673
Hugo Benichid872d3d2021-03-29 10:20:53 +0900674 std::string subchain = "PREROUTING_" + int_ifname;
675 // This can fail if patchpanel did not stopped correctly or failed to cleanup
676 // the chain when |int_ifname| was previously deleted.
677 if (!AddChain(IpFamily::Dual, "mangle", subchain))
678 LOG(ERROR) << "Failed to create mangle chain " << subchain;
679 // Make sure the chain is empty if patchpanel did not cleaned correctly that
680 // chain before.
681 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
682 LOG(ERROR) << "Could not flush " << subchain;
683 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "PREROUTING", subchain,
684 int_ifname, "" /*oif*/))
685 LOG(ERROR) << "Could not add jump rule from mangle PREROUTING to "
686 << subchain;
Hugo Benichi7a066242021-04-07 23:47:32 +0900687 // IPv4 traffic from all downstream devices should be tagged to go through
688 // SNAT.
689 if (!ModifyFwmark(IpFamily::IPv4, subchain, "-A", "", "", 0,
690 kFwmarkLegacySNAT, kFwmarkLegacySNAT))
691 LOG(ERROR) << "Failed to add fwmark SNAT tagging rule for " << int_ifname;
Hugo Benichid872d3d2021-03-29 10:20:53 +0900692 if (!ModifyFwmarkSourceTag(subchain, "-A", source))
693 LOG(ERROR) << "Failed to add fwmark tagging rule for source " << source
694 << " in " << subchain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900695
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900696 if (!ext_ifname.empty()) {
697 // If |ext_ifname| is not null, mark egress traffic with the
698 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi8c526e92021-03-25 14:59:59 +0900699 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900700 if (ifindex == 0) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900701 LOG(ERROR) << "Failed to retrieve interface index of " << ext_ifname;
Hugo Benichid872d3d2021-03-29 10:20:53 +0900702 return;
Hugo Benichi8c526e92021-03-25 14:59:59 +0900703 }
Hugo Benichid872d3d2021-03-29 10:20:53 +0900704 if (!ModifyFwmarkRoutingTag(subchain, "-A", Fwmark::FromIfIndex(ifindex)))
705 LOG(ERROR) << "Failed to add fwmark routing tag for " << ext_ifname
706 << "<-" << int_ifname << " in " << subchain;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900707 } else {
708 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
709 // PREROUTING to apply any fwmark routing tag saved for the current
710 // connection, and rely on implicit routing to the default logical network
711 // otherwise.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900712 if (!ModifyConnmarkRestore(IpFamily::Dual, subchain, "-A", "" /*iif*/,
Hugo Benichi1af52392020-11-27 18:09:32 +0900713 kFwmarkRoutingMask))
Hugo Benichid872d3d2021-03-29 10:20:53 +0900714 LOG(ERROR) << "Failed to add CONNMARK restore rule in " << subchain;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900715
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900716 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900717 // default network is eligible to be routed through a VPN if |route_on_vpn|
718 // is true.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900719 if (route_on_vpn && !ModifyFwmarkVpnJumpRule(subchain, "-A", {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900720 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900721 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900722}
723
724void Datapath::StopRoutingDevice(const std::string& ext_ifname,
725 const std::string& int_ifname,
726 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900727 TrafficSource source,
728 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900729 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900730 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900731 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
732 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichid872d3d2021-03-29 10:20:53 +0900733
734 std::string subchain = "PREROUTING_" + int_ifname;
735 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "PREROUTING", subchain,
736 int_ifname, "" /*oif*/);
737 FlushChain(IpFamily::Dual, "mangle", subchain);
738 RemoveChain(IpFamily::Dual, "mangle", subchain);
Hugo Benichi8d622b52020-08-13 15:24:12 +0900739}
740
Garrick Evansf0ab7132019-06-18 14:50:42 +0900741bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
742 const std::string& ipv4_addr) {
743 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900744 if (process_runner_->iptables(
745 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
746 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900747 return false;
748
749 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900750 if (process_runner_->iptables(
751 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
752 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900753 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
754 return false;
755 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900756 if (process_runner_->iptables(
757 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
758 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900759 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
760 return false;
761 }
762
763 return true;
764}
765
766void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
767 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900768 process_runner_->iptables(
769 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
770 "--to-destination", ipv4_addr, "-w"});
771 process_runner_->iptables(
772 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
773 "--to-destination", ipv4_addr, "-w"});
774 process_runner_->iptables(
775 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
776 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900777}
778
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900779bool Datapath::AddRedirectDnsRule(const std::string& ifname,
780 const std::string dns_ipv4_addr) {
781 bool success = true;
782 success &= RemoveRedirectDnsRule(ifname);
783 // Use Insert operation to ensure that the new DNS address is used first.
784 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
785 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
786 physical_dns_addresses_[ifname] = dns_ipv4_addr;
787 return success;
788}
789
790bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
791 const auto it = physical_dns_addresses_.find(ifname);
792 if (it == physical_dns_addresses_.end())
793 return true;
794
795 bool success = true;
796 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
797 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
798 physical_dns_addresses_.erase(it);
799 return success;
800}
801
802bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
803 const std::string& protocol,
804 const std::string& ifname,
805 const std::string& dns_ipv4_addr) {
806 std::vector<std::string> args = {op,
807 kRedirectDnsChain,
808 "-p",
809 protocol,
810 "--dport",
811 "53",
812 "-o",
813 ifname,
814 "-j",
815 "DNAT",
816 "--to-destination",
817 dns_ipv4_addr,
818 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900819 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900820}
821
822bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
823 std::vector<std::string> args = {
824 op,
825 "OUTPUT",
826 "-m",
827 "mark",
828 "!",
829 "--mark",
830 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
831 "-j",
832 kRedirectDnsChain,
833 "-w"};
Hugo Benichie8b04672021-03-23 15:27:21 +0900834 return process_runner_->iptables("nat", args) == 0;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900835}
836
Garrick Evans664a82f2019-12-17 12:18:05 +0900837bool Datapath::MaskInterfaceFlags(const std::string& ifname,
838 uint16_t on,
839 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900840 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
841 if (!sock.is_valid()) {
842 PLOG(ERROR) << "Failed to create control socket";
843 return false;
844 }
845 ifreq ifr;
846 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
847 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
848 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
849 return false;
850 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900851 ifr.ifr_flags |= on;
852 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900853 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900854 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
855 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900856 return false;
857 }
858 return true;
859}
860
Garrick Evans260ff302019-07-25 11:22:50 +0900861bool Datapath::AddIPv6HostRoute(const std::string& ifname,
862 const std::string& ipv6_addr,
863 int ipv6_prefix_len) {
864 std::string ipv6_addr_cidr =
865 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
866
Garrick Evans8e8e3472020-01-23 14:03:50 +0900867 return process_runner_->ip6("route", "replace",
868 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900869}
870
871void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
872 const std::string& ipv6_addr,
873 int ipv6_prefix_len) {
874 std::string ipv6_addr_cidr =
875 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
876
Garrick Evans8e8e3472020-01-23 14:03:50 +0900877 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900878}
879
Taoyu Lia0727dc2020-09-24 19:54:59 +0900880bool Datapath::AddIPv6Address(const std::string& ifname,
881 const std::string& ipv6_addr) {
882 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900883}
884
Taoyu Lia0727dc2020-09-24 19:54:59 +0900885void Datapath::RemoveIPv6Address(const std::string& ifname,
886 const std::string& ipv6_addr) {
887 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900888}
889
Hugo Benichi76be34a2020-08-26 22:35:54 +0900890void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900891 int ifindex = FindIfIndex(ext_ifname);
Hugo Benichi8c526e92021-03-25 14:59:59 +0900892 if (ifindex == 0) {
893 // Can happen if the interface has already been removed (b/183679000).
894 LOG(ERROR) << "Failed to set up connection pinning on " << ext_ifname;
895 return;
896 }
897
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900898 std::string subchain = "POSTROUTING_" + ext_ifname;
899 // This can fail if patchpanel did not stopped correctly or failed to cleanup
900 // the chain when |ext_ifname| was previously deleted.
901 if (!AddChain(IpFamily::Dual, "mangle", subchain))
902 LOG(ERROR) << "Failed to create mangle chain " << subchain;
903 // Make sure the chain is empty if patchpanel did not cleaned correctly that
904 // chain before.
905 if (!FlushChain(IpFamily::Dual, "mangle", subchain))
906 LOG(ERROR) << "Could not flush " << subchain;
907 if (!ModifyJumpRule(IpFamily::Dual, "mangle", "-A", "POSTROUTING", subchain,
908 "" /*iif*/, ext_ifname))
909 LOG(ERROR) << "Could not add jump rule from mangle POSTROUTING to "
910 << subchain;
911
Hugo Benichi8c526e92021-03-25 14:59:59 +0900912 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
913 LOG(INFO) << "Start connection pinning on " << ext_ifname
914 << " fwmark=" << routing_mark.ToString();
Hugo Benichi1af52392020-11-27 18:09:32 +0900915 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900916 if (!ModifyConnmarkSet(IpFamily::Dual, subchain, "-A", routing_mark,
917 kFwmarkRoutingMask))
Hugo Benichi76be34a2020-08-26 22:35:54 +0900918 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900919 // Save in CONNMARK the source tag for egress traffic of this connection.
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900920 if (!ModifyConnmarkSave(IpFamily::Dual, subchain, "-A",
Hugo Benichi1af52392020-11-27 18:09:32 +0900921 kFwmarkAllSourcesMask))
922 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
923 "source tag on "
924 << ext_ifname;
925 // Restore from CONNMARK the source tag for ingress traffic of this connection
926 // (returned traffic).
927 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
928 kFwmarkAllSourcesMask))
929 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
930 "traffic received on "
931 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900932}
933
934void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +0900935 std::string subchain = "POSTROUTING_" + ext_ifname;
936 ModifyJumpRule(IpFamily::Dual, "mangle", "-D", "POSTROUTING", subchain,
937 "" /*iif*/, ext_ifname);
938 FlushChain(IpFamily::Dual, "mangle", subchain);
939 RemoveChain(IpFamily::Dual, "mangle", subchain);
940 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
941 kFwmarkAllSourcesMask))
942 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
943 "traffic received on "
944 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900945}
946
Hugo Benichi2a940542020-10-26 18:50:49 +0900947void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi8c526e92021-03-25 14:59:59 +0900948 int ifindex = FindIfIndex(vpn_ifname);
949 if (ifindex == 0) {
950 // Can happen if the interface has already been removed (b/183679000).
951 LOG(ERROR) << "Failed to start VPN routing on " << vpn_ifname;
952 return;
953 }
954
955 Fwmark routing_mark = Fwmark::FromIfIndex(ifindex);
956 LOG(INFO) << "Start VPN routing on " << vpn_ifname
957 << " fwmark=" << routing_mark.ToString();
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900958 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-A", "POSTROUTING", "MASQUERADE",
959 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +0900960 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900961 StartConnectionPinning(vpn_ifname);
Hugo Benichi3540c7f2021-03-29 13:14:42 +0900962
963 // Any traffic that already has a routing tag applied is accepted.
964 if (!ModifyIptables(
965 IpFamily::Dual, "mangle",
966 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
967 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
968 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
969 "connections";
970 // Otherwise, any new traffic from a new connection gets marked with the
971 // VPN routing tag.
Hugo Benichid872d3d2021-03-29 10:20:53 +0900972 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", routing_mark))
Hugo Benichi2a940542020-10-26 18:50:49 +0900973 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichi3540c7f2021-03-29 13:14:42 +0900974
975 // When the VPN client runs on the host, also route arcbr0 to that VPN so
976 // that ARC can access the VPN network through arc0.
Hugo Benichibfc49112020-12-14 12:54:44 +0900977 if (vpn_ifname != kArcBridge)
978 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
979 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900980 if (!ModifyRedirectDnsJumpRule("-A"))
981 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900982}
983
984void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi3540c7f2021-03-29 13:14:42 +0900985 LOG(INFO) << "Stop VPN routing on " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +0900986 if (vpn_ifname != kArcBridge)
987 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
988 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi3540c7f2021-03-29 13:14:42 +0900989 if (!FlushChain(IpFamily::Dual, "mangle", kApplyVpnMarkChain))
990 LOG(ERROR) << "Could not flush " << kApplyVpnMarkChain;
991
Hugo Benichi2a940542020-10-26 18:50:49 +0900992 StopConnectionPinning(vpn_ifname);
Hugo Benichiff3cbcf2021-04-03 00:22:06 +0900993 if (!ModifyJumpRule(IpFamily::IPv4, "nat", "-D", "POSTROUTING", "MASQUERADE",
994 "" /*iif*/, vpn_ifname))
Hugo Benichi891275e2020-12-16 10:35:34 +0900995 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900996 if (!ModifyRedirectDnsJumpRule("-D"))
997 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900998}
999
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001000bool Datapath::ModifyConnmarkSet(IpFamily family,
1001 const std::string& chain,
1002 const std::string& op,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001003 Fwmark mark,
1004 Fwmark mask) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +09001005 return ModifyIptables(family, "mangle",
1006 {op, chain, "-j", "CONNMARK", "--set-mark",
1007 mark.ToString() + "/" + mask.ToString(), "-w"});
Hugo Benichi76be34a2020-08-26 22:35:54 +09001008}
1009
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001010bool Datapath::ModifyConnmarkRestore(IpFamily family,
1011 const std::string& chain,
1012 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001013 const std::string& iif,
1014 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001015 std::vector<std::string> args = {op, chain};
1016 if (!iif.empty()) {
1017 args.push_back("-i");
1018 args.push_back(iif);
1019 }
1020 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001021 mask.ToString(), "-w"});
1022 return ModifyIptables(family, "mangle", args);
1023}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001024
Hugo Benichi1af52392020-11-27 18:09:32 +09001025bool Datapath::ModifyConnmarkSave(IpFamily family,
1026 const std::string& chain,
1027 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001028 Fwmark mask) {
Hugo Benichi50fe47f2021-03-29 11:33:25 +09001029 std::vector<std::string> args = {
1030 op, chain, "-j", "CONNMARK", "--save-mark",
1031 "--mask", mask.ToString(), "-w"};
Hugo Benichi58f264a2020-10-16 18:16:05 +09001032 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001033}
1034
Hugo Benichi2a940542020-10-26 18:50:49 +09001035bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1036 const std::string& op,
Hugo Benichid872d3d2021-03-29 10:20:53 +09001037 Fwmark routing_mark) {
1038 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*int_ifname*/,
1039 "" /*uid_name*/, 0 /*classid*/, routing_mark,
1040 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001041}
1042
Hugo Benichid872d3d2021-03-29 10:20:53 +09001043bool Datapath::ModifyFwmarkSourceTag(const std::string& chain,
1044 const std::string& op,
Hugo Benichi9be19b12020-08-14 15:33:40 +09001045 TrafficSource source) {
Hugo Benichid872d3d2021-03-29 10:20:53 +09001046 return ModifyFwmark(IpFamily::Dual, chain, op, "" /*iif*/, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001047 0 /*classid*/, Fwmark::FromSource(source),
1048 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001049}
1050
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001051bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1052 TrafficSource source) {
1053 std::vector<std::string> args = {"-A",
1054 kApplyLocalSourceMarkChain,
1055 "-m",
1056 "mark",
1057 "--mark",
1058 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1059 "-j",
1060 "MARK",
1061 "--set-mark",
1062 Fwmark::FromSource(source).ToString() + "/" +
1063 kFwmarkAllSourcesMask.ToString(),
1064 "-w"};
1065 return ModifyIptables(IpFamily::Dual, "mangle", args);
1066}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001067
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001068bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1069 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001070 if (std::string(source.uid_name).empty() && source.classid == 0)
1071 return false;
1072
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001073 Fwmark mark = Fwmark::FromSource(source.source_type);
1074 if (source.is_on_vpn)
1075 mark = mark | kFwmarkRouteOnVpn;
1076
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001077 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1078 "" /*iif*/, source.uid_name, source.classid, mark,
1079 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001080}
1081
1082bool Datapath::ModifyFwmark(IpFamily family,
1083 const std::string& chain,
1084 const std::string& op,
1085 const std::string& iif,
1086 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001087 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001088 Fwmark mark,
1089 Fwmark mask,
1090 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001091 std::vector<std::string> args = {op, chain};
1092 if (!iif.empty()) {
1093 args.push_back("-i");
1094 args.push_back(iif);
1095 }
1096 if (!uid_name.empty()) {
1097 args.push_back("-m");
1098 args.push_back("owner");
1099 args.push_back("--uid-owner");
1100 args.push_back(uid_name);
1101 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001102 if (classid != 0) {
1103 args.push_back("-m");
1104 args.push_back("cgroup");
1105 args.push_back("--cgroup");
1106 args.push_back(base::StringPrintf("0x%08x", classid));
1107 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001108 args.push_back("-j");
1109 args.push_back("MARK");
1110 args.push_back("--set-mark");
1111 args.push_back(mark.ToString() + "/" + mask.ToString());
1112 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001113
Hugo Benichi58f264a2020-10-16 18:16:05 +09001114 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001115}
1116
Hugo Benichid82d8832020-08-14 10:05:03 +09001117bool Datapath::ModifyIpForwarding(IpFamily family,
1118 const std::string& op,
1119 const std::string& iif,
1120 const std::string& oif,
1121 bool log_failures) {
1122 if (iif.empty() && oif.empty()) {
1123 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1124 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001125 return false;
1126 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001127 return ModifyJumpRule(family, "filter", op, "FORWARD", "ACCEPT", iif, oif,
1128 log_failures);
1129}
Garrick Evans260ff302019-07-25 11:22:50 +09001130
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001131bool Datapath::ModifyJumpRule(IpFamily family,
1132 const std::string& table,
1133 const std::string& op,
1134 const std::string& chain,
1135 const std::string& target,
1136 const std::string& iif,
1137 const std::string& oif,
1138 bool log_failures) {
1139 std::vector<std::string> args = {op, chain};
Hugo Benichid82d8832020-08-14 10:05:03 +09001140 if (!iif.empty()) {
1141 args.push_back("-i");
1142 args.push_back(iif);
1143 }
1144 if (!oif.empty()) {
1145 args.push_back("-o");
1146 args.push_back(oif);
1147 }
Hugo Benichiff3cbcf2021-04-03 00:22:06 +09001148 args.insert(args.end(), {"-j", target, "-w"});
1149 return ModifyIptables(family, table, args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001150}
1151
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001152bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1153 const std::string& op,
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001154 Fwmark mark,
1155 Fwmark mask) {
1156 std::vector<std::string> args = {op, chain};
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001157 if (mark.Value() != 0 && mask.Value() != 0) {
1158 args.push_back("-m");
1159 args.push_back("mark");
1160 args.push_back("--mark");
1161 args.push_back(mark.ToString() + "/" + mask.ToString());
1162 }
1163 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1164 return ModifyIptables(IpFamily::Dual, "mangle", args);
1165}
1166
Hugo Benichif0f55562021-04-02 15:25:02 +09001167bool Datapath::AddChain(IpFamily family,
1168 const std::string& table,
1169 const std::string& name) {
1170 DCHECK(name.size() <= kIptablesMaxChainLength);
1171 return ModifyChain(family, table, "-N", name);
1172}
1173
1174bool Datapath::RemoveChain(IpFamily family,
1175 const std::string& table,
1176 const std::string& name) {
1177 return ModifyChain(family, table, "-X", name);
1178}
1179
1180bool Datapath::FlushChain(IpFamily family,
1181 const std::string& table,
1182 const std::string& name) {
1183 return ModifyChain(family, table, "-F", name);
1184}
1185
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001186bool Datapath::ModifyChain(IpFamily family,
1187 const std::string& table,
1188 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001189 const std::string& chain,
1190 bool log_failures) {
1191 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001192}
1193
1194bool Datapath::ModifyIptables(IpFamily family,
1195 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001196 const std::vector<std::string>& argv,
1197 bool log_failures) {
1198 switch (family) {
1199 case IPv4:
1200 case IPv6:
1201 case Dual:
1202 break;
1203 default:
1204 LOG(ERROR) << "Could not execute iptables command " << table
1205 << base::JoinString(argv, " ") << ": incorrect IP family "
1206 << family;
1207 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001208 }
1209
1210 bool success = true;
1211 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001212 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001213 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001214 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001215 return success;
1216}
1217
Hugo Benichid82d8832020-08-14 10:05:03 +09001218bool Datapath::StartIpForwarding(IpFamily family,
1219 const std::string& iif,
1220 const std::string& oif) {
1221 return ModifyIpForwarding(family, "-A", iif, oif);
1222}
1223
1224bool Datapath::StopIpForwarding(IpFamily family,
1225 const std::string& iif,
1226 const std::string& oif) {
1227 return ModifyIpForwarding(family, "-D", iif, oif);
1228}
1229
1230bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1231 const std::string& ifname2) {
1232 // Only start Ipv6 forwarding if -C returns false and it had not been
1233 // started yet.
1234 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1235 false /*log_failures*/) &&
1236 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1237 return false;
1238 }
1239
1240 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1241 false /*log_failures*/) &&
1242 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001243 RemoveIPv6Forwarding(ifname1, ifname2);
1244 return false;
1245 }
1246
1247 return true;
1248}
1249
1250void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1251 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001252 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1253 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001254}
1255
Garrick Evans3d97a392020-02-21 15:24:37 +09001256bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1257 uint32_t addr,
1258 uint32_t netmask) {
1259 struct rtentry route;
1260 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001261 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1262 SetSockaddrIn(&route.rt_dst, addr & netmask);
1263 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001264 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001265 return ModifyRtentry(SIOCADDRT, &route);
1266}
Garrick Evans3d97a392020-02-21 15:24:37 +09001267
Hugo Benichie8758b52020-04-03 14:49:01 +09001268bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1269 uint32_t addr,
1270 uint32_t netmask) {
1271 struct rtentry route;
1272 memset(&route, 0, sizeof(route));
1273 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1274 SetSockaddrIn(&route.rt_dst, addr & netmask);
1275 SetSockaddrIn(&route.rt_genmask, netmask);
1276 route.rt_flags = RTF_UP | RTF_GATEWAY;
1277 return ModifyRtentry(SIOCDELRT, &route);
1278}
1279
1280bool Datapath::AddIPv4Route(const std::string& ifname,
1281 uint32_t addr,
1282 uint32_t netmask) {
1283 struct rtentry route;
1284 memset(&route, 0, sizeof(route));
1285 SetSockaddrIn(&route.rt_dst, addr & netmask);
1286 SetSockaddrIn(&route.rt_genmask, netmask);
1287 char rt_dev[IFNAMSIZ];
1288 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1289 rt_dev[IFNAMSIZ - 1] = '\0';
1290 route.rt_dev = rt_dev;
1291 route.rt_flags = RTF_UP | RTF_GATEWAY;
1292 return ModifyRtentry(SIOCADDRT, &route);
1293}
1294
1295bool Datapath::DeleteIPv4Route(const std::string& ifname,
1296 uint32_t addr,
1297 uint32_t netmask) {
1298 struct rtentry route;
1299 memset(&route, 0, sizeof(route));
1300 SetSockaddrIn(&route.rt_dst, addr & netmask);
1301 SetSockaddrIn(&route.rt_genmask, netmask);
1302 char rt_dev[IFNAMSIZ];
1303 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1304 rt_dev[IFNAMSIZ - 1] = '\0';
1305 route.rt_dev = rt_dev;
1306 route.rt_flags = RTF_UP | RTF_GATEWAY;
1307 return ModifyRtentry(SIOCDELRT, &route);
1308}
1309
Taoyu Lia0727dc2020-09-24 19:54:59 +09001310bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001311 DCHECK(route);
1312 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001313 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001314 return false;
1315 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001316 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1317 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001318 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001319 return false;
1320 }
1321 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1322 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001323 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001324 return false;
1325 }
1326 return true;
1327}
1328
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001329bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1330 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1331 kArcAddr, kAdbServerPort, ifname,
1332 kLocalhostAddr, kAdbProxyTcpListenPort);
1333}
1334
1335void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1336 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1337 kArcAddr, kAdbServerPort, ifname,
1338 kLocalhostAddr, kAdbProxyTcpListenPort);
1339}
1340
1341bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1342 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1343 kAdbProxyTcpListenPort, ifname);
1344}
1345
1346void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1347 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1348 kAdbProxyTcpListenPort, ifname);
1349}
1350
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001351void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1352 if_nametoindex_[ifname] = ifindex;
1353}
1354
1355int Datapath::FindIfIndex(const std::string& ifname) {
1356 uint32_t ifindex = if_nametoindex(ifname.c_str());
1357 if (ifindex > 0) {
1358 if_nametoindex_[ifname] = ifindex;
1359 return ifindex;
1360 }
1361
1362 const auto it = if_nametoindex_.find(ifname);
1363 if (it != if_nametoindex_.end())
1364 return it->second;
1365
1366 return 0;
1367}
1368
Hugo Benichifcf81022020-12-04 11:01:37 +09001369std::ostream& operator<<(std::ostream& stream,
1370 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001371 stream << "{ pid: " << nsinfo.pid
1372 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001373 if (!nsinfo.outbound_ifname.empty()) {
1374 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1375 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001376 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1377 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001378 << ", peer_ifname: " << nsinfo.peer_ifname
1379 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1380 return stream;
1381}
1382
Garrick Evans3388a032020-03-24 11:25:55 +09001383} // namespace patchpanel