blob: e9d44b599e40425b8f416e2a778f38973d41991a [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
Hugo Benichiaba7e2e2021-02-22 14:47:11 +090069bool Ioctl(ioctl_t ioctl_h, unsigned long req, const char* arg) {
70 base::ScopedFD control_fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
71 if (!control_fd.is_valid()) {
72 PLOG(ERROR) << "Failed to create control socket for ioctl request=" << req;
73 return false;
74 }
75 if ((*ioctl_h)(control_fd.get(), req, arg) != 0) {
76 PLOG(ERROR) << "ioctl request=" << req << " failed";
77 return false;
78 }
79 return true;
80}
81
Garrick Evans8a067562020-05-11 12:47:30 +090082} // namespace
83
84std::string ArcVethHostName(const std::string& ifname) {
85 return PrefixIfname("veth", ifname);
86}
87
88std::string ArcBridgeName(const std::string& ifname) {
89 return PrefixIfname("arc_", ifname);
90}
91
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090092Datapath::Datapath(MinijailedProcessRunner* process_runner, Firewall* firewall)
93 : Datapath(process_runner, firewall, ioctl) {}
Garrick Evansc7ae82c2019-09-04 16:25:10 +090094
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090095Datapath::Datapath(MinijailedProcessRunner* process_runner,
96 Firewall* firewall,
97 ioctl_t ioctl_hook)
98 : process_runner_(process_runner), firewall_(firewall), ioctl_(ioctl_hook) {
Garrick Evansf0ab7132019-06-18 14:50:42 +090099 CHECK(process_runner_);
100}
101
Garrick Evans260ff302019-07-25 11:22:50 +0900102MinijailedProcessRunner& Datapath::runner() const {
103 return *process_runner_;
104}
105
Hugo Benichibf811c62020-09-07 17:30:45 +0900106void Datapath::Start() {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900107 // Restart from a clean iptables state in case of an unordered shutdown.
108 ResetIptables();
109
Hugo Benichibf811c62020-09-07 17:30:45 +0900110 // Enable IPv4 packet forwarding
111 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "1") != 0)
112 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
113 << " Guest connectivity will not work correctly.";
114
115 // Limit local port range: Android owns 47104-61000.
116 // TODO(garrick): The original history behind this tweak is gone. Some
117 // investigation is needed to see if it is still applicable.
118 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
119 "32768 47103") != 0)
120 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
121 << " apps may not work correctly.";
122
123 // Enable IPv6 packet forwarding
124 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0)
125 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
126 << " IPv6 functionality may be broken.";
127
Hugo Benichi58125d32020-09-09 11:25:45 +0900128 // Create a FORWARD ACCEPT rule for connections already established.
129 if (process_runner_->iptables(
130 "filter", {"-A", "FORWARD", "-m", "state", "--state",
131 "ESTABLISHED,RELATED", "-j", "ACCEPT", "-w"}) != 0)
Hugo Benichibf811c62020-09-07 17:30:45 +0900132 LOG(ERROR) << "Failed to install forwarding rule for established"
133 << " connections.";
134
135 // chromium:898210: Drop any locally originated traffic that would exit a
136 // physical interface with a source IPv4 address from the subnet of IPs used
137 // for VMs, containers, and connected namespaces This is needed to prevent
138 // packets leaking with an incorrect src IP when a local process binds to the
139 // wrong interface.
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900140 if (!ModifyChain(IpFamily::IPv4, "filter", "-N", kDropGuestIpv4PrefixChain))
141 LOG(ERROR) << "Failed to create " << kDropGuestIpv4PrefixChain
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900142 << " filter chain";
143 if (!ModifyIptables(IpFamily::IPv4, "filter",
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900144 {"-I", "OUTPUT", "-j", kDropGuestIpv4PrefixChain, "-w"}))
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900145 LOG(ERROR) << "Failed to set up jump rule from filter OUTPUT to "
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900146 << kDropGuestIpv4PrefixChain;
Hugo Benichibf811c62020-09-07 17:30:45 +0900147 for (const auto& oif : kPhysicalIfnamePrefixes) {
148 if (!AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
149 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
150 << kGuestIPv4Subnet << " exiting " << oif;
151 }
152
Hugo Benichi561fae42021-01-22 15:28:40 +0900153 // Set static SNAT rules for any IPv4 traffic originated from a guest (ARC,
154 // Crostini, ...) or a connected namespace.
155 // chromium:1050579: INVALID packets cannot be tracked by conntrack therefore
156 // need to be explicitly dropped as SNAT cannot be applied to them.
157 if (process_runner_->iptables(
158 "filter", {"-A", "FORWARD", "-m", "mark", "--mark", "1/1", "-m",
159 "state", "--state", "INVALID", "-j", "DROP", "-w"}) != 0)
160 LOG(ERROR) << "Failed to install SNAT mark rules.";
161 if (process_runner_->iptables(
162 "nat", {"-A", "POSTROUTING", "-m", "mark", "--mark", "1/1", "-j",
163 "MASQUERADE", "-w"}) != 0)
164 LOG(ERROR) << "Failed to install SNAT mark rules.";
Hugo Benichibf811c62020-09-07 17:30:45 +0900165 if (!AddOutboundIPv4SNATMark("vmtap+"))
Hugo Benichi561fae42021-01-22 15:28:40 +0900166 LOG(ERROR) << "Failed to set up NAT for TAP devices.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900167
Hugo Benichi2a940542020-10-26 18:50:49 +0900168 // Applies the routing tag saved in conntrack for any established connection
169 // for sockets created in the host network namespace.
Hugo Benichi1af52392020-11-27 18:09:32 +0900170 if (!ModifyConnmarkRestore(IpFamily::Dual, "OUTPUT", "-A", "" /*iif*/,
171 kFwmarkRoutingMask))
Hugo Benichi2a940542020-10-26 18:50:49 +0900172 LOG(ERROR) << "Failed to add OUTPUT CONNMARK restore rule";
Hugo Benichi155de002021-01-19 16:45:46 +0900173 // b/177787823 Also restore the routing tag after routing has taken place so
174 // that packets pre-tagged with the VPN routing tag are in sync with their
175 // associated CONNMARK routing tag. This is necessary to correctly identify
176 // packets exiting through the wrong interface.
177 if (!ModifyConnmarkRestore(IpFamily::Dual, "POSTROUTING", "-A", "" /*iif*/,
178 kFwmarkRoutingMask))
179 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK restore rule";
Hugo Benichi2a940542020-10-26 18:50:49 +0900180
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900181 // Set up a mangle chain used in OUTPUT for applying the fwmark TrafficSource
182 // tag and tagging the local traffic that should be routed through a VPN.
183 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyLocalSourceMarkChain))
184 LOG(ERROR) << "Failed to set up " << kApplyLocalSourceMarkChain
185 << " mangle chain";
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900186 if (!ModifyIptables(IpFamily::Dual, "mangle",
187 {"-A", "OUTPUT", "-j", kApplyLocalSourceMarkChain, "-w"}))
188 LOG(ERROR) << "Failed to attach " << kApplyLocalSourceMarkChain
189 << " to mangle OUTPUT";
190 // Create rules for tagging local sources with the source tag and the vpn
191 // policy tag.
192 for (const auto& source : kLocalSourceTypes) {
Hugo Benichi620202f2020-11-27 10:14:38 +0900193 if (!ModifyFwmarkLocalSourceTag("-A", source))
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900194 LOG(ERROR) << "Failed to create fwmark tagging rule for uid " << source
195 << " in " << kApplyLocalSourceMarkChain;
196 }
197 // Finally add a catch-all rule for tagging any remaining local sources with
198 // the SYSTEM source tag
199 if (!ModifyFwmarkDefaultLocalSourceTag("-A", TrafficSource::SYSTEM))
200 LOG(ERROR) << "Failed to set up rule tagging traffic with default source";
201
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900202 // Sets up a mangle chain used in OUTPUT and PREROUTING for tagging "user"
203 // traffic that should be routed through a VPN.
204 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kApplyVpnMarkChain))
205 LOG(ERROR) << "Failed to set up " << kApplyVpnMarkChain << " mangle chain";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900206 // All local outgoing traffic eligible to VPN routing should traverse the VPN
207 // marking chain.
208 if (!ModifyFwmarkVpnJumpRule("OUTPUT", "-A", "" /*iif*/, kFwmarkRouteOnVpn,
209 kFwmarkVpnMask))
210 LOG(ERROR) << "Failed to add jump rule to VPN chain in mangle OUTPUT chain";
211 // Any traffic that already has a routing tag applied is accepted.
212 if (!ModifyIptables(
213 IpFamily::Dual, "mangle",
214 {"-A", kApplyVpnMarkChain, "-m", "mark", "!", "--mark",
215 "0x0/" + kFwmarkRoutingMask.ToString(), "-j", "ACCEPT", "-w"}))
216 LOG(ERROR) << "Failed to add ACCEPT rule to VPN tagging chain for marked "
217 "connections";
Hugo Benichi155de002021-01-19 16:45:46 +0900218
219 // Sets up a mangle chain used in POSTROUTING for checking consistency between
220 // the routing tag and the output interface.
221 if (!ModifyChain(IpFamily::Dual, "mangle", "-N", kCheckRoutingMarkChain))
222 LOG(ERROR) << "Failed to set up " << kCheckRoutingMarkChain
223 << " mangle chain";
Hugo Benichi155de002021-01-19 16:45:46 +0900224 // b/177787823 If it already exists, the routing tag of any traffic exiting an
225 // interface (physical or VPN) must match the routing tag of that interface.
226 if (!ModifyIptables(IpFamily::Dual, "mangle",
227 {"-A", "POSTROUTING", "-m", "mark", "!", "--mark",
228 "0x0/" + kFwmarkRoutingMask.ToString(), "-j",
229 kCheckRoutingMarkChain, "-w"}))
230 LOG(ERROR) << "Failed to add POSTROUTING jump rule to "
231 << kCheckRoutingMarkChain;
Hugo Benichi52a64992021-01-28 17:47:33 +0900232
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900233 // b/178331695 Sets up a nat chain used in OUTPUT for redirecting DNS queries
234 // of system services. When a VPN is connected, a query routed through a
235 // physical network is redirected to the primary nameserver of that network.
236 if (!ModifyChain(IpFamily::IPv4, "nat", "-N", kRedirectDnsChain))
237 LOG(ERROR) << "Failed to set up " << kRedirectDnsChain << " nat chain";
238
Hugo Benichi52a64992021-01-28 17:47:33 +0900239 // b/176260499: on 4.4 kernel, the following connmark rules are observed to
240 // incorrectly cause neighbor discovery icmpv6 packets to be dropped. Add
241 // these rules to bypass connmark rule for those packets.
242 for (const auto& type : kNeighborDiscoveryTypes) {
243 if (!ModifyIptables(IpFamily::IPv6, "mangle",
244 {"-I", "OUTPUT", "-p", "icmpv6", "--icmpv6-type", type,
245 "-j", "ACCEPT", "-w"}))
246 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
247 << " packets in OUTPUT";
248 if (!ModifyIptables(IpFamily::IPv6, "mangle",
249 {"-I", kCheckRoutingMarkChain, "-p", "icmpv6",
250 "--icmpv6-type", type, "-j", "RETURN", "-w"}))
251 LOG(ERROR) << "Failed to set up connmark bypass rule for " << type
252 << " packets in " << kCheckRoutingMarkChain;
253 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900254}
255
256void Datapath::Stop() {
Hugo Benichibf811c62020-09-07 17:30:45 +0900257 // Restore original local port range.
258 // TODO(garrick): The original history behind this tweak is gone. Some
259 // investigation is needed to see if it is still applicable.
260 if (process_runner_->sysctl_w("net.ipv4.ip_local_port_range",
261 "32768 61000") != 0)
262 LOG(ERROR) << "Failed to restore local port range";
263
264 // Disable packet forwarding
265 if (process_runner_->sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0)
266 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
267
268 if (process_runner_->sysctl_w("net.ipv4.ip_forward", "0") != 0)
269 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900270
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900271 ResetIptables();
272}
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900273
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900274void Datapath::ResetIptables() {
275 // If it exists, remove jump rules from a built-in chain to a custom routing
276 // or tagging chain.
277 ModifyIptables(IpFamily::IPv4, "filter",
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900278 {"-D", "OUTPUT", "-j", kDropGuestIpv4PrefixChain, "-w"},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900279 false /*log_failures*/);
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900280
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900281 // Flush chains used for routing and fwmark tagging. Also delete additional
282 // chains made by patchpanel. Chains used by permission broker (nat
283 // PREROUTING, filter INPUT) and chains used for traffic counters (mangle
284 // {rx,tx}_{<iface>, vpn}) are not flushed.
285 static struct {
286 IpFamily family;
287 std::string table;
288 std::string chain;
289 bool should_delete;
290 } resetOps[] = {
291 {IpFamily::Dual, "filter", "FORWARD", false},
292 {IpFamily::Dual, "mangle", "FORWARD", false},
293 {IpFamily::Dual, "mangle", "INPUT", false},
294 {IpFamily::Dual, "mangle", "OUTPUT", false},
295 {IpFamily::Dual, "mangle", "POSTROUTING", false},
296 {IpFamily::Dual, "mangle", "PREROUTING", false},
297 {IpFamily::Dual, "mangle", kApplyLocalSourceMarkChain, true},
298 {IpFamily::Dual, "mangle", kApplyVpnMarkChain, true},
299 {IpFamily::Dual, "mangle", kCheckRoutingMarkChain, true},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900300 {IpFamily::IPv4, "filter", kDropGuestIpv4PrefixChain, true},
301 {IpFamily::IPv4, "nat", kRedirectDnsChain, true},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900302 {IpFamily::IPv4, "nat", "POSTROUTING", false},
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900303 {IpFamily::IPv4, "nat", "OUTPUT", false},
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900304 };
305 for (const auto& op : resetOps) {
306 // Chains to delete are custom chains and will not exist the first time
307 // patchpanel starts after boot. Skip flushing and delete these chains if
308 // they do not exist to avoid logging spurious error messages.
309 if (op.should_delete && !ModifyChain(op.family, op.table, "-L", op.chain,
310 false /*log_failures*/))
311 continue;
Hugo Benichi155de002021-01-19 16:45:46 +0900312
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900313 if (!ModifyChain(op.family, op.table, "-F", op.chain))
314 LOG(ERROR) << "Failed to flush " << op.chain << " chain in table "
315 << op.table;
Hugo Benichi2a940542020-10-26 18:50:49 +0900316
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900317 if (op.should_delete && !ModifyChain(op.family, op.table, "-X", op.chain))
318 LOG(ERROR) << "Failed to delete " << op.chain << " chain in table "
319 << op.table;
Hugo Benichi3a9162b2020-09-09 15:47:40 +0900320 }
Hugo Benichibf811c62020-09-07 17:30:45 +0900321}
322
Hugo Benichi33860d72020-07-09 16:34:01 +0900323bool Datapath::NetnsAttachName(const std::string& netns_name, pid_t netns_pid) {
324 // Try first to delete any netns with name |netns_name| in case patchpanel
325 // did not exit cleanly.
326 if (process_runner_->ip_netns_delete(netns_name, false /*log_failures*/) == 0)
327 LOG(INFO) << "Deleted left over network namespace name " << netns_name;
328 return process_runner_->ip_netns_attach(netns_name, netns_pid) == 0;
329}
330
331bool Datapath::NetnsDeleteName(const std::string& netns_name) {
332 return process_runner_->ip_netns_delete(netns_name) == 0;
333}
334
Garrick Evans8a949dc2019-07-18 16:17:53 +0900335bool Datapath::AddBridge(const std::string& ifname,
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900336 uint32_t ipv4_addr,
337 uint32_t ipv4_prefix_len) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900338 if (!Ioctl(ioctl_, SIOCBRADDBR, ifname.c_str())) {
339 LOG(ERROR) << "Failed to create bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900340 return false;
341 }
342
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900343 // Configure the persistent Chrome OS bridge interface with static IP.
Garrick Evans6f4fa3a2020-02-10 16:15:09 +0900344 if (process_runner_->ip(
345 "addr", "add",
346 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
347 IPv4AddressToString(Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
348 "dev", ifname}) != 0) {
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900349 RemoveBridge(ifname);
350 return false;
351 }
352
353 if (process_runner_->ip("link", "set", {ifname, "up"}) != 0) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900354 RemoveBridge(ifname);
355 return false;
356 }
357
358 // See nat.conf in chromeos-nat-init for the rest of the NAT setup rules.
Hugo Benichie8758b52020-04-03 14:49:01 +0900359 if (!AddOutboundIPv4SNATMark(ifname)) {
Garrick Evans8a949dc2019-07-18 16:17:53 +0900360 RemoveBridge(ifname);
361 return false;
362 }
363
364 return true;
365}
366
367void Datapath::RemoveBridge(const std::string& ifname) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900368 RemoveOutboundIPv4SNATMark(ifname);
Garrick Evans7a1a9ee2020-01-28 11:03:57 +0900369 process_runner_->ip("link", "set", {ifname, "down"});
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900370 if (!Ioctl(ioctl_, SIOCBRDELBR, ifname.c_str()))
371 LOG(ERROR) << "Failed to destroy bridge " << ifname;
Garrick Evans8a949dc2019-07-18 16:17:53 +0900372}
373
Garrick Evans621ed262019-11-13 12:28:43 +0900374bool Datapath::AddToBridge(const std::string& br_ifname,
375 const std::string& ifname) {
Hugo Benichiaba7e2e2021-02-22 14:47:11 +0900376 struct ifreq ifr;
377 memset(&ifr, 0, sizeof(ifr));
378 strncpy(ifr.ifr_name, br_ifname.c_str(), sizeof(ifr.ifr_name));
379 ifr.ifr_ifindex = FindIfIndex(ifname);
380
381 if (!Ioctl(ioctl_, SIOCBRADDIF, reinterpret_cast<const char*>(&ifr))) {
382 LOG(ERROR) << "Failed to add " << ifname << " to bridge " << br_ifname;
383 return false;
384 }
385
386 return true;
Garrick Evans621ed262019-11-13 12:28:43 +0900387}
388
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900389std::string Datapath::AddTAP(const std::string& name,
Garrick Evans621ed262019-11-13 12:28:43 +0900390 const MacAddress* mac_addr,
391 const SubnetAddress* ipv4_addr,
Garrick Evans4f9f5572019-11-26 10:25:16 +0900392 const std::string& user) {
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900393 base::ScopedFD dev(open(kTunDev, O_RDWR | O_NONBLOCK));
394 if (!dev.is_valid()) {
395 PLOG(ERROR) << "Failed to open " << kTunDev;
396 return "";
397 }
398
399 struct ifreq ifr;
400 memset(&ifr, 0, sizeof(ifr));
401 strncpy(ifr.ifr_name, name.empty() ? kDefaultIfname : name.c_str(),
402 sizeof(ifr.ifr_name));
403 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
404
405 // If a template was given as the name, ifr_name will be updated with the
406 // actual interface name.
407 if ((*ioctl_)(dev.get(), TUNSETIFF, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900408 PLOG(ERROR) << "Failed to create tap interface " << name;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900409 return "";
410 }
411 const char* ifname = ifr.ifr_name;
412
413 if ((*ioctl_)(dev.get(), TUNSETPERSIST, 1) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900414 PLOG(ERROR) << "Failed to persist the interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900415 return "";
416 }
417
Garrick Evans4f9f5572019-11-26 10:25:16 +0900418 if (!user.empty()) {
419 uid_t uid = -1;
420 if (!brillo::userdb::GetUserInfo(user, &uid, nullptr)) {
421 PLOG(ERROR) << "Unable to look up UID for " << user;
422 RemoveTAP(ifname);
423 return "";
424 }
425 if ((*ioctl_)(dev.get(), TUNSETOWNER, uid) != 0) {
426 PLOG(ERROR) << "Failed to set owner " << uid << " of tap interface "
427 << ifname;
428 RemoveTAP(ifname);
429 return "";
430 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900431 }
432
Hugo Benichib9b93fe2019-10-25 23:36:01 +0900433 // Create control socket for configuring the interface.
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900434 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
435 if (!sock.is_valid()) {
436 PLOG(ERROR) << "Failed to create control socket for tap interface "
Garrick Evans621ed262019-11-13 12:28:43 +0900437 << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900438 RemoveTAP(ifname);
439 return "";
440 }
441
Garrick Evans621ed262019-11-13 12:28:43 +0900442 if (ipv4_addr) {
443 struct sockaddr_in* addr =
444 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_addr);
445 addr->sin_family = AF_INET;
446 addr->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Address());
447 if ((*ioctl_)(sock.get(), SIOCSIFADDR, &ifr) != 0) {
448 PLOG(ERROR) << "Failed to set ip address for vmtap interface " << ifname
449 << " {" << ipv4_addr->ToCidrString() << "}";
450 RemoveTAP(ifname);
451 return "";
452 }
453
454 struct sockaddr_in* netmask =
455 reinterpret_cast<struct sockaddr_in*>(&ifr.ifr_netmask);
456 netmask->sin_family = AF_INET;
457 netmask->sin_addr.s_addr = static_cast<in_addr_t>(ipv4_addr->Netmask());
458 if ((*ioctl_)(sock.get(), SIOCSIFNETMASK, &ifr) != 0) {
459 PLOG(ERROR) << "Failed to set netmask for vmtap interface " << ifname
460 << " {" << ipv4_addr->ToCidrString() << "}";
461 RemoveTAP(ifname);
462 return "";
463 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900464 }
465
Garrick Evans621ed262019-11-13 12:28:43 +0900466 if (mac_addr) {
467 struct sockaddr* hwaddr = &ifr.ifr_hwaddr;
468 hwaddr->sa_family = ARPHRD_ETHER;
469 memcpy(&hwaddr->sa_data, mac_addr, sizeof(*mac_addr));
470 if ((*ioctl_)(sock.get(), SIOCSIFHWADDR, &ifr) != 0) {
471 PLOG(ERROR) << "Failed to set mac address for vmtap interface " << ifname
472 << " {" << MacAddressToString(*mac_addr) << "}";
473 RemoveTAP(ifname);
474 return "";
475 }
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900476 }
477
478 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900479 PLOG(ERROR) << "Failed to get flags for tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900480 RemoveTAP(ifname);
481 return "";
482 }
483
484 ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
485 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) != 0) {
Garrick Evans621ed262019-11-13 12:28:43 +0900486 PLOG(ERROR) << "Failed to enable tap interface " << ifname;
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900487 RemoveTAP(ifname);
488 return "";
489 }
490
491 return ifname;
492}
493
494void Datapath::RemoveTAP(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900495 process_runner_->ip("tuntap", "del", {ifname, "mode", "tap"});
Garrick Evansc7ae82c2019-09-04 16:25:10 +0900496}
497
Hugo Benichi33860d72020-07-09 16:34:01 +0900498bool Datapath::ConnectVethPair(pid_t netns_pid,
499 const std::string& netns_name,
Hugo Benichi76675592020-04-08 14:29:57 +0900500 const std::string& veth_ifname,
501 const std::string& peer_ifname,
502 const MacAddress& remote_mac_addr,
503 uint32_t remote_ipv4_addr,
504 uint32_t remote_ipv4_prefix_len,
505 bool remote_multicast_flag) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900506 // Set up the virtual pair across the current namespace and |netns_name|.
507 if (!AddVirtualInterfacePair(netns_name, veth_ifname, peer_ifname)) {
508 LOG(ERROR) << "Failed to create veth pair " << veth_ifname << ","
509 << peer_ifname;
510 return false;
511 }
512
513 // Configure the remote veth in namespace |netns_name|.
Hugo Benichi76675592020-04-08 14:29:57 +0900514 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900515 ScopedNS ns(netns_pid, ScopedNS::Type::Network);
Hugo Benichi33860d72020-07-09 16:34:01 +0900516 if (!ns.IsValid() && netns_pid != kTestPID) {
Hugo Benichi76675592020-04-08 14:29:57 +0900517 LOG(ERROR)
518 << "Cannot create virtual link -- invalid container namespace?";
519 return false;
520 }
521
Hugo Benichi76675592020-04-08 14:29:57 +0900522 if (!ConfigureInterface(peer_ifname, remote_mac_addr, remote_ipv4_addr,
523 remote_ipv4_prefix_len, true /* link up */,
524 remote_multicast_flag)) {
525 LOG(ERROR) << "Failed to configure interface " << peer_ifname;
526 RemoveInterface(peer_ifname);
527 return false;
528 }
529 }
530
Hugo Benichi76675592020-04-08 14:29:57 +0900531 if (!ToggleInterface(veth_ifname, true /*up*/)) {
532 LOG(ERROR) << "Failed to bring up interface " << veth_ifname;
533 RemoveInterface(veth_ifname);
534 return false;
535 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900536
Hugo Benichi76675592020-04-08 14:29:57 +0900537 return true;
538}
539
Hugo Benichi33860d72020-07-09 16:34:01 +0900540bool Datapath::AddVirtualInterfacePair(const std::string& netns_name,
541 const std::string& veth_ifname,
Garrick Evans2470caa2020-03-04 14:15:41 +0900542 const std::string& peer_ifname) {
Hugo Benichi33860d72020-07-09 16:34:01 +0900543 return process_runner_->ip("link", "add",
544 {veth_ifname, "type", "veth", "peer", "name",
545 peer_ifname, "netns", netns_name}) == 0;
Garrick Evans2470caa2020-03-04 14:15:41 +0900546}
Garrick Evans54861622019-07-19 09:05:09 +0900547
Garrick Evans2470caa2020-03-04 14:15:41 +0900548bool Datapath::ToggleInterface(const std::string& ifname, bool up) {
549 const std::string link = up ? "up" : "down";
550 return process_runner_->ip("link", "set", {ifname, link}) == 0;
551}
Garrick Evans54861622019-07-19 09:05:09 +0900552
Garrick Evans2470caa2020-03-04 14:15:41 +0900553bool Datapath::ConfigureInterface(const std::string& ifname,
554 const MacAddress& mac_addr,
555 uint32_t ipv4_addr,
556 uint32_t ipv4_prefix_len,
557 bool up,
558 bool enable_multicast) {
559 const std::string link = up ? "up" : "down";
560 const std::string multicast = enable_multicast ? "on" : "off";
561 return (process_runner_->ip(
562 "addr", "add",
563 {IPv4AddressToCidrString(ipv4_addr, ipv4_prefix_len), "brd",
564 IPv4AddressToString(
565 Ipv4BroadcastAddr(ipv4_addr, ipv4_prefix_len)),
566 "dev", ifname}) == 0) &&
567 (process_runner_->ip("link", "set",
568 {
569 "dev",
570 ifname,
571 link,
572 "addr",
573 MacAddressToString(mac_addr),
574 "multicast",
575 multicast,
576 }) == 0);
Garrick Evans54861622019-07-19 09:05:09 +0900577}
578
579void Datapath::RemoveInterface(const std::string& ifname) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900580 process_runner_->ip("link", "delete", {ifname}, false /*log_failures*/);
Garrick Evans54861622019-07-19 09:05:09 +0900581}
582
Hugo Benichi321f23b2020-09-25 15:42:05 +0900583bool Datapath::AddSourceIPv4DropRule(const std::string& oif,
584 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900585 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900586 "filter", {"-I", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
587 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900588}
589
590bool Datapath::RemoveSourceIPv4DropRule(const std::string& oif,
591 const std::string& src_ip) {
Hugo Benichi91ee09f2020-12-03 22:24:22 +0900592 return process_runner_->iptables(
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900593 "filter", {"-D", kDropGuestIpv4PrefixChain, "-o", oif, "-s",
594 src_ip, "-j", "DROP", "-w"}) == 0;
Hugo Benichi321f23b2020-09-25 15:42:05 +0900595}
596
Hugo Benichifcf81022020-12-04 11:01:37 +0900597bool Datapath::StartRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900598 // Veth interface configuration and client routing configuration:
599 // - attach a name to the client namespace.
600 // - create veth pair across the current namespace and the client namespace.
601 // - configure IPv4 address on remote veth inside client namespace.
602 // - configure IPv4 address on local veth inside host namespace.
603 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichifcf81022020-12-04 11:01:37 +0900604 if (!NetnsAttachName(nsinfo.netns_name, nsinfo.pid)) {
605 LOG(ERROR) << "Failed to attach name " << nsinfo.netns_name
606 << " to namespace pid " << nsinfo.pid;
Hugo Benichi7c342672020-09-08 09:18:14 +0900607 return false;
608 }
609
Hugo Benichifcf81022020-12-04 11:01:37 +0900610 if (!ConnectVethPair(
611 nsinfo.pid, nsinfo.netns_name, nsinfo.host_ifname, nsinfo.peer_ifname,
612 nsinfo.peer_mac_addr, nsinfo.peer_subnet->AddressAtOffset(1),
613 nsinfo.peer_subnet->PrefixLength(), false /* enable_multicast */)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900614 LOG(ERROR) << "Failed to create veth pair for"
615 " namespace pid "
Hugo Benichifcf81022020-12-04 11:01:37 +0900616 << nsinfo.pid;
617 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900618 return false;
619 }
620
Hugo Benichifcf81022020-12-04 11:01:37 +0900621 if (!ConfigureInterface(nsinfo.host_ifname, nsinfo.peer_mac_addr,
622 nsinfo.peer_subnet->AddressAtOffset(0),
623 nsinfo.peer_subnet->PrefixLength(),
624 true /* link up */, false /* enable_multicast */)) {
625 LOG(ERROR) << "Cannot configure host interface " << nsinfo.host_ifname;
626 RemoveInterface(nsinfo.host_ifname);
627 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900628 return false;
629 }
630
631 {
Hugo Benichi0781d402021-02-22 13:43:11 +0900632 ScopedNS ns(nsinfo.pid, ScopedNS::Type::Network);
Hugo Benichifcf81022020-12-04 11:01:37 +0900633 if (!ns.IsValid() && nsinfo.pid != kTestPID) {
634 LOG(ERROR) << "Invalid namespace pid " << nsinfo.pid;
635 RemoveInterface(nsinfo.host_ifname);
636 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900637 return false;
638 }
639
Hugo Benichifcf81022020-12-04 11:01:37 +0900640 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0), INADDR_ANY,
641 INADDR_ANY)) {
642 LOG(ERROR) << "Failed to add default /0 route to " << nsinfo.host_ifname
643 << " inside namespace pid " << nsinfo.pid;
644 RemoveInterface(nsinfo.host_ifname);
645 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900646 return false;
647 }
648 }
649
650 // Host namespace routing configuration
651 // - ingress: add route to client subnet via |host_ifname|.
652 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
653 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
654 // Note that by default unsolicited ingress traffic is not forwarded to the
655 // client namespace unless the client specifically set port forwarding
656 // through permission_broker DBus APIs.
657 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
658 // both ways between client namespace and other guest containers and VMs.
Hugo Benichifcf81022020-12-04 11:01:37 +0900659 uint32_t netmask = Ipv4Netmask(nsinfo.peer_subnet->PrefixLength());
660 if (!AddIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
661 nsinfo.peer_subnet->BaseAddress(), netmask)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900662 LOG(ERROR) << "Failed to set route to client namespace";
Hugo Benichifcf81022020-12-04 11:01:37 +0900663 RemoveInterface(nsinfo.host_ifname);
664 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900665 return false;
666 }
667
Hugo Benichi7c342672020-09-08 09:18:14 +0900668 // TODO(b/161508179) Do not rely on legacy fwmark 1 for SNAT.
Hugo Benichifcf81022020-12-04 11:01:37 +0900669 if (!AddOutboundIPv4SNATMark(nsinfo.host_ifname)) {
Hugo Benichi7c342672020-09-08 09:18:14 +0900670 LOG(ERROR) << "Failed to set SNAT for traffic"
671 " outgoing from "
Hugo Benichifcf81022020-12-04 11:01:37 +0900672 << nsinfo.host_ifname;
673 RemoveInterface(nsinfo.host_ifname);
674 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
675 nsinfo.peer_subnet->BaseAddress(), netmask);
676 StopIpForwarding(IpFamily::IPv4, "", nsinfo.host_ifname);
677 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900678 return false;
679 }
680
Hugo Benichi93306e52020-12-04 16:08:00 +0900681 StartRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
682 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
683 nsinfo.route_on_vpn);
684
Hugo Benichi7c342672020-09-08 09:18:14 +0900685 return true;
686}
687
Hugo Benichifcf81022020-12-04 11:01:37 +0900688void Datapath::StopRoutingNamespace(const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +0900689 StopRoutingDevice(nsinfo.outbound_ifname, nsinfo.host_ifname,
690 nsinfo.peer_subnet->AddressAtOffset(0), nsinfo.source,
691 nsinfo.route_on_vpn);
Hugo Benichifcf81022020-12-04 11:01:37 +0900692 RemoveInterface(nsinfo.host_ifname);
Hugo Benichifcf81022020-12-04 11:01:37 +0900693 RemoveOutboundIPv4SNATMark(nsinfo.host_ifname);
694 DeleteIPv4Route(nsinfo.peer_subnet->AddressAtOffset(0),
695 nsinfo.peer_subnet->BaseAddress(),
696 Ipv4Netmask(nsinfo.peer_subnet->PrefixLength()));
697 NetnsDeleteName(nsinfo.netns_name);
Hugo Benichi7c342672020-09-08 09:18:14 +0900698}
699
Hugo Benichi8d622b52020-08-13 15:24:12 +0900700void Datapath::StartRoutingDevice(const std::string& ext_ifname,
701 const std::string& int_ifname,
702 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900703 TrafficSource source,
704 bool route_on_vpn) {
705 if (source == TrafficSource::ARC && !ext_ifname.empty() &&
Hugo Benichibfc49112020-12-14 12:54:44 +0900706 int_ipv4_addr != 0 &&
Hugo Benichi8d622b52020-08-13 15:24:12 +0900707 !AddInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr)))
708 LOG(ERROR) << "Failed to configure ingress traffic rules for " << ext_ifname
709 << "->" << int_ifname;
710
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900711 if (!StartIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900712 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "->"
713 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900714
Hugo Benichifa97b3b2020-10-06 22:45:26 +0900715 if (!StartIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname))
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900716 LOG(ERROR) << "Failed to enable IP forwarding for " << ext_ifname << "<-"
717 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900718
Hugo Benichi2a940542020-10-26 18:50:49 +0900719 if (!ModifyFwmarkSourceTag("-A", int_ifname, source))
720 LOG(ERROR) << "Failed to add PREROUTING fwmark tagging rule for source "
721 << source << " for " << int_ifname;
722
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900723 if (!ext_ifname.empty()) {
724 // If |ext_ifname| is not null, mark egress traffic with the
725 // fwmark routing tag corresponding to |ext_ifname|.
Hugo Benichi2a940542020-10-26 18:50:49 +0900726 if (!ModifyFwmarkRoutingTag("PREROUTING", "-A", ext_ifname, int_ifname))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900727 LOG(ERROR) << "Failed to add PREROUTING fwmark routing tag for "
728 << ext_ifname << "<-" << int_ifname;
729 } else {
730 // Otherwise if ext_ifname is null, set up a CONNMARK restore rule in
731 // PREROUTING to apply any fwmark routing tag saved for the current
732 // connection, and rely on implicit routing to the default logical network
733 // otherwise.
Hugo Benichi1af52392020-11-27 18:09:32 +0900734 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", int_ifname,
735 kFwmarkRoutingMask))
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900736 LOG(ERROR) << "Failed to add PREROUTING CONNMARK restore rule for "
737 << int_ifname;
Hugo Benichi8d622b52020-08-13 15:24:12 +0900738
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900739 // Forwarded traffic from downstream virtual devices routed to the system
Hugo Benichi93306e52020-12-04 16:08:00 +0900740 // default network is eligible to be routed through a VPN if |route_on_vpn|
741 // is true.
742 if (route_on_vpn &&
743 !ModifyFwmarkVpnJumpRule("PREROUTING", "-A", int_ifname, {}, {}))
Hugo Benichi3ef370b2020-11-16 19:07:17 +0900744 LOG(ERROR) << "Failed to add jump rule to VPN chain for " << int_ifname;
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900745 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900746}
747
748void Datapath::StopRoutingDevice(const std::string& ext_ifname,
749 const std::string& int_ifname,
750 uint32_t int_ipv4_addr,
Hugo Benichi93306e52020-12-04 16:08:00 +0900751 TrafficSource source,
752 bool route_on_vpn) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900753 if (source == TrafficSource::ARC && !ext_ifname.empty() && int_ipv4_addr != 0)
Hugo Benichi8d622b52020-08-13 15:24:12 +0900754 RemoveInboundIPv4DNAT(ext_ifname, IPv4AddressToString(int_ipv4_addr));
Hugo Benichic6ae67c2020-08-14 15:02:13 +0900755 StopIpForwarding(IpFamily::IPv4, ext_ifname, int_ifname);
756 StopIpForwarding(IpFamily::IPv4, int_ifname, ext_ifname);
Hugo Benichi9be19b12020-08-14 15:33:40 +0900757 ModifyFwmarkSourceTag("-D", int_ifname, source);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900758 if (!ext_ifname.empty()) {
Hugo Benichi2a940542020-10-26 18:50:49 +0900759 ModifyFwmarkRoutingTag("PREROUTING", "-D", ext_ifname, int_ifname);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900760 } else {
Hugo Benichi1af52392020-11-27 18:09:32 +0900761 ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", int_ifname,
762 kFwmarkRoutingMask);
Hugo Benichi93306e52020-12-04 16:08:00 +0900763 if (route_on_vpn)
764 ModifyFwmarkVpnJumpRule("PREROUTING", "-D", int_ifname, {}, {});
Hugo Benichiaf9d8a72020-08-26 13:28:13 +0900765 }
Hugo Benichi8d622b52020-08-13 15:24:12 +0900766}
767
Garrick Evansf0ab7132019-06-18 14:50:42 +0900768bool Datapath::AddInboundIPv4DNAT(const std::string& ifname,
769 const std::string& ipv4_addr) {
770 // Direct ingress IP traffic to existing sockets.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900771 if (process_runner_->iptables(
772 "nat", {"-A", "PREROUTING", "-i", ifname, "-m", "socket",
773 "--nowildcard", "-j", "ACCEPT", "-w"}) != 0)
Garrick Evansf0ab7132019-06-18 14:50:42 +0900774 return false;
775
776 // Direct ingress TCP & UDP traffic to ARC interface for new connections.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900777 if (process_runner_->iptables(
778 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
779 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900780 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
781 return false;
782 }
Garrick Evans8e8e3472020-01-23 14:03:50 +0900783 if (process_runner_->iptables(
784 "nat", {"-A", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
785 "--to-destination", ipv4_addr, "-w"}) != 0) {
Garrick Evansf0ab7132019-06-18 14:50:42 +0900786 RemoveInboundIPv4DNAT(ifname, ipv4_addr);
787 return false;
788 }
789
790 return true;
791}
792
793void Datapath::RemoveInboundIPv4DNAT(const std::string& ifname,
794 const std::string& ipv4_addr) {
Garrick Evans8e8e3472020-01-23 14:03:50 +0900795 process_runner_->iptables(
796 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "udp", "-j", "DNAT",
797 "--to-destination", ipv4_addr, "-w"});
798 process_runner_->iptables(
799 "nat", {"-D", "PREROUTING", "-i", ifname, "-p", "tcp", "-j", "DNAT",
800 "--to-destination", ipv4_addr, "-w"});
801 process_runner_->iptables(
802 "nat", {"-D", "PREROUTING", "-i", ifname, "-m", "socket", "--nowildcard",
803 "-j", "ACCEPT", "-w"});
Garrick Evansf0ab7132019-06-18 14:50:42 +0900804}
805
Hugo Benichie8758b52020-04-03 14:49:01 +0900806bool Datapath::AddOutboundIPv4SNATMark(const std::string& ifname) {
807 return process_runner_->iptables(
808 "mangle", {"-A", "PREROUTING", "-i", ifname, "-j", "MARK",
Hugo Benichi6c445322020-08-12 16:46:19 +0900809 "--set-mark", "1/1", "-w"}) == 0;
Hugo Benichie8758b52020-04-03 14:49:01 +0900810}
811
812void Datapath::RemoveOutboundIPv4SNATMark(const std::string& ifname) {
813 process_runner_->iptables("mangle", {"-D", "PREROUTING", "-i", ifname, "-j",
Hugo Benichi6c445322020-08-12 16:46:19 +0900814 "MARK", "--set-mark", "1/1", "-w"});
Hugo Benichie8758b52020-04-03 14:49:01 +0900815}
816
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900817bool Datapath::AddRedirectDnsRule(const std::string& ifname,
818 const std::string dns_ipv4_addr) {
819 bool success = true;
820 success &= RemoveRedirectDnsRule(ifname);
821 // Use Insert operation to ensure that the new DNS address is used first.
822 success &= ModifyRedirectDnsDNATRule("-I", "tcp", ifname, dns_ipv4_addr);
823 success &= ModifyRedirectDnsDNATRule("-I", "udp", ifname, dns_ipv4_addr);
824 physical_dns_addresses_[ifname] = dns_ipv4_addr;
825 return success;
826}
827
828bool Datapath::RemoveRedirectDnsRule(const std::string& ifname) {
829 const auto it = physical_dns_addresses_.find(ifname);
830 if (it == physical_dns_addresses_.end())
831 return true;
832
833 bool success = true;
834 success &= ModifyRedirectDnsDNATRule("-D", "tcp", ifname, it->second);
835 success &= ModifyRedirectDnsDNATRule("-D", "udp", ifname, it->second);
836 physical_dns_addresses_.erase(it);
837 return success;
838}
839
840bool Datapath::ModifyRedirectDnsDNATRule(const std::string& op,
841 const std::string& protocol,
842 const std::string& ifname,
843 const std::string& dns_ipv4_addr) {
844 std::vector<std::string> args = {op,
845 kRedirectDnsChain,
846 "-p",
847 protocol,
848 "--dport",
849 "53",
850 "-o",
851 ifname,
852 "-j",
853 "DNAT",
854 "--to-destination",
855 dns_ipv4_addr,
856 "-w"};
857 return process_runner_->iptables("nat", args) != 0;
858}
859
860bool Datapath::ModifyRedirectDnsJumpRule(const std::string& op) {
861 std::vector<std::string> args = {
862 op,
863 "OUTPUT",
864 "-m",
865 "mark",
866 "!",
867 "--mark",
868 kFwmarkRouteOnVpn.ToString() + "/" + kFwmarkVpnMask.ToString(),
869 "-j",
870 kRedirectDnsChain,
871 "-w"};
872 return process_runner_->iptables("nat", args) != 0;
873}
874
Garrick Evans664a82f2019-12-17 12:18:05 +0900875bool Datapath::MaskInterfaceFlags(const std::string& ifname,
876 uint16_t on,
877 uint16_t off) {
Taoyu Li90c13912019-11-26 17:56:54 +0900878 base::ScopedFD sock(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
879 if (!sock.is_valid()) {
880 PLOG(ERROR) << "Failed to create control socket";
881 return false;
882 }
883 ifreq ifr;
884 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", ifname.c_str());
885 if ((*ioctl_)(sock.get(), SIOCGIFFLAGS, &ifr) < 0) {
886 PLOG(WARNING) << "ioctl() failed to get interface flag on " << ifname;
887 return false;
888 }
Garrick Evans664a82f2019-12-17 12:18:05 +0900889 ifr.ifr_flags |= on;
890 ifr.ifr_flags &= ~off;
Taoyu Li90c13912019-11-26 17:56:54 +0900891 if ((*ioctl_)(sock.get(), SIOCSIFFLAGS, &ifr) < 0) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900892 PLOG(WARNING) << "ioctl() failed to set flag 0x" << std::hex << on
893 << " unset flag 0x" << std::hex << off << " on " << ifname;
Taoyu Li90c13912019-11-26 17:56:54 +0900894 return false;
895 }
896 return true;
897}
898
Garrick Evans260ff302019-07-25 11:22:50 +0900899bool Datapath::AddIPv6HostRoute(const std::string& ifname,
900 const std::string& ipv6_addr,
901 int ipv6_prefix_len) {
902 std::string ipv6_addr_cidr =
903 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
904
Garrick Evans8e8e3472020-01-23 14:03:50 +0900905 return process_runner_->ip6("route", "replace",
906 {ipv6_addr_cidr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900907}
908
909void Datapath::RemoveIPv6HostRoute(const std::string& ifname,
910 const std::string& ipv6_addr,
911 int ipv6_prefix_len) {
912 std::string ipv6_addr_cidr =
913 ipv6_addr + "/" + std::to_string(ipv6_prefix_len);
914
Garrick Evans8e8e3472020-01-23 14:03:50 +0900915 process_runner_->ip6("route", "del", {ipv6_addr_cidr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900916}
917
Taoyu Lia0727dc2020-09-24 19:54:59 +0900918bool Datapath::AddIPv6Address(const std::string& ifname,
919 const std::string& ipv6_addr) {
920 return process_runner_->ip6("addr", "add", {ipv6_addr, "dev", ifname}) == 0;
Garrick Evans260ff302019-07-25 11:22:50 +0900921}
922
Taoyu Lia0727dc2020-09-24 19:54:59 +0900923void Datapath::RemoveIPv6Address(const std::string& ifname,
924 const std::string& ipv6_addr) {
925 process_runner_->ip6("addr", "del", {ipv6_addr, "dev", ifname});
Garrick Evans260ff302019-07-25 11:22:50 +0900926}
927
Hugo Benichi76be34a2020-08-26 22:35:54 +0900928void Datapath::StartConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900929 int ifindex = FindIfIndex(ext_ifname);
930 if (ifindex != 0 && !ModifyIptables(IpFamily::Dual, "mangle",
931 {"-A", kCheckRoutingMarkChain, "-o",
932 ext_ifname, "-m", "mark", "!", "--mark",
933 Fwmark::FromIfIndex(ifindex).ToString() +
934 "/" + kFwmarkRoutingMask.ToString(),
935 "-j", "DROP", "-w"}))
936 LOG(ERROR) << "Could not set fwmark routing filter rule for " << ext_ifname;
937
Hugo Benichi1af52392020-11-27 18:09:32 +0900938 // Set in CONNMARK the routing tag associated with |ext_ifname|.
Hugo Benichi76be34a2020-08-26 22:35:54 +0900939 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-A", ext_ifname))
940 LOG(ERROR) << "Could not start connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900941 // Save in CONNMARK the source tag for egress traffic of this connection.
942 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-A", ext_ifname,
943 kFwmarkAllSourcesMask))
944 LOG(ERROR) << "Failed to add POSTROUTING CONNMARK rule for saving fwmark "
945 "source tag on "
946 << ext_ifname;
947 // Restore from CONNMARK the source tag for ingress traffic of this connection
948 // (returned traffic).
949 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-A", ext_ifname,
950 kFwmarkAllSourcesMask))
951 LOG(ERROR) << "Could not setup fwmark source tagging rule for return "
952 "traffic received on "
953 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900954}
955
956void Datapath::StopConnectionPinning(const std::string& ext_ifname) {
Hugo Benichi155de002021-01-19 16:45:46 +0900957 int ifindex = FindIfIndex(ext_ifname);
958 if (ifindex != 0 && !ModifyIptables(IpFamily::Dual, "mangle",
959 {"-D", kCheckRoutingMarkChain, "-o",
960 ext_ifname, "-m", "mark", "!", "--mark",
961 Fwmark::FromIfIndex(ifindex).ToString() +
962 "/" + kFwmarkRoutingMask.ToString(),
963 "-j", "DROP", "-w"}))
964 LOG(ERROR) << "Could not remove fwmark routing filter rule for "
965 << ext_ifname;
966
Hugo Benichi76be34a2020-08-26 22:35:54 +0900967 if (!ModifyConnmarkSetPostrouting(IpFamily::Dual, "-D", ext_ifname))
968 LOG(ERROR) << "Could not stop connection pinning on " << ext_ifname;
Hugo Benichi1af52392020-11-27 18:09:32 +0900969 if (!ModifyConnmarkSave(IpFamily::Dual, "POSTROUTING", "-D", ext_ifname,
970 kFwmarkAllSourcesMask))
971 LOG(ERROR) << "Could not remove POSTROUTING CONNMARK rule for saving "
972 "fwmark source tag on "
973 << ext_ifname;
974 if (!ModifyConnmarkRestore(IpFamily::Dual, "PREROUTING", "-D", ext_ifname,
975 kFwmarkAllSourcesMask))
976 LOG(ERROR) << "Could not remove fwmark source tagging rule for return "
977 "traffic received on "
978 << ext_ifname;
Hugo Benichi76be34a2020-08-26 22:35:54 +0900979}
980
Hugo Benichi2a940542020-10-26 18:50:49 +0900981void Datapath::StartVpnRouting(const std::string& vpn_ifname) {
Hugo Benichi891275e2020-12-16 10:35:34 +0900982 if (process_runner_->iptables("nat", {"-A", "POSTROUTING", "-o", vpn_ifname,
983 "-j", "MASQUERADE", "-w"}) != 0)
984 LOG(ERROR) << "Could not set up SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi2a940542020-10-26 18:50:49 +0900985 StartConnectionPinning(vpn_ifname);
986 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-A", vpn_ifname, ""))
987 LOG(ERROR) << "Failed to set up VPN set-mark rule for " << vpn_ifname;
Hugo Benichibfc49112020-12-14 12:54:44 +0900988 if (vpn_ifname != kArcBridge)
989 StartRoutingDevice(vpn_ifname, kArcBridge, 0 /*no inbound DNAT */,
990 TrafficSource::ARC, true /* route_on_vpn */);
Hugo Benichi1e0656f2021-02-15 15:43:38 +0900991 if (!ModifyRedirectDnsJumpRule("-A"))
992 LOG(ERROR) << "Failed to set jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +0900993}
994
995void Datapath::StopVpnRouting(const std::string& vpn_ifname) {
Hugo Benichibfc49112020-12-14 12:54:44 +0900996 if (vpn_ifname != kArcBridge)
997 StopRoutingDevice(vpn_ifname, kArcBridge, 0 /* no inbound DNAT */,
998 TrafficSource::ARC, false /* route_on_vpn */);
Hugo Benichi2a940542020-10-26 18:50:49 +0900999 if (!ModifyFwmarkRoutingTag(kApplyVpnMarkChain, "-D", vpn_ifname, ""))
1000 LOG(ERROR) << "Failed to remove VPN set-mark rule for " << vpn_ifname;
1001 StopConnectionPinning(vpn_ifname);
Hugo Benichi891275e2020-12-16 10:35:34 +09001002 if (process_runner_->iptables("nat", {"-D", "POSTROUTING", "-o", vpn_ifname,
1003 "-j", "MASQUERADE", "-w"}) != 0)
1004 LOG(ERROR) << "Could not stop SNAT for traffic outgoing " << vpn_ifname;
Hugo Benichi1e0656f2021-02-15 15:43:38 +09001005 if (!ModifyRedirectDnsJumpRule("-D"))
1006 LOG(ERROR) << "Failed to remove jump rule to " << kRedirectDnsChain;
Hugo Benichi2a940542020-10-26 18:50:49 +09001007}
1008
Hugo Benichi76be34a2020-08-26 22:35:54 +09001009bool Datapath::ModifyConnmarkSetPostrouting(IpFamily family,
1010 const std::string& op,
1011 const std::string& oif) {
Hugo Benichi76be34a2020-08-26 22:35:54 +09001012 int ifindex = FindIfIndex(oif);
1013 if (ifindex == 0) {
1014 PLOG(ERROR) << "if_nametoindex(" << oif << ") failed";
1015 return false;
1016 }
1017
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001018 return ModifyConnmarkSet(family, "POSTROUTING", op, oif,
1019 Fwmark::FromIfIndex(ifindex), kFwmarkRoutingMask);
1020}
1021
1022bool Datapath::ModifyConnmarkSet(IpFamily family,
1023 const std::string& chain,
1024 const std::string& op,
1025 const std::string& oif,
1026 Fwmark mark,
1027 Fwmark mask) {
1028 if (chain != kApplyVpnMarkChain && (chain != "POSTROUTING" || oif.empty())) {
1029 LOG(ERROR) << "Invalid arguments chain=" << chain << " oif=" << oif;
1030 return false;
1031 }
1032
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001033 std::vector<std::string> args = {op, chain};
1034 if (!oif.empty()) {
1035 args.push_back("-o");
1036 args.push_back(oif);
1037 }
1038 args.push_back("-j");
1039 args.push_back("CONNMARK");
1040 args.push_back("--set-mark");
1041 args.push_back(mark.ToString() + "/" + mask.ToString());
1042 args.push_back("-w");
Hugo Benichi76be34a2020-08-26 22:35:54 +09001043
Hugo Benichi58f264a2020-10-16 18:16:05 +09001044 return ModifyIptables(family, "mangle", args);
Hugo Benichi76be34a2020-08-26 22:35:54 +09001045}
1046
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001047bool Datapath::ModifyConnmarkRestore(IpFamily family,
1048 const std::string& chain,
1049 const std::string& op,
Hugo Benichi1af52392020-11-27 18:09:32 +09001050 const std::string& iif,
1051 Fwmark mask) {
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001052 std::vector<std::string> args = {op, chain};
1053 if (!iif.empty()) {
1054 args.push_back("-i");
1055 args.push_back(iif);
1056 }
1057 args.insert(args.end(), {"-j", "CONNMARK", "--restore-mark", "--mask",
Hugo Benichi1af52392020-11-27 18:09:32 +09001058 mask.ToString(), "-w"});
1059 return ModifyIptables(family, "mangle", args);
1060}
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001061
Hugo Benichi1af52392020-11-27 18:09:32 +09001062bool Datapath::ModifyConnmarkSave(IpFamily family,
1063 const std::string& chain,
1064 const std::string& op,
1065 const std::string& oif,
1066 Fwmark mask) {
1067 std::vector<std::string> args = {op, chain};
1068 if (!oif.empty()) {
1069 args.push_back("-o");
1070 args.push_back(oif);
1071 }
1072 args.insert(args.end(), {"-j", "CONNMARK", "--save-mark", "--mask",
1073 mask.ToString(), "-w"});
Hugo Benichi58f264a2020-10-16 18:16:05 +09001074 return ModifyIptables(family, "mangle", args);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001075}
1076
Hugo Benichi2a940542020-10-26 18:50:49 +09001077bool Datapath::ModifyFwmarkRoutingTag(const std::string& chain,
1078 const std::string& op,
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001079 const std::string& ext_ifname,
1080 const std::string& int_ifname) {
1081 int ifindex = FindIfIndex(ext_ifname);
1082 if (ifindex == 0) {
1083 PLOG(ERROR) << "if_nametoindex(" << ext_ifname << ") failed";
1084 return false;
1085 }
1086
Hugo Benichi2a940542020-10-26 18:50:49 +09001087 return ModifyFwmark(IpFamily::Dual, chain, op, int_ifname, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001088 0 /*classid*/, Fwmark::FromIfIndex(ifindex),
1089 kFwmarkRoutingMask);
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001090}
1091
Hugo Benichi9be19b12020-08-14 15:33:40 +09001092bool Datapath::ModifyFwmarkSourceTag(const std::string& op,
1093 const std::string& iif,
1094 TrafficSource source) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001095 return ModifyFwmark(IpFamily::Dual, "PREROUTING", op, iif, "" /*uid_name*/,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001096 0 /*classid*/, Fwmark::FromSource(source),
1097 kFwmarkAllSourcesMask);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001098}
1099
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001100bool Datapath::ModifyFwmarkDefaultLocalSourceTag(const std::string& op,
1101 TrafficSource source) {
1102 std::vector<std::string> args = {"-A",
1103 kApplyLocalSourceMarkChain,
1104 "-m",
1105 "mark",
1106 "--mark",
1107 "0x0/" + kFwmarkAllSourcesMask.ToString(),
1108 "-j",
1109 "MARK",
1110 "--set-mark",
1111 Fwmark::FromSource(source).ToString() + "/" +
1112 kFwmarkAllSourcesMask.ToString(),
1113 "-w"};
1114 return ModifyIptables(IpFamily::Dual, "mangle", args);
1115}
Hugo Benichi9be19b12020-08-14 15:33:40 +09001116
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001117bool Datapath::ModifyFwmarkLocalSourceTag(const std::string& op,
1118 const LocalSourceSpecs& source) {
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001119 if (std::string(source.uid_name).empty() && source.classid == 0)
1120 return false;
1121
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001122 Fwmark mark = Fwmark::FromSource(source.source_type);
1123 if (source.is_on_vpn)
1124 mark = mark | kFwmarkRouteOnVpn;
1125
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001126 return ModifyFwmark(IpFamily::Dual, kApplyLocalSourceMarkChain, op,
1127 "" /*iif*/, source.uid_name, source.classid, mark,
1128 kFwmarkPolicyMask);
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001129}
1130
1131bool Datapath::ModifyFwmark(IpFamily family,
1132 const std::string& chain,
1133 const std::string& op,
1134 const std::string& iif,
1135 const std::string& uid_name,
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001136 uint32_t classid,
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001137 Fwmark mark,
1138 Fwmark mask,
1139 bool log_failures) {
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001140 std::vector<std::string> args = {op, chain};
1141 if (!iif.empty()) {
1142 args.push_back("-i");
1143 args.push_back(iif);
1144 }
1145 if (!uid_name.empty()) {
1146 args.push_back("-m");
1147 args.push_back("owner");
1148 args.push_back("--uid-owner");
1149 args.push_back(uid_name);
1150 }
Hugo Benichi7e3b1fc2020-11-19 15:47:05 +09001151 if (classid != 0) {
1152 args.push_back("-m");
1153 args.push_back("cgroup");
1154 args.push_back("--cgroup");
1155 args.push_back(base::StringPrintf("0x%08x", classid));
1156 }
Hugo Benichi3a9162b2020-09-09 15:47:40 +09001157 args.push_back("-j");
1158 args.push_back("MARK");
1159 args.push_back("--set-mark");
1160 args.push_back(mark.ToString() + "/" + mask.ToString());
1161 args.push_back("-w");
Hugo Benichi9be19b12020-08-14 15:33:40 +09001162
Hugo Benichi58f264a2020-10-16 18:16:05 +09001163 return ModifyIptables(family, "mangle", args, log_failures);
Hugo Benichi9be19b12020-08-14 15:33:40 +09001164}
1165
Hugo Benichid82d8832020-08-14 10:05:03 +09001166bool Datapath::ModifyIpForwarding(IpFamily family,
1167 const std::string& op,
1168 const std::string& iif,
1169 const std::string& oif,
1170 bool log_failures) {
1171 if (iif.empty() && oif.empty()) {
1172 LOG(ERROR) << "Cannot change IP forwarding with no input or output "
1173 "interface specified";
Garrick Evans260ff302019-07-25 11:22:50 +09001174 return false;
1175 }
1176
Hugo Benichid82d8832020-08-14 10:05:03 +09001177 std::vector<std::string> args = {op, "FORWARD"};
1178 if (!iif.empty()) {
1179 args.push_back("-i");
1180 args.push_back(iif);
1181 }
1182 if (!oif.empty()) {
1183 args.push_back("-o");
1184 args.push_back(oif);
1185 }
1186 args.push_back("-j");
1187 args.push_back("ACCEPT");
1188 args.push_back("-w");
1189
Hugo Benichi58f264a2020-10-16 18:16:05 +09001190 return ModifyIptables(family, "filter", args, log_failures);
Hugo Benichid82d8832020-08-14 10:05:03 +09001191}
1192
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001193bool Datapath::ModifyFwmarkVpnJumpRule(const std::string& chain,
1194 const std::string& op,
1195 const std::string& iif,
1196 Fwmark mark,
1197 Fwmark mask) {
1198 std::vector<std::string> args = {op, chain};
1199 if (!iif.empty()) {
1200 args.push_back("-i");
1201 args.push_back(iif);
1202 }
1203 if (mark.Value() != 0 && mask.Value() != 0) {
1204 args.push_back("-m");
1205 args.push_back("mark");
1206 args.push_back("--mark");
1207 args.push_back(mark.ToString() + "/" + mask.ToString());
1208 }
1209 args.insert(args.end(), {"-j", kApplyVpnMarkChain, "-w"});
1210 return ModifyIptables(IpFamily::Dual, "mangle", args);
1211}
1212
1213bool Datapath::ModifyChain(IpFamily family,
1214 const std::string& table,
1215 const std::string& op,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001216 const std::string& chain,
1217 bool log_failures) {
1218 return ModifyIptables(family, table, {op, chain, "-w"}, log_failures);
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001219}
1220
1221bool Datapath::ModifyIptables(IpFamily family,
1222 const std::string& table,
Hugo Benichi58f264a2020-10-16 18:16:05 +09001223 const std::vector<std::string>& argv,
1224 bool log_failures) {
1225 switch (family) {
1226 case IPv4:
1227 case IPv6:
1228 case Dual:
1229 break;
1230 default:
1231 LOG(ERROR) << "Could not execute iptables command " << table
1232 << base::JoinString(argv, " ") << ": incorrect IP family "
1233 << family;
1234 return false;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001235 }
1236
1237 bool success = true;
1238 if (family & IpFamily::IPv4)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001239 success &= process_runner_->iptables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001240 if (family & IpFamily::IPv6)
Hugo Benichi58f264a2020-10-16 18:16:05 +09001241 success &= process_runner_->ip6tables(table, argv, log_failures) == 0;
Hugo Benichi3ef370b2020-11-16 19:07:17 +09001242 return success;
1243}
1244
Hugo Benichid82d8832020-08-14 10:05:03 +09001245bool Datapath::StartIpForwarding(IpFamily family,
1246 const std::string& iif,
1247 const std::string& oif) {
1248 return ModifyIpForwarding(family, "-A", iif, oif);
1249}
1250
1251bool Datapath::StopIpForwarding(IpFamily family,
1252 const std::string& iif,
1253 const std::string& oif) {
1254 return ModifyIpForwarding(family, "-D", iif, oif);
1255}
1256
1257bool Datapath::AddIPv6Forwarding(const std::string& ifname1,
1258 const std::string& ifname2) {
1259 // Only start Ipv6 forwarding if -C returns false and it had not been
1260 // started yet.
1261 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname1, ifname2,
1262 false /*log_failures*/) &&
1263 !StartIpForwarding(IpFamily::IPv6, ifname1, ifname2)) {
1264 return false;
1265 }
1266
1267 if (!ModifyIpForwarding(IpFamily::IPv6, "-C", ifname2, ifname1,
1268 false /*log_failures*/) &&
1269 !StartIpForwarding(IpFamily::IPv6, ifname2, ifname1)) {
Garrick Evans260ff302019-07-25 11:22:50 +09001270 RemoveIPv6Forwarding(ifname1, ifname2);
1271 return false;
1272 }
1273
1274 return true;
1275}
1276
1277void Datapath::RemoveIPv6Forwarding(const std::string& ifname1,
1278 const std::string& ifname2) {
Hugo Benichid82d8832020-08-14 10:05:03 +09001279 StopIpForwarding(IpFamily::IPv6, ifname1, ifname2);
1280 StopIpForwarding(IpFamily::IPv6, ifname2, ifname1);
Garrick Evans260ff302019-07-25 11:22:50 +09001281}
1282
Garrick Evans3d97a392020-02-21 15:24:37 +09001283bool Datapath::AddIPv4Route(uint32_t gateway_addr,
1284 uint32_t addr,
1285 uint32_t netmask) {
1286 struct rtentry route;
1287 memset(&route, 0, sizeof(route));
Hugo Benichie8758b52020-04-03 14:49:01 +09001288 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1289 SetSockaddrIn(&route.rt_dst, addr & netmask);
1290 SetSockaddrIn(&route.rt_genmask, netmask);
Garrick Evans3d97a392020-02-21 15:24:37 +09001291 route.rt_flags = RTF_UP | RTF_GATEWAY;
Hugo Benichie8758b52020-04-03 14:49:01 +09001292 return ModifyRtentry(SIOCADDRT, &route);
1293}
Garrick Evans3d97a392020-02-21 15:24:37 +09001294
Hugo Benichie8758b52020-04-03 14:49:01 +09001295bool Datapath::DeleteIPv4Route(uint32_t gateway_addr,
1296 uint32_t addr,
1297 uint32_t netmask) {
1298 struct rtentry route;
1299 memset(&route, 0, sizeof(route));
1300 SetSockaddrIn(&route.rt_gateway, gateway_addr);
1301 SetSockaddrIn(&route.rt_dst, addr & netmask);
1302 SetSockaddrIn(&route.rt_genmask, netmask);
1303 route.rt_flags = RTF_UP | RTF_GATEWAY;
1304 return ModifyRtentry(SIOCDELRT, &route);
1305}
1306
1307bool Datapath::AddIPv4Route(const std::string& ifname,
1308 uint32_t addr,
1309 uint32_t netmask) {
1310 struct rtentry route;
1311 memset(&route, 0, sizeof(route));
1312 SetSockaddrIn(&route.rt_dst, addr & netmask);
1313 SetSockaddrIn(&route.rt_genmask, netmask);
1314 char rt_dev[IFNAMSIZ];
1315 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1316 rt_dev[IFNAMSIZ - 1] = '\0';
1317 route.rt_dev = rt_dev;
1318 route.rt_flags = RTF_UP | RTF_GATEWAY;
1319 return ModifyRtentry(SIOCADDRT, &route);
1320}
1321
1322bool Datapath::DeleteIPv4Route(const std::string& ifname,
1323 uint32_t addr,
1324 uint32_t netmask) {
1325 struct rtentry route;
1326 memset(&route, 0, sizeof(route));
1327 SetSockaddrIn(&route.rt_dst, addr & netmask);
1328 SetSockaddrIn(&route.rt_genmask, netmask);
1329 char rt_dev[IFNAMSIZ];
1330 strncpy(rt_dev, ifname.c_str(), IFNAMSIZ);
1331 rt_dev[IFNAMSIZ - 1] = '\0';
1332 route.rt_dev = rt_dev;
1333 route.rt_flags = RTF_UP | RTF_GATEWAY;
1334 return ModifyRtentry(SIOCDELRT, &route);
1335}
1336
Taoyu Lia0727dc2020-09-24 19:54:59 +09001337bool Datapath::ModifyRtentry(ioctl_req_t op, struct rtentry* route) {
Hugo Benichie8758b52020-04-03 14:49:01 +09001338 DCHECK(route);
1339 if (op != SIOCADDRT && op != SIOCDELRT) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001340 LOG(ERROR) << "Invalid operation " << op << " for rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001341 return false;
1342 }
Hugo Benichie8758b52020-04-03 14:49:01 +09001343 base::ScopedFD fd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1344 if (!fd.is_valid()) {
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001345 PLOG(ERROR) << "Failed to create socket for adding rtentry " << *route;
Hugo Benichie8758b52020-04-03 14:49:01 +09001346 return false;
1347 }
1348 if (HANDLE_EINTR(ioctl_(fd.get(), op, route)) != 0) {
1349 std::string opname = op == SIOCADDRT ? "add" : "delete";
Andreea Costinas34aa7a92020-08-04 10:36:10 +02001350 PLOG(ERROR) << "Failed to " << opname << " rtentry " << *route;
Garrick Evans3d97a392020-02-21 15:24:37 +09001351 return false;
1352 }
1353 return true;
1354}
1355
Jason Jeremy Imana7273a32020-08-04 11:25:31 +09001356bool Datapath::AddAdbPortForwardRule(const std::string& ifname) {
1357 return firewall_->AddIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1358 kArcAddr, kAdbServerPort, ifname,
1359 kLocalhostAddr, kAdbProxyTcpListenPort);
1360}
1361
1362void Datapath::DeleteAdbPortForwardRule(const std::string& ifname) {
1363 firewall_->DeleteIpv4ForwardRule(patchpanel::ModifyPortRuleRequest::TCP,
1364 kArcAddr, kAdbServerPort, ifname,
1365 kLocalhostAddr, kAdbProxyTcpListenPort);
1366}
1367
1368bool Datapath::AddAdbPortAccessRule(const std::string& ifname) {
1369 return firewall_->AddAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1370 kAdbProxyTcpListenPort, ifname);
1371}
1372
1373void Datapath::DeleteAdbPortAccessRule(const std::string& ifname) {
1374 firewall_->DeleteAcceptRules(patchpanel::ModifyPortRuleRequest::TCP,
1375 kAdbProxyTcpListenPort, ifname);
1376}
1377
Hugo Benichiaf9d8a72020-08-26 13:28:13 +09001378void Datapath::SetIfnameIndex(const std::string& ifname, int ifindex) {
1379 if_nametoindex_[ifname] = ifindex;
1380}
1381
1382int Datapath::FindIfIndex(const std::string& ifname) {
1383 uint32_t ifindex = if_nametoindex(ifname.c_str());
1384 if (ifindex > 0) {
1385 if_nametoindex_[ifname] = ifindex;
1386 return ifindex;
1387 }
1388
1389 const auto it = if_nametoindex_.find(ifname);
1390 if (it != if_nametoindex_.end())
1391 return it->second;
1392
1393 return 0;
1394}
1395
Hugo Benichifcf81022020-12-04 11:01:37 +09001396std::ostream& operator<<(std::ostream& stream,
1397 const ConnectedNamespace& nsinfo) {
Hugo Benichi93306e52020-12-04 16:08:00 +09001398 stream << "{ pid: " << nsinfo.pid
1399 << ", source: " << TrafficSourceName(nsinfo.source);
Hugo Benichifcf81022020-12-04 11:01:37 +09001400 if (!nsinfo.outbound_ifname.empty()) {
1401 stream << ", outbound_ifname: " << nsinfo.outbound_ifname;
1402 }
Hugo Benichi93306e52020-12-04 16:08:00 +09001403 stream << ", route_on_vpn: " << nsinfo.route_on_vpn
1404 << ", host_ifname: " << nsinfo.host_ifname
Hugo Benichifcf81022020-12-04 11:01:37 +09001405 << ", peer_ifname: " << nsinfo.peer_ifname
1406 << ", peer_subnet: " << nsinfo.peer_subnet->ToCidrString() << '}';
1407 return stream;
1408}
1409
Garrick Evans3388a032020-03-24 11:25:55 +09001410} // namespace patchpanel