blob: 1bb62c18289f1228d08be647651c3d5642a27b2f [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
Garrick Evansc7ae82c2019-09-04 16:25:10 +090020#include <base/files/scoped_file.h>
21#include <base/logging.h>
Taoyu Li79871c92020-07-02 16:09:39 +090022#include <base/posix/eintr_wrapper.h>
Garrick Evans54861622019-07-19 09:05:09 +090023#include <base/strings/string_number_conversions.h>
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +090024#include <base/strings/string_util.h>
25#include <base/strings/stringprintf.h>
Garrick Evans4f9f5572019-11-26 10:25:16 +090026#include <brillo/userdb_utils.h>
Garrick Evans54861622019-07-19 09:05:09 +090027
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090028#include "patchpanel/adb_proxy.h"
Hugo Benichibfc49112020-12-14 12:54:44 +090029#include "patchpanel/arc_service.h"
Garrick Evans3388a032020-03-24 11:25:55 +090030#include "patchpanel/net_util.h"
31#include "patchpanel/scoped_ns.h"
Garrick Evansc7ae82c2019-09-04 16:25:10 +090032
Garrick Evans3388a032020-03-24 11:25:55 +090033namespace patchpanel {
Garrick Evans54861622019-07-19 09:05:09 +090034
Garrick Evansc7ae82c2019-09-04 16:25:10 +090035namespace {
Hugo Benichi76675592020-04-08 14:29:57 +090036// TODO(hugobenichi) Consolidate this constant definition in a single place.
37constexpr pid_t kTestPID = -2;
Garrick Evansc7ae82c2019-09-04 16:25:10 +090038constexpr char kDefaultIfname[] = "vmtap%d";
39constexpr char kTunDev[] = "/dev/net/tun";
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090040constexpr char kArcAddr[] = "100.115.92.2";
41constexpr char kLocalhostAddr[] = "127.0.0.1";
42constexpr uint16_t kAdbServerPort = 5555;
Hugo Benichie8758b52020-04-03 14:49:01 +090043
Hugo Benichibf811c62020-09-07 17:30:45 +090044// Constants used for dropping locally originated traffic bound to an incorrect
45// source IPv4 address.
46constexpr char kGuestIPv4Subnet[] = "100.115.92.0/23";
47constexpr std::array<const char*, 6> kPhysicalIfnamePrefixes{
48 {"eth+", "wlan+", "mlan+", "usb+", "wwan+", "rmnet+"}};
49
Hugo Benichi3a9162b2020-09-09 15:47:40 +090050constexpr char kApplyLocalSourceMarkChain[] = "apply_local_source_mark";
Hugo Benichi3ef370b2020-11-16 19:07:17 +090051constexpr char kApplyVpnMarkChain[] = "apply_vpn_mark";
Hugo Benichi155de002021-01-19 16:45:46 +090052constexpr char kCheckRoutingMarkChain[] = "check_routing_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
Garrick Evans8a067562020-05-11 12:47:30 +090056std::string PrefixIfname(const std::string& prefix, const std::string& ifname) {
57 std::string n = prefix + ifname;
Garrick Evans2f581a02020-05-11 10:43:35 +090058 if (n.length() < IFNAMSIZ)
59 return n;
Garrick Evans54861622019-07-19 09:05:09 +090060
Garrick Evans2f581a02020-05-11 10:43:35 +090061 // Best effort attempt to preserve the interface number, assuming it's the
62 // last char in the name.
63 auto c = ifname[ifname.length() - 1];
64 n.resize(IFNAMSIZ - 1);
65 n[n.length() - 1] = c;
66 return n;
Garrick Evans54861622019-07-19 09:05:09 +090067}
Garrick Evansf0ab7132019-06-18 14:50:42 +090068
Garrick Evans8a067562020-05-11 12:47:30 +090069} // namespace
70
71std::string ArcVethHostName(const std::string& ifname) {
72 return PrefixIfname("veth", ifname);
73}
74
75std::string ArcBridgeName(const std::string& ifname) {
76 return PrefixIfname("arc_", ifname);
77}
78
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090079Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
80 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090081
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090082Datapath::Datapath(MinijailedProcessRunner* process_runner,
83 Firewall* firewall,
84 ioctl_t ioctl_hook)
85 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +090086 CHECK(process_runner_);
87}
88
Garrick Evans260ff302019-07-25 11:22:50 +090089MinijailedProcessRunner& Datapath::runner() const {
90 return *process_runner_;
91}
92
Hugo Benichibf811c62020-09-07 17:30:45 +090093void Datapath::Start() {
Hugo Benichi91ee09f2020-12-03 22:24:22 +090094 // Restart from a clean iptables state in case of an unordered shutdown.
95 ResetIptables();
96
Hugo Benichibf811c62020-09-07 17:30:45 +090097 // Enable IPv4 packet forwarding
98 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
99 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
100 << " Guest connectivity will not work correctly.";
101
102 // Limit local port range: Android owns 47104-61000.
103 // TODO(garrick): The original history behind this tweak is gone. Some
104 // investigation is needed to see if it is still applicable.
105 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
106 "32768 47103") != 0)
107 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
108 << " apps may not work correctly.";
109
110 // Enable IPv6 packet forwarding
111 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
112 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
113 << " IPv6 functionality may be broken.";
114
Hugo Benichi58125d32020-09-09 11:25:45 +0900115 // Create a FORWARD ACCEPT rule for connections already established.
116 if (process_runner_->iptables(
117 "filter", {"-A", "FORWARD", "-m", "state", "--state",
118 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900119 LOG(ERROR) << "Failed to install forwarding rule for established"
120 << " connections.";
121
122 // chromium:898210: Drop any locally originated traffic that would exit a
123 // physical interface with a source IPv4 address from the subnet of IPs used
124 // for VMs, containers, and connected namespaces This is needed to prevent
125 // packets leaking with an incorrect src IP when a local process binds to the
126 // wrong interface.
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900127 if (!ModifyChain(IpFamily::IPv4, "filter", "-N", kDropGuestIpv4PrefixChain))
128 LOG(ERROR) << "Failed to create " << kDropGuestIpv4PrefixChain
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900129 << " filter chain";
130 if (!ModifyIptables(IpFamily::IPv4, "filter",
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900131 {"-I", "OUTPUT", "-j", kDropGuestIpv4PrefixChain, "-w"}))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900132 LOG(ERROR) << "Failed to set up jump rule from filter OUTPUT to "
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900133 << kDropGuestIpv4PrefixChain;
Hugo Benichibf811c62020-09-07 17:30:45 +0900134 for (const auto& oif : kPhysicalIfnamePrefixes) {
135 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
136 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
137 << kGuestIPv4Subnet << " exiting " << oif;
138 }
139
Hugo Benichi561fae42021-01-22 15:28:40 +0900140 // Set static SNAT rules for any IPv4 traffic originated from a guest (ARC,
141 // Crostini, ...) or a connected namespace.
142 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
143 // need to be explicitly dropped as SNAT cannot be applied to them.
144 if (process_runner_->iptables(
145 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
146 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0)
147 LOG(ERROR) << "Failed to install SNAT mark rules.";
148 if (process_runner_->iptables(
149 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
150 "MASQUERADE", "-w"}) != 0)
151 LOG(ERROR) << "Failed to install SNAT mark rules.";
Hugo Benichibf811c62020-09-07 17:30:45 +0900152 if (!AddOutboundIPv4SNATMark("vmtap+"))
Hugo Benichi561fae42021-01-22 15:28:40 +0900153 LOG(ERROR) << "Failed to set up NAT for TAP devices.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900154
Hugo Benichi2a940542020-10-26 18:50:49 +0900155 // Applies the routing tag saved in conntrack for any established connection
156 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900157 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
158 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900159 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
Hugo Benichi155de002021-01-19 16:45:46 +0900160 // b/177787823 Also restore the routing tag after routing has taken place so
161 // that packets pre-tagged with the VPN routing tag are in sync with their
162 // associated CONNMARK routing tag. This is necessary to correctly identify
163 // packets exiting through the wrong interface.
164 if (!ModifyConnmarkRestore(IpFamily::Dual, "POSTROUTING", "-A", "" /*iif*/,
165 kFwmarkRoutingMask))
166 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK restore rule";
Hugo Benichi2a940542020-10-26 18:50:49 +0900167
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900168 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
169 // tag and tagging the local traffic that should be routed through a VPN.
170 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyLocalSourceMarkChain))
171 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
172 << " mangle chain";
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900173 if (!ModifyIptables(IpFamily::Dual, "mangle",
174 {"-A", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
175 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
176 << " to mangle OUTPUT";
177 // Create rules for tagging local sources with the source tag and the vpn
178 // policy tag.
179 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900180 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900181 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
182 << " in " << kApplyLocalSourceMarkChain;
183 }
184 // Finally add a catch-all rule for tagging any remaining local sources with
185 // the SYSTEM source tag
186 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
187 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
188
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900189 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
190 // traffic that should be routed through a VPN.
191 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyVpnMarkChain))
192 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900193 // All local outgoing traffic eligible to VPN routing should traverse the VPN
194 // marking chain.
195 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", "" /*iif*/, kFwmarkRouteOnVpn,
196 kFwmarkVpnMask))
197 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
198 // Any traffic that already has a routing tag applied is accepted.
199 if (!ModifyIptables(
200 IpFamily::Dual, "mangle",
201 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
202 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
203 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
204 "connections";
Hugo Benichi155de002021-01-19 16:45:46 +0900205
206 // Sets up a mangle chain used in POSTROUTING for checking consistency between
207 // the routing tag and the output interface.
208 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kCheckRoutingMarkChain))
209 LOG(ERROR) << "Failed to set up " << kCheckRoutingMarkChain
210 << " mangle chain";
Hugo Benichi155de002021-01-19 16:45:46 +0900211 // b/177787823 If it already exists, the routing tag of any traffic exiting an
212 // interface (physical or VPN) must match the routing tag of that interface.
213 if (!ModifyIptables(IpFamily::Dual, "mangle",
214 {"-A", "POSTROUTING", "-m", "mark", "!", "--mark",
215 "0x0/" + kFwmarkRoutingMask.ToString(), "-j",
216 kCheckRoutingMarkChain, "-w"}))
217 LOG(ERROR) << "Failed to add POSTROUTING jump rule to "
218 << kCheckRoutingMarkChain;
Hugo Benichi52a64992021-01-28 17:47:33 +0900219
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900220 // b/178331695 Sets up a nat chain used in OUTPUT for redirecting DNS queries
221 // of system services. When a VPN is connected, a query routed through a
222 // physical network is redirected to the primary nameserver of that network.
223 if (!ModifyChain(IpFamily::IPv4, "nat", "-N", kRedirectDnsChain))
224 LOG(ERROR) << "Failed to set up " << kRedirectDnsChain << " nat chain";
225
Hugo Benichi52a64992021-01-28 17:47:33 +0900226 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
227 // incorrectly cause neighbor discovery icmpv6 packets to be dropped. Add
228 // these rules to bypass connmark rule for those packets.
229 for (const auto& type : kNeighborDiscoveryTypes) {
230 if (!ModifyIptables(IpFamily::IPv6, "mangle",
231 {"-I", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
232 "-j", "ACCEPT", "-w"}))
233 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
234 << " packets in OUTPUT";
235 if (!ModifyIptables(IpFamily::IPv6, "mangle",
236 {"-I", kCheckRoutingMarkChain, "-p", "icmpv6",
237 "--icmpv6-type", type, "-j", "RETURN", "-w"}))
238 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
239 << " packets in " << kCheckRoutingMarkChain;
240 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900241}
242
243void Datapath::Stop() {
Hugo Benichibf811c62020-09-07 17:30:45 +0900244 // Restore original local port range.
245 // TODO(garrick): The original history behind this tweak is gone. Some
246 // investigation is needed to see if it is still applicable.
247 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
248 "32768 61000") != 0)
249 LOG(ERROR) << "Failed to restore local port range";
250
251 // Disable packet forwarding
252 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
253 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
254
255 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
256 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900257
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900258 ResetIptables();
259}
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900260
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900261void Datapath::ResetIptables() {
262 // If it exists, remove jump rules from a built-in chain to a custom routing
263 // or tagging chain.
264 ModifyIptables(IpFamily::IPv4, "filter",
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900265 {"-D", "OUTPUT", "-j", kDropGuestIpv4PrefixChain, "-w"},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900266 false /*log_failures*/);
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900267
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900268 // Flush chains used for routing and fwmark tagging. Also delete additional
269 // chains made by patchpanel. Chains used by permission broker (nat
270 // PREROUTING, filter INPUT) and chains used for traffic counters (mangle
271 // {rx,tx}_{<iface>, vpn}) are not flushed.
272 static struct {
273 IpFamily family;
274 std::string table;
275 std::string chain;
276 bool should_delete;
277 } resetOps[] = {
278 {IpFamily::Dual, "filter", "FORWARD", false},
279 {IpFamily::Dual, "mangle", "FORWARD", false},
280 {IpFamily::Dual, "mangle", "INPUT", false},
281 {IpFamily::Dual, "mangle", "OUTPUT", false},
282 {IpFamily::Dual, "mangle", "POSTROUTING", false},
283 {IpFamily::Dual, "mangle", "PREROUTING", false},
284 {IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain, true},
285 {IpFamily::Dual, "mangle", kApplyVpnMarkChain, true},
286 {IpFamily::Dual, "mangle", kCheckRoutingMarkChain, true},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900287 {IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain, true},
288 {IpFamily::IPv4, "nat", kRedirectDnsChain, true},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900289 {IpFamily::IPv4, "nat", "POSTROUTING", false},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900290 {IpFamily::IPv4, "nat", "OUTPUT", false},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900291 };
292 for (const auto& op : resetOps) {
293 // Chains to delete are custom chains and will not exist the first time
294 // patchpanel starts after boot. Skip flushing and delete these chains if
295 // they do not exist to avoid logging spurious error messages.
296 if (op.should_delete && !ModifyChain(op.family, op.table, "-L", op.chain,
297 false /*log_failures*/))
298 continue;
Hugo Benichi155de002021-01-19 16:45:46 +0900299
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900300 if (!ModifyChain(op.family, op.table, "-F", op.chain))
301 LOG(ERROR) << "Failed to flush " << op.chain << " chain in table "
302 << op.table;
Hugo Benichi2a940542020-10-26 18:50:49 +0900303
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900304 if (op.should_delete && !ModifyChain(op.family, op.table, "-X", op.chain))
305 LOG(ERROR) << "Failed to delete " << op.chain << " chain in table "
306 << op.table;
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900307 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900308}
309
Hugo Benichi33860d72020-07-09 16:34:01 +0900310bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
311 // Try first to delete any netns with name |netns_name| in case patchpanel
312 // did not exit cleanly.
313 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
314 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
315 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
316}
317
318bool Datapath::NetnsDeleteName(const std::string& netns_name) {
319 return process_runner_->ip_netns_delete(netns_name) == 0;
320}
321
Garrick Evans8a949dc2019-07-18 16:17:53 +0900322bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900323 uint32_t ipv4_addr,
324 uint32_t ipv4_prefix_len) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900325 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900326 if (process_runner_->brctl("addbr", {ifname}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900327 return false;
328 }
329
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900330 if (process_runner_->ip(
331 "addr", "add",
332 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
333 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
334 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900335 RemoveBridge(ifname);
336 return false;
337 }
338
339 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900340 RemoveBridge(ifname);
341 return false;
342 }
343
344 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900345 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900346 RemoveBridge(ifname);
347 return false;
348 }
349
350 return true;
351}
352
353void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900354 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900355 process_runner_->ip("link", "set", {ifname, "down"});
Garrick Evans8e8e3472020-01-23 14:03:50 +0900356 process_runner_->brctl("delbr", {ifname});
Garrick Evans8a949dc2019-07-18 16:17:53 +0900357}
358
Garrick Evans621ed262019-11-13 12:28:43 +0900359bool Datapath::AddToBridge(const std::string& br_ifname,
360 const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900361 return (process_runner_->brctl("addif", {br_ifname, ifname}) == 0);
Garrick Evans621ed262019-11-13 12:28:43 +0900362}
363
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900364std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900365 const MacAddress* mac_addr,
366 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900367 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900368 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
369 if (!dev.is_valid()) {
370 PLOG(ERROR) << "Failed to open " << kTunDev;
371 return "";
372 }
373
374 struct ifreq ifr;
375 memset(&ifr, 0, sizeof(ifr));
376 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
377 sizeof(ifr.ifr_name));
378 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
379
380 // If a template was given as the name, ifr_name will be updated with the
381 // actual interface name.
382 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900383 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900384 return "";
385 }
386 const char* ifname = ifr.ifr_name;
387
388 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900389 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900390 return "";
391 }
392
Garrick Evans4f9f5572019-11-26 10:25:16 +0900393 if (!user.empty()) {
394 uid_t uid = -1;
395 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
396 PLOG(ERROR) << "Unable to look up UID for " << user;
397 RemoveTAP(ifname);
398 return "";
399 }
400 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
401 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
402 << ifname;
403 RemoveTAP(ifname);
404 return "";
405 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900406 }
407
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900408 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900409 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
410 if (!sock.is_valid()) {
411 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900412 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900413 RemoveTAP(ifname);
414 return "";
415 }
416
Garrick Evans621ed262019-11-13 12:28:43 +0900417 if (ipv4_addr) {
418 struct sockaddr_in* addr =
419 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
420 addr->sin_family = AF_INET;
421 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
422 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
423 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
424 << " {" << ipv4_addr->ToCidrString() << "}";
425 RemoveTAP(ifname);
426 return "";
427 }
428
429 struct sockaddr_in* netmask =
430 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
431 netmask->sin_family = AF_INET;
432 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
433 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
434 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
435 << " {" << ipv4_addr->ToCidrString() << "}";
436 RemoveTAP(ifname);
437 return "";
438 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900439 }
440
Garrick Evans621ed262019-11-13 12:28:43 +0900441 if (mac_addr) {
442 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
443 hwaddr->sa_family = ARPHRD_ETHER;
444 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
445 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
446 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
447 << " {" << MacAddressToString(*mac_addr) << "}";
448 RemoveTAP(ifname);
449 return "";
450 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900451 }
452
453 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900454 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900455 RemoveTAP(ifname);
456 return "";
457 }
458
459 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
460 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900461 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900462 RemoveTAP(ifname);
463 return "";
464 }
465
466 return ifname;
467}
468
469void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900470 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900471}
472
Hugo Benichi33860d72020-07-09 16:34:01 +0900473bool Datapath::ConnectVethPair(pid_t netns_pid,
474 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900475 const std::string& veth_ifname,
476 const std::string& peer_ifname,
477 const MacAddress& remote_mac_addr,
478 uint32_t remote_ipv4_addr,
479 uint32_t remote_ipv4_prefix_len,
480 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900481 // Set up the virtual pair across the current namespace and |netns_name|.
482 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
483 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
484 << peer_ifname;
485 return false;
486 }
487
488 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900489 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900490 ScopedNS ns(netns_pid, ScopedNS::Type::Network);
Hugo Benichi33860d72020-07-09 16:34:01 +0900491 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900492 LOG(ERROR)
493 << "Cannot create virtual link -- invalid container namespace?";
494 return false;
495 }
496
Hugo Benichi76675592020-04-08 14:29:57 +0900497 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
498 remote_ipv4_prefix_len, true /* link up */,
499 remote_multicast_flag)) {
500 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
501 RemoveInterface(peer_ifname);
502 return false;
503 }
504 }
505
Hugo Benichi76675592020-04-08 14:29:57 +0900506 if (!ToggleInterface(veth_ifname, true /*up*/)) {
507 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
508 RemoveInterface(veth_ifname);
509 return false;
510 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900511
Hugo Benichi76675592020-04-08 14:29:57 +0900512 return true;
513}
514
Hugo Benichi33860d72020-07-09 16:34:01 +0900515bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
516 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900517 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900518 return process_runner_->ip("link", "add",
519 {veth_ifname, "type", "veth", "peer", "name",
520 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900521}
Garrick Evans54861622019-07-19 09:05:09 +0900522
Garrick Evans2470caa2020-03-04 14:15:41 +0900523bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
524 const std::string link = up ? "up" : "down";
525 return process_runner_->ip("link", "set", {ifname, link}) == 0;
526}
Garrick Evans54861622019-07-19 09:05:09 +0900527
Garrick Evans2470caa2020-03-04 14:15:41 +0900528bool Datapath::ConfigureInterface(const std::string& ifname,
529 const MacAddress& mac_addr,
530 uint32_t ipv4_addr,
531 uint32_t ipv4_prefix_len,
532 bool up,
533 bool enable_multicast) {
534 const std::string link = up ? "up" : "down";
535 const std::string multicast = enable_multicast ? "on" : "off";
536 return (process_runner_->ip(
537 "addr", "add",
538 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
539 IPv4AddressToString(
540 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
541 "dev", ifname}) == 0) &&
542 (process_runner_->ip("link", "set",
543 {
544 "dev",
545 ifname,
546 link,
547 "addr",
548 MacAddressToString(mac_addr),
549 "multicast",
550 multicast,
551 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900552}
553
554void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900555 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900556}
557
Hugo Benichi321f23b2020-09-25 15:42:05 +0900558bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
559 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900560 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900561 "filter", {"-I", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
562 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900563}
564
565bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
566 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900567 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900568 "filter", {"-D", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
569 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900570}
571
Hugo Benichifcf81022020-12-04 11:01:37 +0900572bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900573 // Veth interface configuration and client routing configuration:
574 // - attach a name to the client namespace.
575 // - create veth pair across the current namespace and the client namespace.
576 // - configure IPv4 address on remote veth inside client namespace.
577 // - configure IPv4 address on local veth inside host namespace.
578 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900579 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
580 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
581 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900582 return false;
583 }
584
Hugo Benichifcf81022020-12-04 11:01:37 +0900585 if (!ConnectVethPair(
586 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
587 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
588 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900589 LOG(ERROR) << "Failed to create veth pair for"
590 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900591 << nsinfo.pid;
592 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900593 return false;
594 }
595
Hugo Benichifcf81022020-12-04 11:01:37 +0900596 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
597 nsinfo.peer_subnet->AddressAtOffset(0),
598 nsinfo.peer_subnet->PrefixLength(),
599 true /* link up */, false /* enable_multicast */)) {
600 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
601 RemoveInterface(nsinfo.host_ifname);
602 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900603 return false;
604 }
605
606 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900607 ScopedNS ns(nsinfo.pid, ScopedNS::Type::Network);
Hugo Benichifcf81022020-12-04 11:01:37 +0900608 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
609 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
610 RemoveInterface(nsinfo.host_ifname);
611 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900612 return false;
613 }
614
Hugo Benichifcf81022020-12-04 11:01:37 +0900615 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
616 INADDR_ANY)) {
617 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
618 << " inside namespace pid " << nsinfo.pid;
619 RemoveInterface(nsinfo.host_ifname);
620 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900621 return false;
622 }
623 }
624
625 // Host namespace routing configuration
626 // - ingress: add route to client subnet via |host_ifname|.
627 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
628 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
629 // Note that by default unsolicited ingress traffic is not forwarded to the
630 // client namespace unless the client specifically set port forwarding
631 // through permission_broker DBus APIs.
632 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
633 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900634 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
635 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
636 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900637 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900638 RemoveInterface(nsinfo.host_ifname);
639 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900640 return false;
641 }
642
Hugo Benichi7c342672020-09-08 09:18:14 +0900643 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900644 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900645 LOG(ERROR) << "Failed to set SNAT for traffic"
646 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900647 << nsinfo.host_ifname;
648 RemoveInterface(nsinfo.host_ifname);
649 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
650 nsinfo.peer_subnet->BaseAddress(), netmask);
651 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
652 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900653 return false;
654 }
655
Hugo Benichi93306e52020-12-04 16:08:00 +0900656 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
657 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
658 nsinfo.route_on_vpn);
659
Hugo Benichi7c342672020-09-08 09:18:14 +0900660 return true;
661}
662
Hugo Benichifcf81022020-12-04 11:01:37 +0900663void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900664 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
665 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
666 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900667 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900668 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
669 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
670 nsinfo.peer_subnet->BaseAddress(),
671 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
672 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900673}
674
Hugo Benichi8d622b52020-08-13 15:24:12 +0900675void Datapath::StartRoutingDevice(const std::string& ext_ifname,
676 const std::string& int_ifname,
677 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900678 TrafficSource source,
679 bool route_on_vpn) {
680 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900681 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900682 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
683 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
684 << "->" << int_ifname;
685
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900686 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900687 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
688 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900689
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900690 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900691 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
692 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900693
Hugo Benichi2a940542020-10-26 18:50:49 +0900694 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
695 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
696 << source << " for " << int_ifname;
697
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900698 if (!ext_ifname.empty()) {
699 // If |ext_ifname| is not null, mark egress traffic with the
700 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi2a940542020-10-26 18:50:49 +0900701 if (!ModifyFwmarkRoutingTag("PREROUTING", "-A", ext_ifname, int_ifname))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900702 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
703 << ext_ifname << "<-" << int_ifname;
704 } else {
705 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
706 // PREROUTING to apply any fwmark routing tag saved for the current
707 // connection, and rely on implicit routing to the default logical network
708 // otherwise.
Hugo Benichi1af52392020-11-27 18:09:32 +0900709 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname,
710 kFwmarkRoutingMask))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900711 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
712 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900713
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900714 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900715 // default network is eligible to be routed through a VPN if |route_on_vpn|
716 // is true.
717 if (route_on_vpn &&
718 !ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900719 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900720 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900721}
722
723void Datapath::StopRoutingDevice(const std::string& ext_ifname,
724 const std::string& int_ifname,
725 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900726 TrafficSource source,
727 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900728 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900729 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900730 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
731 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900732 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900733 if (!ext_ifname.empty()) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900734 ModifyFwmarkRoutingTag("PREROUTING", "-D", ext_ifname, int_ifname);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900735 } else {
Hugo Benichi1af52392020-11-27 18:09:32 +0900736 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname,
737 kFwmarkRoutingMask);
Hugo Benichi93306e52020-12-04 16:08:00 +0900738 if (route_on_vpn)
739 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900740 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900741}
742
Garrick Evansf0ab7132019-06-18 14:50:42 +0900743bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
744 const std::string& ipv4_addr) {
745 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900746 if (process_runner_->iptables(
747 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
748 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900749 return false;
750
751 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900752 if (process_runner_->iptables(
753 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
754 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900755 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
756 return false;
757 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900758 if (process_runner_->iptables(
759 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
760 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900761 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
762 return false;
763 }
764
765 return true;
766}
767
768void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
769 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900770 process_runner_->iptables(
771 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
772 "--to-destination", ipv4_addr, "-w"});
773 process_runner_->iptables(
774 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
775 "--to-destination", ipv4_addr, "-w"});
776 process_runner_->iptables(
777 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
778 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900779}
780
Hugo Benichie8758b52020-04-03 14:49:01 +0900781bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
782 return process_runner_->iptables(
783 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900784 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900785}
786
787void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
788 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900789 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900790}
791
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900792bool Datapath::AddRedirectDnsRule(const std::string& ifname,
793 const std::string dns_ipv4_addr) {
794 bool success = true;
795 success &= RemoveRedirectDnsRule(ifname);
796 // Use Insert operation to ensure that the new DNS address is used first.
797 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
798 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
799 physical_dns_addresses_[ifname] = dns_ipv4_addr;
800 return success;
801}
802
803bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
804 const auto it = physical_dns_addresses_.find(ifname);
805 if (it == physical_dns_addresses_.end())
806 return true;
807
808 bool success = true;
809 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
810 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
811 physical_dns_addresses_.erase(it);
812 return success;
813}
814
815bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
816 const std::string& protocol,
817 const std::string& ifname,
818 const std::string& dns_ipv4_addr) {
819 std::vector<std::string> args = {op,
820 kRedirectDnsChain,
821 "-p",
822 protocol,
823 "--dport",
824 "53",
825 "-o",
826 ifname,
827 "-j",
828 "DNAT",
829 "--to-destination",
830 dns_ipv4_addr,
831 "-w"};
832 return process_runner_->iptables("nat", args) != 0;
833}
834
835bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
836 std::vector<std::string> args = {
837 op,
838 "OUTPUT",
839 "-m",
840 "mark",
841 "!",
842 "--mark",
843 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
844 "-j",
845 kRedirectDnsChain,
846 "-w"};
847 return process_runner_->iptables("nat", args) != 0;
848}
849
Garrick Evans664a82f2019-12-17 12:18:05 +0900850bool Datapath::MaskInterfaceFlags(const std::string& ifname,
851 uint16_t on,
852 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900853 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
854 if (!sock.is_valid()) {
855 PLOG(ERROR) << "Failed to create control socket";
856 return false;
857 }
858 ifreq ifr;
859 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
860 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
861 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
862 return false;
863 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900864 ifr.ifr_flags |= on;
865 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900866 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900867 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
868 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900869 return false;
870 }
871 return true;
872}
873
Garrick Evans260ff302019-07-25 11:22:50 +0900874bool Datapath::AddIPv6HostRoute(const std::string& ifname,
875 const std::string& ipv6_addr,
876 int ipv6_prefix_len) {
877 std::string ipv6_addr_cidr =
878 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
879
Garrick Evans8e8e3472020-01-23 14:03:50 +0900880 return process_runner_->ip6("route", "replace",
881 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900882}
883
884void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
885 const std::string& ipv6_addr,
886 int ipv6_prefix_len) {
887 std::string ipv6_addr_cidr =
888 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
889
Garrick Evans8e8e3472020-01-23 14:03:50 +0900890 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900891}
892
Taoyu Lia0727dc2020-09-24 19:54:59 +0900893bool Datapath::AddIPv6Address(const std::string& ifname,
894 const std::string& ipv6_addr) {
895 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900896}
897
Taoyu Lia0727dc2020-09-24 19:54:59 +0900898void Datapath::RemoveIPv6Address(const std::string& ifname,
899 const std::string& ipv6_addr) {
900 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900901}
902
Hugo Benichi76be34a2020-08-26 22:35:54 +0900903void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900904 int ifindex = FindIfIndex(ext_ifname);
905 if (ifindex != 0 && !ModifyIptables(IpFamily::Dual, "mangle",
906 {"-A", kCheckRoutingMarkChain, "-o",
907 ext_ifname, "-m", "mark", "!", "--mark",
908 Fwmark::FromIfIndex(ifindex).ToString() +
909 "/" + kFwmarkRoutingMask.ToString(),
910 "-j", "DROP", "-w"}))
911 LOG(ERROR) << "Could not set fwmark routing filter rule for " << ext_ifname;
912
Hugo Benichi1af52392020-11-27 18:09:32 +0900913 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi76be34a2020-08-26 22:35:54 +0900914 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
915 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900916 // Save in CONNMARK the source tag for egress traffic of this connection.
917 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
918 kFwmarkAllSourcesMask))
919 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
920 "source tag on "
921 << ext_ifname;
922 // Restore from CONNMARK the source tag for ingress traffic of this connection
923 // (returned traffic).
924 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
925 kFwmarkAllSourcesMask))
926 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
927 "traffic received on "
928 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900929}
930
931void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900932 int ifindex = FindIfIndex(ext_ifname);
933 if (ifindex != 0 && !ModifyIptables(IpFamily::Dual, "mangle",
934 {"-D", kCheckRoutingMarkChain, "-o",
935 ext_ifname, "-m", "mark", "!", "--mark",
936 Fwmark::FromIfIndex(ifindex).ToString() +
937 "/" + kFwmarkRoutingMask.ToString(),
938 "-j", "DROP", "-w"}))
939 LOG(ERROR) << "Could not remove fwmark routing filter rule for "
940 << ext_ifname;
941
Hugo Benichi76be34a2020-08-26 22:35:54 +0900942 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
943 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900944 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
945 kFwmarkAllSourcesMask))
946 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
947 "fwmark source tag on "
948 << ext_ifname;
949 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
950 kFwmarkAllSourcesMask))
951 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
952 "traffic received on "
953 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900954}
955
Hugo Benichi2a940542020-10-26 18:50:49 +0900956void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi891275e2020-12-16 10:35:34 +0900957 if (process_runner_->iptables("nat", {"-A", "POSTROUTING", "-o", vpn_ifname,
958 "-j", "MASQUERADE", "-w"}) != 0)
959 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900960 StartConnectionPinning(vpn_ifname);
961 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", vpn_ifname, ""))
962 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +0900963 if (vpn_ifname != kArcBridge)
964 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
965 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900966 if (!ModifyRedirectDnsJumpRule("-A"))
967 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900968}
969
970void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900971 if (vpn_ifname != kArcBridge)
972 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
973 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi2a940542020-10-26 18:50:49 +0900974 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", vpn_ifname, ""))
975 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
976 StopConnectionPinning(vpn_ifname);
Hugo Benichi891275e2020-12-16 10:35:34 +0900977 if (process_runner_->iptables("nat", {"-D", "POSTROUTING", "-o", vpn_ifname,
978 "-j", "MASQUERADE", "-w"}) != 0)
979 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900980 if (!ModifyRedirectDnsJumpRule("-D"))
981 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900982}
983
Hugo Benichi76be34a2020-08-26 22:35:54 +0900984bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
985 const std::string& op,
986 const std::string& oif) {
Hugo Benichi76be34a2020-08-26 22:35:54 +0900987 int ifindex = FindIfIndex(oif);
988 if (ifindex == 0) {
989 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
990 return false;
991 }
992
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900993 return ModifyConnmarkSet(family, "POSTROUTING", op, oif,
994 Fwmark::FromIfIndex(ifindex), kFwmarkRoutingMask);
995}
996
997bool Datapath::ModifyConnmarkSet(IpFamily family,
998 const std::string& chain,
999 const std::string& op,
1000 const std::string& oif,
1001 Fwmark mark,
1002 Fwmark mask) {
1003 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
1004 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
1005 return false;
1006 }
1007
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001008 std::vector<std::string> args = {op, chain};
1009 if (!oif.empty()) {
1010 args.push_back("-o");
1011 args.push_back(oif);
1012 }
1013 args.push_back("-j");
1014 args.push_back("CONNMARK");
1015 args.push_back("--set-mark");
1016 args.push_back(mark.ToString() + "/" + mask.ToString());
1017 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +09001018
Hugo Benichi58f264a2020-10-16 18:16:05 +09001019 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +09001020}
1021
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001022bool Datapath::ModifyConnmarkRestore(IpFamily family,
1023 const std::string& chain,
1024 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001025 const std::string& iif,
1026 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001027 std::vector<std::string> args = {op, chain};
1028 if (!iif.empty()) {
1029 args.push_back("-i");
1030 args.push_back(iif);
1031 }
1032 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001033 mask.ToString(), "-w"});
1034 return ModifyIptables(family, "mangle", args);
1035}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001036
Hugo Benichi1af52392020-11-27 18:09:32 +09001037bool Datapath::ModifyConnmarkSave(IpFamily family,
1038 const std::string& chain,
1039 const std::string& op,
1040 const std::string& oif,
1041 Fwmark mask) {
1042 std::vector<std::string> args = {op, chain};
1043 if (!oif.empty()) {
1044 args.push_back("-o");
1045 args.push_back(oif);
1046 }
1047 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
1048 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +09001049 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001050}
1051
Hugo Benichi2a940542020-10-26 18:50:49 +09001052bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1053 const std::string& op,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001054 const std::string& ext_ifname,
1055 const std::string& int_ifname) {
1056 int ifindex = FindIfIndex(ext_ifname);
1057 if (ifindex == 0) {
1058 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
1059 return false;
1060 }
1061
Hugo Benichi2a940542020-10-26 18:50:49 +09001062 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001063 0 /*classid*/, Fwmark::FromIfIndex(ifindex),
1064 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001065}
1066
Hugo Benichi9be19b12020-08-14 15:33:40 +09001067bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
1068 const std::string& iif,
1069 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001070 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001071 0 /*classid*/, Fwmark::FromSource(source),
1072 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001073}
1074
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001075bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1076 TrafficSource source) {
1077 std::vector<std::string> args = {"-A",
1078 kApplyLocalSourceMarkChain,
1079 "-m",
1080 "mark",
1081 "--mark",
1082 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1083 "-j",
1084 "MARK",
1085 "--set-mark",
1086 Fwmark::FromSource(source).ToString() + "/" +
1087 kFwmarkAllSourcesMask.ToString(),
1088 "-w"};
1089 return ModifyIptables(IpFamily::Dual, "mangle", args);
1090}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001091
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001092bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1093 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001094 if (std::string(source.uid_name).empty() && source.classid == 0)
1095 return false;
1096
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001097 Fwmark mark = Fwmark::FromSource(source.source_type);
1098 if (source.is_on_vpn)
1099 mark = mark | kFwmarkRouteOnVpn;
1100
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001101 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1102 "" /*iif*/, source.uid_name, source.classid, mark,
1103 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001104}
1105
1106bool Datapath::ModifyFwmark(IpFamily family,
1107 const std::string& chain,
1108 const std::string& op,
1109 const std::string& iif,
1110 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001111 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001112 Fwmark mark,
1113 Fwmark mask,
1114 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001115 std::vector<std::string> args = {op, chain};
1116 if (!iif.empty()) {
1117 args.push_back("-i");
1118 args.push_back(iif);
1119 }
1120 if (!uid_name.empty()) {
1121 args.push_back("-m");
1122 args.push_back("owner");
1123 args.push_back("--uid-owner");
1124 args.push_back(uid_name);
1125 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001126 if (classid != 0) {
1127 args.push_back("-m");
1128 args.push_back("cgroup");
1129 args.push_back("--cgroup");
1130 args.push_back(base::StringPrintf("0x%08x", classid));
1131 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001132 args.push_back("-j");
1133 args.push_back("MARK");
1134 args.push_back("--set-mark");
1135 args.push_back(mark.ToString() + "/" + mask.ToString());
1136 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001137
Hugo Benichi58f264a2020-10-16 18:16:05 +09001138 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001139}
1140
Hugo Benichid82d8832020-08-14 10:05:03 +09001141bool Datapath::ModifyIpForwarding(IpFamily family,
1142 const std::string& op,
1143 const std::string& iif,
1144 const std::string& oif,
1145 bool log_failures) {
1146 if (iif.empty() && oif.empty()) {
1147 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1148 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001149 return false;
1150 }
1151
Hugo Benichid82d8832020-08-14 10:05:03 +09001152 std::vector<std::string> args = {op, "FORWARD"};
1153 if (!iif.empty()) {
1154 args.push_back("-i");
1155 args.push_back(iif);
1156 }
1157 if (!oif.empty()) {
1158 args.push_back("-o");
1159 args.push_back(oif);
1160 }
1161 args.push_back("-j");
1162 args.push_back("ACCEPT");
1163 args.push_back("-w");
1164
Hugo Benichi58f264a2020-10-16 18:16:05 +09001165 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001166}
1167
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001168bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1169 const std::string& op,
1170 const std::string& iif,
1171 Fwmark mark,
1172 Fwmark mask) {
1173 std::vector<std::string> args = {op, chain};
1174 if (!iif.empty()) {
1175 args.push_back("-i");
1176 args.push_back(iif);
1177 }
1178 if (mark.Value() != 0 && mask.Value() != 0) {
1179 args.push_back("-m");
1180 args.push_back("mark");
1181 args.push_back("--mark");
1182 args.push_back(mark.ToString() + "/" + mask.ToString());
1183 }
1184 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1185 return ModifyIptables(IpFamily::Dual, "mangle", args);
1186}
1187
1188bool Datapath::ModifyChain(IpFamily family,
1189 const std::string& table,
1190 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001191 const std::string& chain,
1192 bool log_failures) {
1193 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001194}
1195
1196bool Datapath::ModifyIptables(IpFamily family,
1197 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001198 const std::vector<std::string>& argv,
1199 bool log_failures) {
1200 switch (family) {
1201 case IPv4:
1202 case IPv6:
1203 case Dual:
1204 break;
1205 default:
1206 LOG(ERROR) << "Could not execute iptables command " << table
1207 << base::JoinString(argv, " ") << ": incorrect IP family "
1208 << family;
1209 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001210 }
1211
1212 bool success = true;
1213 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001214 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001215 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001216 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001217 return success;
1218}
1219
Hugo Benichid82d8832020-08-14 10:05:03 +09001220bool Datapath::StartIpForwarding(IpFamily family,
1221 const std::string& iif,
1222 const std::string& oif) {
1223 return ModifyIpForwarding(family, "-A", iif, oif);
1224}
1225
1226bool Datapath::StopIpForwarding(IpFamily family,
1227 const std::string& iif,
1228 const std::string& oif) {
1229 return ModifyIpForwarding(family, "-D", iif, oif);
1230}
1231
1232bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1233 const std::string& ifname2) {
1234 // Only start Ipv6 forwarding if -C returns false and it had not been
1235 // started yet.
1236 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1237 false /*log_failures*/) &&
1238 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1239 return false;
1240 }
1241
1242 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1243 false /*log_failures*/) &&
1244 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001245 RemoveIPv6Forwarding(ifname1, ifname2);
1246 return false;
1247 }
1248
1249 return true;
1250}
1251
1252void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1253 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001254 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1255 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001256}
1257
Garrick Evans3d97a392020-02-21 15:24:37 +09001258bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1259 uint32_t addr,
1260 uint32_t netmask) {
1261 struct rtentry route;
1262 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001263 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1264 SetSockaddrIn(&route.rt_dst, addr & netmask);
1265 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001266 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001267 return ModifyRtentry(SIOCADDRT, &route);
1268}
Garrick Evans3d97a392020-02-21 15:24:37 +09001269
Hugo Benichie8758b52020-04-03 14:49:01 +09001270bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1271 uint32_t addr,
1272 uint32_t netmask) {
1273 struct rtentry route;
1274 memset(&route, 0, sizeof(route));
1275 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1276 SetSockaddrIn(&route.rt_dst, addr & netmask);
1277 SetSockaddrIn(&route.rt_genmask, netmask);
1278 route.rt_flags = RTF_UP | RTF_GATEWAY;
1279 return ModifyRtentry(SIOCDELRT, &route);
1280}
1281
1282bool Datapath::AddIPv4Route(const std::string& ifname,
1283 uint32_t addr,
1284 uint32_t netmask) {
1285 struct rtentry route;
1286 memset(&route, 0, sizeof(route));
1287 SetSockaddrIn(&route.rt_dst, addr & netmask);
1288 SetSockaddrIn(&route.rt_genmask, netmask);
1289 char rt_dev[IFNAMSIZ];
1290 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1291 rt_dev[IFNAMSIZ - 1] = '\0';
1292 route.rt_dev = rt_dev;
1293 route.rt_flags = RTF_UP | RTF_GATEWAY;
1294 return ModifyRtentry(SIOCADDRT, &route);
1295}
1296
1297bool Datapath::DeleteIPv4Route(const std::string& ifname,
1298 uint32_t addr,
1299 uint32_t netmask) {
1300 struct rtentry route;
1301 memset(&route, 0, sizeof(route));
1302 SetSockaddrIn(&route.rt_dst, addr & netmask);
1303 SetSockaddrIn(&route.rt_genmask, netmask);
1304 char rt_dev[IFNAMSIZ];
1305 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1306 rt_dev[IFNAMSIZ - 1] = '\0';
1307 route.rt_dev = rt_dev;
1308 route.rt_flags = RTF_UP | RTF_GATEWAY;
1309 return ModifyRtentry(SIOCDELRT, &route);
1310}
1311
Taoyu Lia0727dc2020-09-24 19:54:59 +09001312bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001313 DCHECK(route);
1314 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001315 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001316 return false;
1317 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001318 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1319 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001320 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001321 return false;
1322 }
1323 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1324 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001325 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001326 return false;
1327 }
1328 return true;
1329}
1330
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001331bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1332 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1333 kArcAddr, kAdbServerPort, ifname,
1334 kLocalhostAddr, kAdbProxyTcpListenPort);
1335}
1336
1337void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1338 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1339 kArcAddr, kAdbServerPort, ifname,
1340 kLocalhostAddr, kAdbProxyTcpListenPort);
1341}
1342
1343bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1344 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1345 kAdbProxyTcpListenPort, ifname);
1346}
1347
1348void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1349 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1350 kAdbProxyTcpListenPort, ifname);
1351}
1352
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001353void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1354 if_nametoindex_[ifname] = ifindex;
1355}
1356
1357int Datapath::FindIfIndex(const std::string& ifname) {
1358 uint32_t ifindex = if_nametoindex(ifname.c_str());
1359 if (ifindex > 0) {
1360 if_nametoindex_[ifname] = ifindex;
1361 return ifindex;
1362 }
1363
1364 const auto it = if_nametoindex_.find(ifname);
1365 if (it != if_nametoindex_.end())
1366 return it->second;
1367
1368 return 0;
1369}
1370
Hugo Benichifcf81022020-12-04 11:01:37 +09001371std::ostream& operator<<(std::ostream& stream,
1372 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001373 stream << "{ pid: " << nsinfo.pid
1374 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001375 if (!nsinfo.outbound_ifname.empty()) {
1376 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1377 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001378 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1379 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001380 << ", peer_ifname: " << nsinfo.peer_ifname
1381 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1382 return stream;
1383}
1384
Garrick Evans3388a032020-03-24 11:25:55 +09001385} // namespace patchpanel