1 /*
2 * Copyright 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * binder_test.cpp - unit tests for netd binder RPCs.
17 */
18
19 #include <cerrno>
20 #include <chrono>
21 #include <cinttypes>
22 #include <condition_variable>
23 #include <cstdint>
24 #include <cstdlib>
25 #include <iostream>
26 #include <mutex>
27 #include <regex>
28 #include <set>
29 #include <string>
30 #include <thread>
31 #include <vector>
32
33 #include <dirent.h>
34 #include <fcntl.h>
35 #include <ifaddrs.h>
36 #include <linux/if.h>
37 #include <linux/if_tun.h>
38 #include <net/ethernet.h>
39 #include <net/if.h>
40 #include <netdb.h>
41 #include <netinet/in.h>
42 #include <netinet/tcp.h>
43 #include <openssl/base64.h>
44 #include <sys/socket.h>
45 #include <sys/types.h>
46
47 #include <android-base/file.h>
48 #include <android-base/format.h>
49 #include <android-base/macros.h>
50 #include <android-base/scopeguard.h>
51 #include <android-base/stringprintf.h>
52 #include <android-base/strings.h>
53 #include <android/multinetwork.h>
54 #include <binder/IPCThreadState.h>
55 #include <bpf/BpfMap.h>
56 #include <bpf/BpfUtils.h>
57 #include <com/android/internal/net/BnOemNetdUnsolicitedEventListener.h>
58 #include <com/android/internal/net/IOemNetd.h>
59 #include <cutils/multiuser.h>
60 #include <gtest/gtest.h>
61 #include <netdbpf/bpf_shared.h>
62 #include <netutils/ifc.h>
63 #include <utils/Errors.h>
64 #include "Fwmark.h"
65 #include "InterfaceController.h"
66 #include "NetdClient.h"
67 #include "NetdConstants.h"
68 #include "NetworkController.h"
69 #include "RouteController.h"
70 #include "SockDiag.h"
71 #include "TestUnsolService.h"
72 #include "XfrmController.h"
73 #include "android/net/INetd.h"
74 #include "binder/IServiceManager.h"
75 #include "netdutils/InternetAddresses.h"
76 #include "netdutils/Stopwatch.h"
77 #include "netdutils/Syscalls.h"
78 #include "netid_client.h" // NETID_UNSET
79 #include "test_utils.h"
80 #include "tun_interface.h"
81
82 #define IP6TABLES_PATH "/system/bin/ip6tables"
83 #define IPTABLES_PATH "/system/bin/iptables"
84 #define RAW_TABLE "raw"
85 #define MANGLE_TABLE "mangle"
86 #define FILTER_TABLE "filter"
87 #define NAT_TABLE "nat"
88
89 namespace binder = android::binder;
90
91 using android::IBinder;
92 using android::IServiceManager;
93 using android::sp;
94 using android::String16;
95 using android::String8;
96 using android::base::Join;
97 using android::base::make_scope_guard;
98 using android::base::ReadFdToString;
99 using android::base::ReadFileToString;
100 using android::base::StartsWith;
101 using android::base::StringPrintf;
102 using android::base::Trim;
103 using android::base::unique_fd;
104 using android::net::INetd;
105 using android::net::InterfaceConfigurationParcel;
106 using android::net::InterfaceController;
107 using android::net::MarkMaskParcel;
108 using android::net::NativeNetworkConfig;
109 using android::net::NativeNetworkType;
110 using android::net::NativeVpnType;
111 using android::net::RULE_PRIORITY_BYPASSABLE_VPN;
112 using android::net::RULE_PRIORITY_DEFAULT_NETWORK;
113 using android::net::RULE_PRIORITY_EXPLICIT_NETWORK;
114 using android::net::RULE_PRIORITY_OUTPUT_INTERFACE;
115 using android::net::RULE_PRIORITY_PROHIBIT_NON_VPN;
116 using android::net::RULE_PRIORITY_SECURE_VPN;
117 using android::net::RULE_PRIORITY_TETHERING;
118 using android::net::RULE_PRIORITY_UID_DEFAULT_NETWORK;
119 using android::net::RULE_PRIORITY_UID_DEFAULT_UNREACHABLE;
120 using android::net::RULE_PRIORITY_UID_EXPLICIT_NETWORK;
121 using android::net::RULE_PRIORITY_UID_IMPLICIT_NETWORK;
122 using android::net::RULE_PRIORITY_VPN_FALLTHROUGH;
123 using android::net::SockDiag;
124 using android::net::TetherOffloadRuleParcel;
125 using android::net::TetherStatsParcel;
126 using android::net::TunInterface;
127 using android::net::UidRangeParcel;
128 using android::net::UidRanges;
129 using android::net::netd::aidl::NativeUidRangeConfig;
130 using android::netdutils::IPAddress;
131 using android::netdutils::ScopedAddrinfo;
132 using android::netdutils::sSyscalls;
133 using android::netdutils::Stopwatch;
134
135 static const char* IP_RULE_V4 = "-4";
136 static const char* IP_RULE_V6 = "-6";
137 static const int TEST_NETID1 = 65501;
138 static const int TEST_NETID2 = 65502;
139 static const int TEST_NETID3 = 65503;
140 static const int TEST_NETID4 = 65504;
141 static const int TEST_DUMP_NETID = 65123;
142 static const char* DNSMASQ = "dnsmasq";
143
144 // Use maximum reserved appId for applications to avoid conflict with existing
145 // uids.
146 static const int TEST_UID1 = 99999;
147 static const int TEST_UID2 = 99998;
148 static const int TEST_UID3 = 99997;
149 static const int TEST_UID4 = 99996;
150 static const int TEST_UID5 = 99995;
151 static const int TEST_UID6 = 99994;
152
153 constexpr int BASE_UID = AID_USER_OFFSET * 5;
154
155 static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
156 static const std::string ESP_ALLOW_RULE("esp");
157
158 static const in6_addr V6_ADDR = {
159 {// 2001:db8:cafe::8888
160 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0x88}}};
161
162 class NetdBinderTest : public ::testing::Test {
163 public:
NetdBinderTest()164 NetdBinderTest() {
165 sp<IServiceManager> sm = android::defaultServiceManager();
166 sp<IBinder> binder = sm->getService(String16("netd"));
167 if (binder != nullptr) {
168 mNetd = android::interface_cast<INetd>(binder);
169 }
170 }
171
SetUp()172 void SetUp() override {
173 ASSERT_NE(nullptr, mNetd.get());
174 }
175
TearDown()176 void TearDown() override {
177 mNetd->networkDestroy(TEST_NETID1);
178 mNetd->networkDestroy(TEST_NETID2);
179 mNetd->networkDestroy(TEST_NETID3);
180 mNetd->networkDestroy(TEST_NETID4);
181 setNetworkForProcess(NETID_UNSET);
182 // Restore default network
183 if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
184 }
185
186 bool allocateIpSecResources(bool expectOk, int32_t* spi);
187
188 // Static because setting up the tun interface takes about 40ms.
SetUpTestCase()189 static void SetUpTestCase() {
190 ASSERT_EQ(0, sTun.init());
191 ASSERT_EQ(0, sTun2.init());
192 ASSERT_EQ(0, sTun3.init());
193 ASSERT_EQ(0, sTun4.init());
194 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
195 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
196 ASSERT_LE(sTun3.name().size(), static_cast<size_t>(IFNAMSIZ));
197 ASSERT_LE(sTun4.name().size(), static_cast<size_t>(IFNAMSIZ));
198 }
199
TearDownTestCase()200 static void TearDownTestCase() {
201 // Closing the socket removes the interface and IP addresses.
202 sTun.destroy();
203 sTun2.destroy();
204 sTun3.destroy();
205 sTun4.destroy();
206 }
207
208 static void fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
209 unique_fd* acceptedSocket);
210
211 void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
212 int fallthroughNetId = TEST_NETID1);
213
214 void createAndSetDefaultNetwork(int netId, const std::string& interface,
215 int permission = INetd::PERMISSION_NONE);
216
217 void createPhysicalNetwork(int netId, const std::string& interface,
218 int permission = INetd::PERMISSION_NONE);
219
220 void createDefaultAndOtherPhysicalNetwork(int defaultNetId, int otherNetId);
221
222 void createVpnAndOtherPhysicalNetwork(int systemDefaultNetId, int otherNetId, int vpnNetId,
223 bool secure);
224
225 void createVpnAndAppDefaultNetworkWithUid(int systemDefaultNetId, int appDefaultNetId,
226 int vpnNetId, bool secure,
227 std::vector<UidRangeParcel>&& appDefaultUidRanges,
228 std::vector<UidRangeParcel>&& vpnUidRanges);
229
230 protected:
231 // Use -1 to represent that default network was not modified because
232 // real netId must be an unsigned value.
233 int mStoredDefaultNetwork = -1;
234 sp<INetd> mNetd;
235 static TunInterface sTun;
236 static TunInterface sTun2;
237 static TunInterface sTun3;
238 static TunInterface sTun4;
239 };
240
241 TunInterface NetdBinderTest::sTun;
242 TunInterface NetdBinderTest::sTun2;
243 TunInterface NetdBinderTest::sTun3;
244 TunInterface NetdBinderTest::sTun4;
245
246 class TimedOperation : public Stopwatch {
247 public:
TimedOperation(const std::string & name)248 explicit TimedOperation(const std::string &name): mName(name) {}
~TimedOperation()249 virtual ~TimedOperation() {
250 std::cerr << " " << mName << ": " << timeTakenUs() << "us" << std::endl;
251 }
252
253 private:
254 std::string mName;
255 };
256
TEST_F(NetdBinderTest,IsAlive)257 TEST_F(NetdBinderTest, IsAlive) {
258 TimedOperation t("isAlive RPC");
259 bool isAlive = false;
260 mNetd->isAlive(&isAlive);
261 ASSERT_TRUE(isAlive);
262 }
263
264 namespace {
265
makeNativeNetworkConfig(int netId,NativeNetworkType networkType,int permission,bool secure)266 NativeNetworkConfig makeNativeNetworkConfig(int netId, NativeNetworkType networkType,
267 int permission, bool secure) {
268 NativeNetworkConfig config = {};
269 config.netId = netId;
270 config.networkType = networkType;
271 config.permission = permission;
272 config.secure = secure;
273 // The vpnType doesn't matter in AOSP. Just pick a well defined one from INetd.
274 config.vpnType = NativeVpnType::PLATFORM;
275 return config;
276 }
277
278 } // namespace
279
testNetworkExistsButCannotConnect(const sp<INetd> & netd,TunInterface & ifc,const int netId)280 bool testNetworkExistsButCannotConnect(const sp<INetd>& netd, TunInterface& ifc, const int netId) {
281 // If this network exists, we should definitely not be able to create it.
282 // Note that this networkCreate is never allowed to create reserved network IDs, so
283 // this call may fail for other reasons than the network already existing.
284 const auto& config = makeNativeNetworkConfig(netId, NativeNetworkType::PHYSICAL,
285 INetd::PERMISSION_NONE, false);
286 EXPECT_FALSE(netd->networkCreate(config).isOk());
287 // Test if the network exist by adding interface. INetd has no dedicated method to query. When
288 // the network exists and the interface can be added, the function succeeds. When the network
289 // exists but the interface cannot be added, it fails with EINVAL, otherwise it is ENONET.
290 binder::Status status = netd->networkAddInterface(netId, ifc.name());
291 if (status.isOk()) { // clean up
292 EXPECT_TRUE(netd->networkRemoveInterface(netId, ifc.name()).isOk());
293 } else if (status.serviceSpecificErrorCode() == ENONET) {
294 return false;
295 }
296
297 const sockaddr_in6 sin6 = {.sin6_family = AF_INET6,
298 .sin6_addr = {{.u6_addr32 = {htonl(0x20010db8), 0, 0, 0}}},
299 .sin6_port = 53};
300 const int s = socket(AF_INET6, SOCK_DGRAM, 0);
301 EXPECT_NE(-1, s);
302 if (s == -1) return true;
303 Fwmark fwmark;
304 fwmark.explicitlySelected = true;
305 fwmark.netId = netId;
306 EXPECT_EQ(0, setsockopt(s, SOL_SOCKET, SO_MARK, &fwmark.intValue, sizeof(fwmark.intValue)));
307 const int ret = connect(s, (struct sockaddr*)&sin6, sizeof(sin6));
308 const int err = errno;
309 EXPECT_EQ(-1, ret);
310 EXPECT_EQ(ENETUNREACH, err);
311 close(s);
312 return true;
313 }
314
TEST_F(NetdBinderTest,InitialNetworksExist)315 TEST_F(NetdBinderTest, InitialNetworksExist) {
316 EXPECT_TRUE(testNetworkExistsButCannotConnect(mNetd, sTun, INetd::DUMMY_NET_ID));
317 EXPECT_TRUE(testNetworkExistsButCannotConnect(mNetd, sTun, INetd::LOCAL_NET_ID));
318 EXPECT_TRUE(testNetworkExistsButCannotConnect(mNetd, sTun, INetd::UNREACHABLE_NET_ID));
319 EXPECT_FALSE(testNetworkExistsButCannotConnect(mNetd, sTun, 77 /* not exist */));
320 }
321
TEST_F(NetdBinderTest,IpSecTunnelInterface)322 TEST_F(NetdBinderTest, IpSecTunnelInterface) {
323 const struct TestData {
324 const std::string family;
325 const std::string deviceName;
326 const std::string localAddress;
327 const std::string remoteAddress;
328 int32_t iKey;
329 int32_t oKey;
330 int32_t ifId;
331 } kTestData[] = {
332 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
333 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
334 0xFFFE},
335 };
336
337 for (size_t i = 0; i < std::size(kTestData); i++) {
338 const auto& td = kTestData[i];
339
340 binder::Status status;
341
342 // Create Tunnel Interface.
343 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
344 td.iKey, td.oKey, td.ifId);
345 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
346
347 // Check that the interface exists
348 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
349
350 // Update Tunnel Interface.
351 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
352 td.iKey, td.oKey, td.ifId);
353 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
354
355 // Remove Tunnel Interface.
356 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
357 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
358
359 // Check that the interface no longer exists
360 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
361 }
362 }
363
TEST_F(NetdBinderTest,IpSecSetEncapSocketOwner)364 TEST_F(NetdBinderTest, IpSecSetEncapSocketOwner) {
365 unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
366 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
367
368 int sockOptVal = UDP_ENCAP_ESPINUDP;
369 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
370
371 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
372 EXPECT_TRUE(res.isOk());
373
374 struct stat info;
375 EXPECT_EQ(0, fstat(sockFd.get(), &info));
376 EXPECT_EQ(1001, (int) info.st_uid);
377 }
378
379 // IPsec tests are not run in 32 bit mode; both 32-bit kernels and
380 // mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
381 #if INTPTR_MAX != INT32_MAX
382
383 using android::net::XfrmController;
384
385 static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
386 static_cast<int>(android::net::XfrmDirection::OUT)};
387 static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
388
389 #define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
390 do { if ((_expect_) != (_ret_)) return false; } while(false)
allocateIpSecResources(bool expectOk,int32_t * spi)391 bool NetdBinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
392 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
393 SCOPED_TRACE(status);
394 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
395
396 // Add a policy
397 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
398 SCOPED_TRACE(status);
399 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
400
401 // Add an ipsec interface
402 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
403 0xD00D, 0xE00D, false)
404 .ok();
405 }
406
TEST_F(NetdBinderTest,XfrmDualSelectorTunnelModePoliciesV4)407 TEST_F(NetdBinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
408 android::binder::Status status;
409
410 // Repeat to ensure cleanup and recreation works correctly
411 for (int i = 0; i < 2; i++) {
412 for (int direction : XFRM_DIRECTIONS) {
413 for (int addrFamily : ADDRESS_FAMILIES) {
414 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
415 "127.0.0.6", 123, 0, 0, 0);
416 EXPECT_TRUE(status.isOk())
417 << " family: " << addrFamily << " direction: " << direction;
418 }
419 }
420
421 // Cleanup
422 for (int direction : XFRM_DIRECTIONS) {
423 for (int addrFamily : ADDRESS_FAMILIES) {
424 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
425 EXPECT_TRUE(status.isOk());
426 }
427 }
428 }
429 }
430
TEST_F(NetdBinderTest,XfrmDualSelectorTunnelModePoliciesV6)431 TEST_F(NetdBinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
432 binder::Status status;
433
434 // Repeat to ensure cleanup and recreation works correctly
435 for (int i = 0; i < 2; i++) {
436 for (int direction : XFRM_DIRECTIONS) {
437 for (int addrFamily : ADDRESS_FAMILIES) {
438 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
439 "2001:db8::d00d", 123, 0, 0, 0);
440 EXPECT_TRUE(status.isOk())
441 << " family: " << addrFamily << " direction: " << direction;
442 }
443 }
444
445 // Cleanup
446 for (int direction : XFRM_DIRECTIONS) {
447 for (int addrFamily : ADDRESS_FAMILIES) {
448 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
449 EXPECT_TRUE(status.isOk());
450 }
451 }
452 }
453 }
454
TEST_F(NetdBinderTest,XfrmControllerInit)455 TEST_F(NetdBinderTest, XfrmControllerInit) {
456 android::netdutils::Status status;
457 status = XfrmController::Init();
458 SCOPED_TRACE(status);
459
460 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
461 // feature.
462 if (status.code() == EOPNOTSUPP) return;
463
464 ASSERT_TRUE(status.ok());
465
466 int32_t spi = 0;
467
468 ASSERT_TRUE(allocateIpSecResources(true, &spi));
469 ASSERT_TRUE(allocateIpSecResources(false, &spi));
470
471 status = XfrmController::Init();
472 ASSERT_TRUE(status.ok());
473 ASSERT_TRUE(allocateIpSecResources(true, &spi));
474
475 // Clean up
476 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
477 SCOPED_TRACE(status);
478 ASSERT_TRUE(status.ok());
479
480 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
481 SCOPED_TRACE(status);
482 ASSERT_TRUE(status.ok());
483
484 // Remove Virtual Tunnel Interface.
485 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
486 }
487
488 #endif // INTPTR_MAX != INT32_MAX
489
bandwidthDataSaverEnabled(const char * binary)490 static int bandwidthDataSaverEnabled(const char *binary) {
491 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
492
493 // Output looks like this:
494 //
495 // Chain bw_data_saver (1 references)
496 // target prot opt source destination
497 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
498 //
499 // or:
500 //
501 // Chain bw_data_saver (1 references)
502 // target prot opt source destination
503 // ... possibly connectivity critical packet rules here ...
504 // REJECT all -- ::/0 ::/0
505
506 EXPECT_GE(lines.size(), 3U);
507
508 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
509 // Data saver disabled.
510 return 0;
511 }
512
513 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
514
515 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
516 // Data saver enabled.
517 return 1;
518 }
519
520 return -1;
521 }
522
enableDataSaver(sp<INetd> & netd,bool enable)523 bool enableDataSaver(sp<INetd>& netd, bool enable) {
524 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
525 bool ret;
526 netd->bandwidthEnableDataSaver(enable, &ret);
527 return ret;
528 }
529
getDataSaverState()530 int getDataSaverState() {
531 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
532 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
533 EXPECT_EQ(enabled4, enabled6);
534 EXPECT_NE(-1, enabled4);
535 EXPECT_NE(-1, enabled6);
536 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
537 return -1;
538 }
539 return enabled6;
540 }
541
TEST_F(NetdBinderTest,BandwidthEnableDataSaver)542 TEST_F(NetdBinderTest, BandwidthEnableDataSaver) {
543 const int wasEnabled = getDataSaverState();
544 ASSERT_NE(-1, wasEnabled);
545
546 if (wasEnabled) {
547 ASSERT_TRUE(enableDataSaver(mNetd, false));
548 EXPECT_EQ(0, getDataSaverState());
549 }
550
551 ASSERT_TRUE(enableDataSaver(mNetd, false));
552 EXPECT_EQ(0, getDataSaverState());
553
554 ASSERT_TRUE(enableDataSaver(mNetd, true));
555 EXPECT_EQ(1, getDataSaverState());
556
557 ASSERT_TRUE(enableDataSaver(mNetd, true));
558 EXPECT_EQ(1, getDataSaverState());
559
560 if (!wasEnabled) {
561 ASSERT_TRUE(enableDataSaver(mNetd, false));
562 EXPECT_EQ(0, getDataSaverState());
563 }
564 }
565
ipRuleExistsForRange(const uint32_t priority,const UidRangeParcel & range,const std::string & action,const char * ipVersion,const char * oif)566 static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
567 const std::string& action, const char* ipVersion,
568 const char* oif) {
569 // Output looks like this:
570 // "<priority>:\tfrom all iif lo oif netdc0ca6 uidrange 500000-500000 lookup netdc0ca6"
571 // "<priority>:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
572 std::vector<std::string> rules = listIpRules(ipVersion);
573
574 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
575 std::string suffix;
576 if (oif) {
577 suffix = StringPrintf(" iif lo oif %s uidrange %d-%d %s\n", oif, range.start, range.stop,
578 action.c_str());
579 } else {
580 suffix = StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop,
581 action.c_str());
582 }
583 for (const auto& line : rules) {
584 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
585 return true;
586 }
587 }
588 return false;
589 }
590
591 // Overloads function with oif parameter for VPN rules compare.
ipRuleExistsForRange(const uint32_t priority,const UidRangeParcel & range,const std::string & action,const char * oif)592 static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
593 const std::string& action, const char* oif) {
594 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4, oif);
595 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6, oif);
596 EXPECT_EQ(existsIp4, existsIp6);
597 return existsIp4;
598 }
599
ipRuleExistsForRange(const uint32_t priority,const UidRangeParcel & range,const std::string & action)600 static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
601 const std::string& action) {
602 return ipRuleExistsForRange(priority, range, action, nullptr);
603 }
604
605 namespace {
606
makeUidRangeParcel(int start,int stop)607 UidRangeParcel makeUidRangeParcel(int start, int stop) {
608 UidRangeParcel res;
609 res.start = start;
610 res.stop = stop;
611
612 return res;
613 }
614
makeNativeUidRangeConfig(unsigned netId,std::vector<UidRangeParcel> && uidRanges,uint32_t subPriority)615 NativeUidRangeConfig makeNativeUidRangeConfig(unsigned netId,
616 std::vector<UidRangeParcel>&& uidRanges,
617 uint32_t subPriority) {
618 NativeUidRangeConfig res;
619 res.netId = netId;
620 res.uidRanges = uidRanges;
621 res.subPriority = subPriority;
622
623 return res;
624 }
625
626 } // namespace
627
TEST_F(NetdBinderTest,NetworkInterfaces)628 TEST_F(NetdBinderTest, NetworkInterfaces) {
629 auto config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
630 INetd::PERMISSION_NONE, false);
631 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
632 EXPECT_EQ(EEXIST, mNetd->networkCreate(config).serviceSpecificErrorCode());
633
634 config.networkType = NativeNetworkType::VIRTUAL;
635 config.secure = true;
636 EXPECT_EQ(EEXIST, mNetd->networkCreate(config).serviceSpecificErrorCode());
637
638 config.netId = TEST_NETID2;
639 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
640
641 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
642 EXPECT_EQ(EBUSY,
643 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
644
645 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
646 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
647 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
648 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
649 }
650
TEST_F(NetdBinderTest,NetworkUidRules)651 TEST_F(NetdBinderTest, NetworkUidRules) {
652 auto config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::VIRTUAL,
653 INetd::PERMISSION_NONE, true);
654 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
655 EXPECT_EQ(EEXIST, mNetd->networkCreate(config).serviceSpecificErrorCode());
656 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
657
658 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
659 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
660 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
661 std::string action = StringPrintf("lookup %s ", sTun.name().c_str());
662
663 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
664
665 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], action));
666 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, action));
667 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
668 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], action));
669
670 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
671 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], action));
672 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
673 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], action));
674
675 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
676 }
677
TEST_F(NetdBinderTest,NetworkRejectNonSecureVpn)678 TEST_F(NetdBinderTest, NetworkRejectNonSecureVpn) {
679 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
680 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
681 // Make sure no rules existed before calling commands.
682 for (auto const& range : uidRanges) {
683 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_PROHIBIT_NON_VPN, range, "prohibit"));
684 }
685 // Create two valid rules.
686 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
687 for (auto const& range : uidRanges) {
688 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_PROHIBIT_NON_VPN, range, "prohibit"));
689 }
690
691 // Remove the rules.
692 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
693 for (auto const& range : uidRanges) {
694 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_PROHIBIT_NON_VPN, range, "prohibit"));
695 }
696
697 // Fail to remove the rules a second time after they are already deleted.
698 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
699 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
700 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
701 }
702
703 // Create a socket pair that isLoopbackSocket won't think is local.
fakeRemoteSocketPair(unique_fd * clientSocket,unique_fd * serverSocket,unique_fd * acceptedSocket)704 void NetdBinderTest::fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
705 unique_fd* acceptedSocket) {
706 serverSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
707 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
708 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
709
710 socklen_t addrlen = sizeof(server6);
711 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
712 ASSERT_EQ(0, listen(*serverSocket, 10));
713
714 clientSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
715 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
716 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
717 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
718 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
719
720 acceptedSocket->reset(
721 accept4(*serverSocket, (struct sockaddr*)&server6, &addrlen, SOCK_CLOEXEC));
722 ASSERT_NE(-1, *acceptedSocket);
723
724 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
725 }
726
checkSocketpairOpen(int clientSocket,int acceptedSocket)727 void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
728 char buf[4096];
729 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
730 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
731 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
732 }
733
checkSocketpairClosed(int clientSocket,int acceptedSocket)734 void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
735 // Check that the client socket was closed with ECONNABORTED.
736 int ret = write(clientSocket, "foo", sizeof("foo"));
737 int err = errno;
738 EXPECT_EQ(-1, ret);
739 EXPECT_EQ(ECONNABORTED, err);
740
741 // Check that it sent a RST to the server.
742 ret = write(acceptedSocket, "foo", sizeof("foo"));
743 err = errno;
744 EXPECT_EQ(-1, ret);
745 EXPECT_EQ(ECONNRESET, err);
746 }
747
TEST_F(NetdBinderTest,SocketDestroy)748 TEST_F(NetdBinderTest, SocketDestroy) {
749 unique_fd clientSocket, serverSocket, acceptedSocket;
750 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
751
752 // Pick a random UID in the system UID range.
753 constexpr int baseUid = AID_APP - 2000;
754 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
755 int uid = baseUid + 500 + arc4random_uniform(1000);
756 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
757
758 // UID ranges that don't contain uid.
759 std::vector<UidRangeParcel> uidRanges = {
760 makeUidRangeParcel(baseUid + 42, baseUid + 449),
761 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
762 makeUidRangeParcel(baseUid + 498, uid - 1),
763 makeUidRangeParcel(uid + 1, baseUid + 1520),
764 };
765 // A skip list that doesn't contain UID.
766 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
767
768 // Close sockets. Our test socket should be intact.
769 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
770 checkSocketpairOpen(clientSocket, acceptedSocket);
771
772 // UID ranges that do contain uid.
773 uidRanges = {
774 makeUidRangeParcel(baseUid + 42, baseUid + 449),
775 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
776 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
777 };
778 // Add uid to the skip list.
779 skipUids.push_back(uid);
780
781 // Close sockets. Our test socket should still be intact because it's in the skip list.
782 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
783 checkSocketpairOpen(clientSocket, acceptedSocket);
784
785 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
786 skipUids.resize(skipUids.size() - 1);
787 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
788 checkSocketpairClosed(clientSocket, acceptedSocket);
789 }
790
TEST_F(NetdBinderTest,SocketDestroyLinkLocal)791 TEST_F(NetdBinderTest, SocketDestroyLinkLocal) {
792 // Add the same link-local address to two interfaces.
793 const char* kLinkLocalAddress = "fe80::ace:d00d";
794
795 const struct addrinfo hints = {
796 .ai_family = AF_INET6,
797 .ai_socktype = SOCK_STREAM,
798 .ai_flags = AI_NUMERICHOST,
799 };
800
801 binder::Status status = mNetd->interfaceAddAddress(sTun.name(), kLinkLocalAddress, 64);
802 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
803 status = mNetd->interfaceAddAddress(sTun2.name(), kLinkLocalAddress, 64);
804 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
805
806 // Bind a listening socket to the address on each of two interfaces.
807 // The sockets must be open at the same time, because this test checks that SOCK_DESTROY only
808 // destroys the sockets on the interface where the address is deleted.
809 struct addrinfo* addrinfoList = nullptr;
810 int ret = getaddrinfo(kLinkLocalAddress, nullptr, &hints, &addrinfoList);
811 ScopedAddrinfo addrinfoCleanup(addrinfoList);
812 ASSERT_EQ(0, ret);
813
814 socklen_t len = addrinfoList[0].ai_addrlen;
815 sockaddr_in6 sin6_1 = *reinterpret_cast<sockaddr_in6*>(addrinfoList[0].ai_addr);
816 sockaddr_in6 sin6_2 = sin6_1;
817 sin6_1.sin6_scope_id = if_nametoindex(sTun.name().c_str());
818 sin6_2.sin6_scope_id = if_nametoindex(sTun2.name().c_str());
819
820 int s1 = socket(AF_INET6, SOCK_STREAM, 0);
821 ASSERT_EQ(0, bind(s1, reinterpret_cast<sockaddr*>(&sin6_1), len));
822 ASSERT_EQ(0, getsockname(s1, reinterpret_cast<sockaddr*>(&sin6_1), &len));
823
824 int s2 = socket(AF_INET6, SOCK_STREAM, 0);
825 ASSERT_EQ(0, bind(s2, reinterpret_cast<sockaddr*>(&sin6_2), len));
826 ASSERT_EQ(0, getsockname(s2, reinterpret_cast<sockaddr*>(&sin6_2), &len));
827
828 ASSERT_EQ(0, listen(s1, 10));
829 ASSERT_EQ(0, listen(s2, 10));
830
831 // Connect one client socket to each and accept the connections.
832 int c1 = socket(AF_INET6, SOCK_STREAM, 0);
833 int c2 = socket(AF_INET6, SOCK_STREAM, 0);
834 ASSERT_EQ(0, connect(c1, reinterpret_cast<sockaddr*>(&sin6_1), len));
835 ASSERT_EQ(0, connect(c2, reinterpret_cast<sockaddr*>(&sin6_2), len));
836 int a1 = accept(s1, nullptr, 0);
837 ASSERT_NE(-1, a1);
838 int a2 = accept(s2, nullptr, 0);
839 ASSERT_NE(-1, a2);
840
841 // Delete the address on sTun2.
842 status = mNetd->interfaceDelAddress(sTun2.name(), kLinkLocalAddress, 64);
843 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
844
845 // The sockets on sTun2 are closed, but the ones on sTun1 remain open.
846 char buf[1024];
847 EXPECT_EQ(-1, read(c2, buf, sizeof(buf)));
848 EXPECT_EQ(ECONNABORTED, errno);
849 // The blocking read above ensures that SOCK_DESTROY has completed.
850
851 EXPECT_EQ(3, write(a1, "foo", 3));
852 EXPECT_EQ(3, read(c1, buf, sizeof(buf)));
853 EXPECT_EQ(-1, write(a2, "foo", 3));
854 EXPECT_TRUE(errno == ECONNABORTED || errno == ECONNRESET);
855 }
856
857 namespace {
858
netmaskToPrefixLength(const uint8_t * buf,size_t buflen)859 int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
860 if (buf == nullptr) return -1;
861
862 int prefixLength = 0;
863 bool endOfContiguousBits = false;
864 for (unsigned int i = 0; i < buflen; i++) {
865 const uint8_t value = buf[i];
866
867 // Bad bit sequence: check for a contiguous set of bits from the high
868 // end by verifying that the inverted value + 1 is a power of 2
869 // (power of 2 iff. (v & (v - 1)) == 0).
870 const uint8_t inverse = ~value + 1;
871 if ((inverse & (inverse - 1)) != 0) return -1;
872
873 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
874
875 // Bogus netmask.
876 if (endOfContiguousBits && value != 0) return -1;
877
878 if (value != 0xff) endOfContiguousBits = true;
879 }
880
881 return prefixLength;
882 }
883
884 template<typename T>
netmaskToPrefixLength(const T * p)885 int netmaskToPrefixLength(const T *p) {
886 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
887 }
888
889
interfaceHasAddress(const std::string & ifname,const char * addrString,int prefixLength)890 static bool interfaceHasAddress(
891 const std::string &ifname, const char *addrString, int prefixLength) {
892 struct addrinfo *addrinfoList = nullptr;
893
894 const struct addrinfo hints = {
895 .ai_flags = AI_NUMERICHOST,
896 .ai_family = AF_UNSPEC,
897 .ai_socktype = SOCK_DGRAM,
898 };
899 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
900 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
901 return false;
902 }
903 ScopedAddrinfo addrinfoCleanup(addrinfoList);
904
905 struct ifaddrs *ifaddrsList = nullptr;
906 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
907
908 if (getifaddrs(&ifaddrsList) != 0) {
909 return false;
910 }
911
912 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
913 if (std::string(addr->ifa_name) != ifname ||
914 addr->ifa_addr == nullptr ||
915 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
916 continue;
917 }
918
919 switch (addr->ifa_addr->sa_family) {
920 case AF_INET: {
921 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
922 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
923 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
924 continue;
925 }
926
927 if (prefixLength < 0) return true; // not checking prefix lengths
928
929 if (addr->ifa_netmask == nullptr) return false;
930 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
931 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
932 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
933 }
934 case AF_INET6: {
935 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
936 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
937 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
938 continue;
939 }
940
941 if (prefixLength < 0) return true; // not checking prefix lengths
942
943 if (addr->ifa_netmask == nullptr) return false;
944 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
945 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
946 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
947 }
948 default:
949 // Cannot happen because we have already screened for matching
950 // address families at the top of each iteration.
951 continue;
952 }
953 }
954
955 return false;
956 }
957
958 } // namespace
959
TEST_F(NetdBinderTest,InterfaceAddRemoveAddress)960 TEST_F(NetdBinderTest, InterfaceAddRemoveAddress) {
961 static const struct TestData {
962 const char *addrString;
963 const int prefixLength;
964 const int expectAddResult;
965 const int expectRemoveResult;
966 } kTestData[] = {
967 {"192.0.2.1", 24, 0, 0},
968 {"192.0.2.2", 25, 0, 0},
969 {"192.0.2.3", 32, 0, 0},
970 {"192.0.2.4", 33, EINVAL, EADDRNOTAVAIL},
971 {"192.not.an.ip", 24, EINVAL, EINVAL},
972 {"2001:db8::1", 64, 0, 0},
973 {"2001:db8::2", 65, 0, 0},
974 {"2001:db8::3", 128, 0, 0},
975 {"fe80::1234", 64, 0, 0},
976 {"2001:db8::4", 129, EINVAL, EINVAL},
977 {"foo:bar::bad", 64, EINVAL, EINVAL},
978 {"2001:db8::1/64", 64, EINVAL, EINVAL},
979 };
980
981 for (size_t i = 0; i < std::size(kTestData); i++) {
982 const auto &td = kTestData[i];
983
984 SCOPED_TRACE(String8::format("Offending IP address %s/%d", td.addrString, td.prefixLength));
985
986 // [1.a] Add the address.
987 binder::Status status = mNetd->interfaceAddAddress(
988 sTun.name(), td.addrString, td.prefixLength);
989 if (td.expectAddResult == 0) {
990 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
991 } else {
992 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
993 ASSERT_EQ(td.expectAddResult, status.serviceSpecificErrorCode());
994 }
995
996 // [1.b] Verify the addition meets the expectation.
997 if (td.expectAddResult == 0) {
998 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
999 } else {
1000 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
1001 }
1002
1003 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
1004 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
1005 if (td.expectRemoveResult == 0) {
1006 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1007 } else {
1008 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1009 ASSERT_EQ(td.expectRemoveResult, status.serviceSpecificErrorCode());
1010 }
1011
1012 // [2.b] No matter what, the address should not be present.
1013 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
1014 }
1015
1016 // Check that netlink errors are returned correctly.
1017 // We do this by attempting to create an IPv6 address on an interface that has IPv6 disabled,
1018 // which returns EACCES.
1019 TunInterface tun;
1020 ASSERT_EQ(0, tun.init());
1021 binder::Status status =
1022 mNetd->setProcSysNet(INetd::IPV6, INetd::CONF, tun.name(), "disable_ipv6", "1");
1023 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
1024 status = mNetd->interfaceAddAddress(tun.name(), "2001:db8::1", 64);
1025 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1026 EXPECT_EQ(EACCES, status.serviceSpecificErrorCode());
1027 tun.destroy();
1028 }
1029
TEST_F(NetdBinderTest,GetProcSysNet)1030 TEST_F(NetdBinderTest, GetProcSysNet) {
1031 const char* LOOPBACK = "lo";
1032 static const struct {
1033 const int ipversion;
1034 const int which;
1035 const char* ifname;
1036 const char* parameter;
1037 const char* expectedValue;
1038 const int expectedReturnCode;
1039 } kTestData[] = {
1040 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
1041 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
1042 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
1043 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
1044 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
1045 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
1046 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
1047 };
1048
1049 for (size_t i = 0; i < std::size(kTestData); i++) {
1050 const auto& td = kTestData[i];
1051
1052 std::string value;
1053 const binder::Status status =
1054 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
1055
1056 if (td.expectedReturnCode == 0) {
1057 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
1058 EXPECT_EQ(0, status.exceptionCode());
1059 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1060 EXPECT_EQ(td.expectedValue, value);
1061 } else {
1062 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
1063 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1064 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
1065 }
1066 }
1067 }
1068
TEST_F(NetdBinderTest,SetProcSysNet)1069 TEST_F(NetdBinderTest, SetProcSysNet) {
1070 static const struct {
1071 const int ipversion;
1072 const int which;
1073 const char* ifname;
1074 const char* parameter;
1075 const char* value;
1076 const int expectedReturnCode;
1077 } kTestData[] = {
1078 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
1079 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
1080 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
1081 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
1082 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
1083 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
1084 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
1085 };
1086
1087 for (size_t i = 0; i < std::size(kTestData); i++) {
1088 const auto& td = kTestData[i];
1089 const binder::Status status =
1090 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
1091
1092 if (td.expectedReturnCode == 0) {
1093 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
1094 EXPECT_EQ(0, status.exceptionCode());
1095 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1096 } else {
1097 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
1098 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1099 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
1100 }
1101 }
1102 }
1103
TEST_F(NetdBinderTest,GetSetProcSysNet)1104 TEST_F(NetdBinderTest, GetSetProcSysNet) {
1105 const int ipversion = INetd::IPV6;
1106 const int category = INetd::NEIGH;
1107 const std::string& tun = sTun.name();
1108 const std::string parameter("ucast_solicit");
1109
1110 std::string value{};
1111 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
1112 ASSERT_FALSE(value.empty());
1113 const int ival = std::stoi(value);
1114 EXPECT_GT(ival, 0);
1115 // Try doubling the parameter value (always best!).
1116 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
1117 .isOk());
1118 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
1119 EXPECT_EQ(2 * ival, std::stoi(value));
1120 // Try resetting the parameter.
1121 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
1122 .isOk());
1123 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
1124 EXPECT_EQ(ival, std::stoi(value));
1125 }
1126
1127 namespace {
1128
expectNoTestCounterRules()1129 void expectNoTestCounterRules() {
1130 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1131 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1132 std::string allRules = Join(runCommand(command), "\n");
1133 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1134 }
1135 }
1136
addTetherCounterValues(const char * path,const std::string & if1,const std::string & if2,int byte,int pkt)1137 void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1138 int byte, int pkt) {
1139 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1140 path, if1.c_str(), if2.c_str(), pkt, byte));
1141 }
1142
delTetherCounterValues(const char * path,const std::string & if1,const std::string & if2)1143 void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
1144 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1145 path, if1.c_str(), if2.c_str()));
1146 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1147 path, if2.c_str(), if1.c_str()));
1148 }
1149
getStatsVectorByIf(const std::vector<TetherStatsParcel> & statsVec,const std::string & iface)1150 std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1151 const std::string& iface) {
1152 for (auto& stats : statsVec) {
1153 if (stats.iface == iface) {
1154 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1155 }
1156 }
1157 return {};
1158 }
1159
1160 } // namespace
1161
TEST_F(NetdBinderTest,TetherGetStats)1162 TEST_F(NetdBinderTest, TetherGetStats) {
1163 expectNoTestCounterRules();
1164
1165 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1166 // disabling tethering. We don't check the return value because these commands will fail if
1167 // tethering is already enabled.
1168 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1169 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1170
1171 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1172 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1173 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1174
1175 // Ensure we won't use the same interface name, otherwise the test will fail.
1176 u_int32_t rNumber = arc4random_uniform(10000);
1177 std::string extIface1 = StringPrintf("netdtest_%u", rNumber);
1178 std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1);
1179
1180 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1181 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1182 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1183 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1184 // RX is from external to internal, and TX is from internal to external.
1185 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1186 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1187
1188 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1189 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1190
1191 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1192 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1193
1194 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1195 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1196 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1197
1198 std::vector<TetherStatsParcel> statsVec;
1199 binder::Status status = mNetd->tetherGetStats(&statsVec);
1200 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1201
1202 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
1203
1204 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
1205
1206 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1207 delTetherCounterValues(path, intIface1, extIface1);
1208 delTetherCounterValues(path, intIface2, extIface2);
1209 if (path == IP6TABLES_PATH) {
1210 delTetherCounterValues(path, intIface3, extIface2);
1211 }
1212 }
1213
1214 expectNoTestCounterRules();
1215 }
1216
1217 namespace {
1218
1219 constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1220 constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
1221
listIptablesRuleByTable(const char * binary,const char * table,const char * chainName)1222 static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1223 const char* chainName) {
1224 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1225 return runCommand(command);
1226 }
1227
1228 // TODO: It is a duplicate function, need to remove it
iptablesIdleTimerInterfaceRuleExists(const char * binary,const char * chainName,const std::string & expectedInterface,const std::string & expectedRule,const char * table)1229 bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
1230 const std::string& expectedInterface,
1231 const std::string& expectedRule, const char* table) {
1232 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1233 for (const auto& rule : rules) {
1234 if (rule.find(expectedInterface) != std::string::npos) {
1235 if (rule.find(expectedRule) != std::string::npos) {
1236 return true;
1237 }
1238 }
1239 }
1240 return false;
1241 }
1242
expectIdletimerInterfaceRuleExists(const std::string & ifname,int timeout,const std::string & classLabel)1243 void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
1244 const std::string& classLabel) {
1245 std::string IdletimerRule =
1246 StringPrintf("timeout:%u label:%s send_nl_msg", timeout, classLabel.c_str());
1247 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1248 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1249 IdletimerRule, RAW_TABLE));
1250 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
1251 ifname, IdletimerRule, MANGLE_TABLE));
1252 }
1253 }
1254
expectIdletimerInterfaceRuleNotExists(const std::string & ifname,int timeout,const std::string & classLabel)1255 void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
1256 const std::string& classLabel) {
1257 std::string IdletimerRule =
1258 StringPrintf("timeout:%u label:%s send_nl_msg", timeout, classLabel.c_str());
1259 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1260 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1261 IdletimerRule, RAW_TABLE));
1262 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
1263 ifname, IdletimerRule, MANGLE_TABLE));
1264 }
1265 }
1266
1267 } // namespace
1268
TEST_F(NetdBinderTest,IdletimerAddRemoveInterface)1269 TEST_F(NetdBinderTest, IdletimerAddRemoveInterface) {
1270 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1271 // rule in the table. Because we only check the result after calling remove function. We might
1272 // check the actual rule which is removed by our function (maybe compare the results between
1273 // calling function before and after)
1274 binder::Status status;
1275 const struct TestData {
1276 const std::string ifname;
1277 int32_t timeout;
1278 const std::string classLabel;
1279 } idleTestData[] = {
1280 {"wlan0", 1234, "happyday"},
1281 {"rmnet_data0", 4567, "friday"},
1282 };
1283 for (const auto& td : idleTestData) {
1284 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1285 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1286 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1287
1288 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1289 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1290 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1291 }
1292 }
1293
1294 namespace {
1295
1296 constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1297 constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1298
expectStrictSetUidAccept(const int uid)1299 void expectStrictSetUidAccept(const int uid) {
1300 std::string uidRule = StringPrintf("owner UID match %u", uid);
1301 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1302 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1303 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1304 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
1305 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1306 }
1307 }
1308
expectStrictSetUidLog(const int uid)1309 void expectStrictSetUidLog(const int uid) {
1310 static const char logRule[] = "st_penalty_log all";
1311 std::string uidRule = StringPrintf("owner UID match %u", uid);
1312 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1313 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1314 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1315 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
1316 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1317 }
1318 }
1319
expectStrictSetUidReject(const int uid)1320 void expectStrictSetUidReject(const int uid) {
1321 static const char rejectRule[] = "st_penalty_reject all";
1322 std::string uidRule = StringPrintf("owner UID match %u", uid);
1323 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1324 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1325 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1326 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
1327 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1328 }
1329 }
1330
1331 } // namespace
1332
TEST_F(NetdBinderTest,StrictSetUidCleartextPenalty)1333 TEST_F(NetdBinderTest, StrictSetUidCleartextPenalty) {
1334 binder::Status status;
1335 int32_t uid = randomUid();
1336
1337 // setUidCleartextPenalty Policy:Log with randomUid
1338 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1339 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1340 expectStrictSetUidLog(uid);
1341
1342 // setUidCleartextPenalty Policy:Accept with randomUid
1343 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1344 expectStrictSetUidAccept(uid);
1345
1346 // setUidCleartextPenalty Policy:Reject with randomUid
1347 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1348 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1349 expectStrictSetUidReject(uid);
1350
1351 // setUidCleartextPenalty Policy:Accept with randomUid
1352 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1353 expectStrictSetUidAccept(uid);
1354
1355 // test wrong policy
1356 int32_t wrongPolicy = -123;
1357 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1358 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1359 }
1360
1361 namespace {
1362
tryToFindProcesses(const std::string & processName,uint32_t maxTries=1,uint32_t intervalMs=50)1363 std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
1364 uint32_t intervalMs = 50) {
1365 // Output looks like:(clatd)
1366 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1367 // ...
1368 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1369
1370 // (dnsmasq)
1371 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1372
1373 if (maxTries == 0) return {};
1374
1375 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
1376 std::vector<std::string> result;
1377 for (uint32_t run = 1;;) {
1378 result = runCommand(cmd);
1379 if (result.size() || ++run > maxTries) {
1380 break;
1381 }
1382
1383 usleep(intervalMs * 1000);
1384 }
1385 return result;
1386 }
1387
expectProcessExists(const std::string & processName)1388 void expectProcessExists(const std::string& processName) {
1389 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
1390 }
1391
expectProcessDoesNotExist(const std::string & processName)1392 void expectProcessDoesNotExist(const std::string& processName) {
1393 EXPECT_FALSE(tryToFindProcesses(processName).size());
1394 }
1395
1396 } // namespace
1397
TEST_F(NetdBinderTest,ClatdStartStop)1398 TEST_F(NetdBinderTest, ClatdStartStop) {
1399 binder::Status status;
1400
1401 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1402 std::string clatAddress;
1403 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
1404
1405 // Can't start clatd on an interface that's not part of any network...
1406 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1407 EXPECT_FALSE(status.isOk());
1408 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1409
1410 // ... so create a test physical network and add our tun to it.
1411 const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
1412 INetd::PERMISSION_NONE, false);
1413 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
1414 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1415
1416 // Prefix must be 96 bits long.
1417 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1418 EXPECT_FALSE(status.isOk());
1419 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1420
1421 // Can't start clatd unless there's a default route...
1422 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1423 EXPECT_FALSE(status.isOk());
1424 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1425
1426 // so add a default route.
1427 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1428
1429 // Can't start clatd unless there's a global address...
1430 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1431 EXPECT_FALSE(status.isOk());
1432 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1433
1434 // ... so add a global address.
1435 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
1436 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
1437
1438 // Now expect clatd to start successfully.
1439 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1440 EXPECT_TRUE(status.isOk());
1441 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1442
1443 // Starting it again returns EBUSY.
1444 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1445 EXPECT_FALSE(status.isOk());
1446 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1447
1448 expectProcessExists(clatdName);
1449
1450 // Expect clatd to stop successfully.
1451 status = mNetd->clatdStop(sTun.name());
1452 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1453 expectProcessDoesNotExist(clatdName);
1454
1455 // Stopping a clatd that doesn't exist returns ENODEV.
1456 status = mNetd->clatdStop(sTun.name());
1457 EXPECT_FALSE(status.isOk());
1458 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1459 expectProcessDoesNotExist(clatdName);
1460
1461 // Clean up.
1462 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1463 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1464 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1465 }
1466
1467 namespace {
1468
getIpfwdV4Enable()1469 bool getIpfwdV4Enable() {
1470 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1471 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1472 EXPECT_TRUE(!result.empty());
1473 int v4Enable = std::stoi(result[0]);
1474 return v4Enable;
1475 }
1476
getIpfwdV6Enable()1477 bool getIpfwdV6Enable() {
1478 static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
1479 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1480 EXPECT_TRUE(!result.empty());
1481 int v6Enable = std::stoi(result[0]);
1482 return v6Enable;
1483 }
1484
expectIpfwdEnable(bool enable)1485 void expectIpfwdEnable(bool enable) {
1486 int enableIPv4 = getIpfwdV4Enable();
1487 int enableIPv6 = getIpfwdV6Enable();
1488 EXPECT_EQ(enable, enableIPv4);
1489 EXPECT_EQ(enable, enableIPv6);
1490 }
1491
ipRuleIpfwdExists(const char * ipVersion,const std::string & ipfwdRule)1492 bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
1493 std::vector<std::string> rules = listIpRules(ipVersion);
1494 for (const auto& rule : rules) {
1495 if (rule.find(ipfwdRule) != std::string::npos) {
1496 return true;
1497 }
1498 }
1499 return false;
1500 }
1501
expectIpfwdRuleExists(const char * fromIf,const char * toIf)1502 void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1503 std::string ipfwdRule =
1504 StringPrintf("%u:\tfrom all iif %s lookup %s ", RULE_PRIORITY_TETHERING, fromIf, toIf);
1505
1506 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1507 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1508 }
1509 }
1510
expectIpfwdRuleNotExists(const char * fromIf,const char * toIf)1511 void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1512 std::string ipfwdRule =
1513 StringPrintf("%u:\tfrom all iif %s lookup %s ", RULE_PRIORITY_TETHERING, fromIf, toIf);
1514
1515 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1516 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1517 }
1518 }
1519
1520 } // namespace
1521
TEST_F(NetdBinderTest,TestIpfwdEnableDisableStatusForwarding)1522 TEST_F(NetdBinderTest, TestIpfwdEnableDisableStatusForwarding) {
1523 // Get ipfwd requester list from Netd
1524 std::vector<std::string> requesterList;
1525 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
1526 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1527
1528 bool ipfwdEnabled;
1529 if (requesterList.size() == 0) {
1530 // No requester in Netd, ipfwd should be disabled
1531 // So add one test requester and verify
1532 status = mNetd->ipfwdEnableForwarding("TestRequester");
1533 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1534
1535 expectIpfwdEnable(true);
1536 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1537 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1538 EXPECT_TRUE(ipfwdEnabled);
1539
1540 // Remove test one, verify again
1541 status = mNetd->ipfwdDisableForwarding("TestRequester");
1542 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1543
1544 expectIpfwdEnable(false);
1545 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1546 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1547 EXPECT_FALSE(ipfwdEnabled);
1548 } else {
1549 // Disable all requesters
1550 for (const auto& requester : requesterList) {
1551 status = mNetd->ipfwdDisableForwarding(requester);
1552 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1553 }
1554
1555 // After disable all requester, ipfwd should be disabled
1556 expectIpfwdEnable(false);
1557 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1558 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1559 EXPECT_FALSE(ipfwdEnabled);
1560
1561 // Enable them back
1562 for (const auto& requester : requesterList) {
1563 status = mNetd->ipfwdEnableForwarding(requester);
1564 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1565 }
1566
1567 // ipfwd should be enabled
1568 expectIpfwdEnable(true);
1569 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1570 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1571 EXPECT_TRUE(ipfwdEnabled);
1572 }
1573 }
1574
TEST_F(NetdBinderTest,TestIpfwdAddRemoveInterfaceForward)1575 TEST_F(NetdBinderTest, TestIpfwdAddRemoveInterfaceForward) {
1576 // Add test physical network
1577 auto config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
1578 INetd::PERMISSION_NONE, false);
1579 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
1580 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1581
1582 config.netId = TEST_NETID2;
1583 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
1584 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
1585
1586 binder::Status status = mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1587 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1588 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
1589
1590 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1591 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1592 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
1593 }
1594
1595 namespace {
1596
1597 constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1598 constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1599 constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1600 constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1601 constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
1602
1603 // TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1604 // Use either a std::vector<std::string> of things to match, or a variadic function.
iptablesTargetsExists(const char * binary,int expectedCount,const char * table,const char * chainName,const std::string & expectedTargetA,const std::string & expectedTargetB)1605 bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1606 const char* chainName, const std::string& expectedTargetA,
1607 const std::string& expectedTargetB) {
1608 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1609 int matchCount = 0;
1610
1611 for (const auto& rule : rules) {
1612 if (rule.find(expectedTargetA) != std::string::npos) {
1613 if (rule.find(expectedTargetB) != std::string::npos) {
1614 matchCount++;
1615 }
1616 }
1617 }
1618 return matchCount == expectedCount;
1619 }
1620
expectXtQuotaValueEqual(const char * ifname,long quotaBytes)1621 void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1622 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1623 std::string result = "";
1624
1625 EXPECT_TRUE(ReadFileToString(path, &result));
1626 // Quota value might be decreased while matching packets
1627 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
1628 }
1629
expectBandwidthInterfaceQuotaRuleExists(const char * ifname,long quotaBytes)1630 void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1631 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1632 std::string quotaRule = StringPrintf("quota %s", ifname);
1633
1634 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1635 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1636 BANDWIDTH_COSTLY_IF));
1637 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1638 BANDWIDTH_COSTLY_IF));
1639 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1640 BANDWIDTH_COSTLY_IF));
1641 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1642 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1643 }
1644 expectXtQuotaValueEqual(ifname, quotaBytes);
1645 }
1646
expectBandwidthInterfaceQuotaRuleDoesNotExist(const char * ifname)1647 void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1648 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1649 std::string quotaRule = StringPrintf("quota %s", ifname);
1650
1651 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1652 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1653 BANDWIDTH_COSTLY_IF));
1654 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1655 BANDWIDTH_COSTLY_IF));
1656 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1657 BANDWIDTH_COSTLY_IF));
1658 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1659 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1660 }
1661 }
1662
expectBandwidthInterfaceAlertRuleExists(const char * ifname,long alertBytes)1663 void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1664 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1665 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1666 std::string alertName = StringPrintf("%sAlert", ifname);
1667
1668 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1669 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1670 }
1671 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1672 }
1673
expectBandwidthInterfaceAlertRuleDoesNotExist(const char * ifname)1674 void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1675 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1676 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1677
1678 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1679 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1680 }
1681 }
1682
expectBandwidthGlobalAlertRuleExists(long alertBytes)1683 void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1684 static const char globalAlertRule[] = "quota globalAlert";
1685 static const char globalAlertName[] = "globalAlert";
1686
1687 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1688 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
1689 }
1690 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1691 }
1692
1693 } // namespace
1694
TEST_F(NetdBinderTest,BandwidthSetRemoveInterfaceQuota)1695 TEST_F(NetdBinderTest, BandwidthSetRemoveInterfaceQuota) {
1696 long testQuotaBytes = 5550;
1697
1698 // Add test physical network
1699 const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
1700 INetd::PERMISSION_NONE, false);
1701 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
1702 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1703
1704 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1705 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1706 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1707
1708 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1709 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1710 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1711
1712 // Remove test physical network
1713 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1714 }
1715
TEST_F(NetdBinderTest,BandwidthSetRemoveInterfaceAlert)1716 TEST_F(NetdBinderTest, BandwidthSetRemoveInterfaceAlert) {
1717 long testAlertBytes = 373;
1718 // Add test physical network
1719 const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
1720 INetd::PERMISSION_NONE, false);
1721 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
1722 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1723 // Need to have a prior interface quota set to set an alert
1724 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1725 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1726 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1727 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1728
1729 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1730 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1731 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1732
1733 // Remove interface quota
1734 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1735 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1736 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1737
1738 // Remove test physical network
1739 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1740 }
1741
TEST_F(NetdBinderTest,BandwidthSetGlobalAlert)1742 TEST_F(NetdBinderTest, BandwidthSetGlobalAlert) {
1743 int64_t testAlertBytes = 2097200;
1744
1745 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1746 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1747 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1748
1749 testAlertBytes = 2098230;
1750 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1751 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1752 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1753 }
1754
1755 namespace {
1756
ipRouteString(const std::string & ifName,const std::string & dst,const std::string & nextHop,const std::string & mtu)1757 std::string ipRouteString(const std::string& ifName, const std::string& dst,
1758 const std::string& nextHop, const std::string& mtu) {
1759 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1760
1761 if (!nextHop.empty()) {
1762 dstString += " via " + nextHop;
1763 }
1764
1765 dstString += " dev " + ifName;
1766
1767 if (!mtu.empty()) {
1768 dstString += " proto static";
1769 // IPv6 routes report the metric, IPv4 routes report the scope.
1770 // TODO: move away from specifying the entire string and use a regexp instead.
1771 if (dst.find(':') != std::string::npos) {
1772 dstString += " metric 1024";
1773 } else {
1774 if (nextHop.empty()) {
1775 dstString += " scope link";
1776 }
1777 }
1778 dstString += " mtu " + mtu;
1779 }
1780
1781 return dstString;
1782 }
1783
expectNetworkRouteExistsWithMtu(const char * ipVersion,const std::string & ifName,const std::string & dst,const std::string & nextHop,const std::string & mtu,const char * table)1784 void expectNetworkRouteExistsWithMtu(const char* ipVersion, const std::string& ifName,
1785 const std::string& dst, const std::string& nextHop,
1786 const std::string& mtu, const char* table) {
1787 std::string routeString = ipRouteString(ifName, dst, nextHop, mtu);
1788 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop, mtu)))
1789 << "Couldn't find route to " << dst << ": '" << routeString << "' in table " << table;
1790 }
1791
expectNetworkRouteExists(const char * ipVersion,const std::string & ifName,const std::string & dst,const std::string & nextHop,const char * table)1792 void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1793 const std::string& dst, const std::string& nextHop,
1794 const char* table) {
1795 expectNetworkRouteExistsWithMtu(ipVersion, ifName, dst, nextHop, "", table);
1796 }
1797
expectNetworkRouteDoesNotExist(const char * ipVersion,const std::string & ifName,const std::string & dst,const std::string & nextHop,const char * table)1798 void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
1799 const std::string& dst, const std::string& nextHop,
1800 const char* table) {
1801 std::string routeString = ipRouteString(ifName, dst, nextHop, "");
1802 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop, "")))
1803 << "Found unexpected route " << routeString << " in table " << table;
1804 }
1805
ipRuleExists(const char * ipVersion,const std::string & ipRule)1806 bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1807 std::vector<std::string> rules = listIpRules(ipVersion);
1808 for (const auto& rule : rules) {
1809 if (rule.find(ipRule) != std::string::npos) {
1810 return true;
1811 }
1812 }
1813 return false;
1814 }
1815
expectNetworkDefaultIpRuleExists(const char * ifName)1816 void expectNetworkDefaultIpRuleExists(const char* ifName) {
1817 std::string networkDefaultRule =
1818 StringPrintf("%u:\tfrom all fwmark 0x0/0xffff iif lo lookup %s",
1819 RULE_PRIORITY_DEFAULT_NETWORK, ifName);
1820
1821 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1822 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1823 }
1824 }
1825
expectNetworkDefaultIpRuleDoesNotExist()1826 void expectNetworkDefaultIpRuleDoesNotExist() {
1827 std::string networkDefaultRule =
1828 StringPrintf("%u:\tfrom all fwmark 0x0/0xffff iif lo", RULE_PRIORITY_DEFAULT_NETWORK);
1829
1830 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1831 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1832 }
1833 }
1834
expectNetworkPermissionIpRuleExists(const char * ifName,int permission)1835 void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1836 std::string networkPermissionRule = "";
1837 switch (permission) {
1838 case INetd::PERMISSION_NONE:
1839 networkPermissionRule =
1840 StringPrintf("%u:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s",
1841 RULE_PRIORITY_EXPLICIT_NETWORK, ifName);
1842 break;
1843 case INetd::PERMISSION_NETWORK:
1844 networkPermissionRule =
1845 StringPrintf("%u:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s",
1846 RULE_PRIORITY_EXPLICIT_NETWORK, ifName);
1847 break;
1848 case INetd::PERMISSION_SYSTEM:
1849 networkPermissionRule =
1850 StringPrintf("%u:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s",
1851 RULE_PRIORITY_EXPLICIT_NETWORK, ifName);
1852 break;
1853 }
1854
1855 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1856 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1857 }
1858 }
1859
1860 // TODO: It is a duplicate function, need to remove it
iptablesNetworkPermissionIptablesRuleExists(const char * binary,const char * chainName,const std::string & expectedInterface,const std::string & expectedRule,const char * table)1861 bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1862 const std::string& expectedInterface,
1863 const std::string& expectedRule,
1864 const char* table) {
1865 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1866 for (const auto& rule : rules) {
1867 if (rule.find(expectedInterface) != std::string::npos) {
1868 if (rule.find(expectedRule) != std::string::npos) {
1869 return true;
1870 }
1871 }
1872 }
1873 return false;
1874 }
1875
expectNetworkPermissionIptablesRuleExists(const char * ifName,int permission)1876 void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1877 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1878 std::string networkIncomingPacketMarkRule = "";
1879 switch (permission) {
1880 case INetd::PERMISSION_NONE:
1881 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1882 break;
1883 case INetd::PERMISSION_NETWORK:
1884 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1885 break;
1886 case INetd::PERMISSION_SYSTEM:
1887 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1888 break;
1889 }
1890
1891 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1892 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1893 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1894 }
1895 }
1896
1897 } // namespace
1898
TEST_F(NetdBinderTest,NetworkAddRemoveRouteUserPermission)1899 TEST_F(NetdBinderTest, NetworkAddRemoveRouteUserPermission) {
1900 static const struct {
1901 const char* ipVersion;
1902 const char* testDest;
1903 const char* testNextHop;
1904 const bool expectSuccess;
1905 } kTestData[] = {
1906 {IP_RULE_V4, "0.0.0.0/0", "", true},
1907 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1908 {IP_RULE_V4, "10.251.0.0/16", "", true},
1909 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1910 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
1911 {IP_RULE_V6, "::/0", "", true},
1912 {IP_RULE_V6, "::/0", "2001:db8::", true},
1913 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
1914 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1915 };
1916
1917 static const struct {
1918 const char* ipVersion;
1919 const char* testDest;
1920 const char* testNextHop;
1921 } kTestDataWithNextHop[] = {
1922 {IP_RULE_V4, "10.251.10.0/30", ""},
1923 {IP_RULE_V6, "2001:db8::/32", ""},
1924 };
1925
1926 static const char testTableLegacySystem[] = "legacy_system";
1927 static const char testTableLegacyNetwork[] = "legacy_network";
1928 const int testUid = randomUid();
1929 const std::vector<int32_t> testUids = {testUid};
1930
1931 // Add test physical network
1932 const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
1933 INetd::PERMISSION_NONE, false);
1934 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
1935 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1936
1937 // Setup route for testing nextHop
1938 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
1939 const auto& td = kTestDataWithNextHop[i];
1940
1941 // All route for test tun will disappear once the tun interface is deleted.
1942 binder::Status status =
1943 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1944 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1945 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1946 sTun.name().c_str());
1947
1948 // Add system permission for test uid, setup route in legacy system table.
1949 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1950
1951 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1952 testUid);
1953 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1954 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1955 testTableLegacySystem);
1956
1957 // Remove system permission for test uid, setup route in legacy network table.
1958 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1959
1960 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1961 testUid);
1962 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1963 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1964 testTableLegacyNetwork);
1965 }
1966
1967 for (size_t i = 0; i < std::size(kTestData); i++) {
1968 const auto& td = kTestData[i];
1969
1970 binder::Status status =
1971 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1972 if (td.expectSuccess) {
1973 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1974 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1975 sTun.name().c_str());
1976 } else {
1977 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1978 EXPECT_NE(0, status.serviceSpecificErrorCode());
1979 }
1980
1981 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1982 if (td.expectSuccess) {
1983 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1984 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1985 sTun.name().c_str());
1986 } else {
1987 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1988 EXPECT_NE(0, status.serviceSpecificErrorCode());
1989 }
1990
1991 // Add system permission for test uid, route will be added into legacy system table.
1992 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1993
1994 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1995 testUid);
1996 if (td.expectSuccess) {
1997 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1998 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1999 testTableLegacySystem);
2000 } else {
2001 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
2002 EXPECT_NE(0, status.serviceSpecificErrorCode());
2003 }
2004
2005 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
2006 td.testNextHop, testUid);
2007 if (td.expectSuccess) {
2008 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2009 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
2010 testTableLegacySystem);
2011 } else {
2012 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
2013 EXPECT_NE(0, status.serviceSpecificErrorCode());
2014 }
2015
2016 // Remove system permission for test uid, route will be added into legacy network table.
2017 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
2018
2019 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
2020 testUid);
2021 if (td.expectSuccess) {
2022 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2023 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
2024 testTableLegacyNetwork);
2025 } else {
2026 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
2027 EXPECT_NE(0, status.serviceSpecificErrorCode());
2028 }
2029
2030 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
2031 td.testNextHop, testUid);
2032 if (td.expectSuccess) {
2033 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2034 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
2035 testTableLegacyNetwork);
2036 } else {
2037 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
2038 EXPECT_NE(0, status.serviceSpecificErrorCode());
2039 }
2040 }
2041
2042 for (size_t i = 0; i < std::size(kTestData); i++) {
2043 const auto& td = kTestData[i];
2044 int mtu = (i % 2) ? 1480 : 1280;
2045
2046 android::net::RouteInfoParcel parcel;
2047 parcel.ifName = sTun.name();
2048 parcel.destination = td.testDest;
2049 parcel.nextHop = td.testNextHop;
2050 parcel.mtu = mtu;
2051 binder::Status status = mNetd->networkAddRouteParcel(TEST_NETID1, parcel);
2052 if (td.expectSuccess) {
2053 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2054 expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
2055 std::to_string(parcel.mtu), sTun.name().c_str());
2056 } else {
2057 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
2058 EXPECT_NE(0, status.serviceSpecificErrorCode());
2059 }
2060
2061 parcel.mtu = 1337;
2062 status = mNetd->networkUpdateRouteParcel(TEST_NETID1, parcel);
2063 if (td.expectSuccess) {
2064 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2065 expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
2066 std::to_string(parcel.mtu), sTun.name().c_str());
2067 } else {
2068 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
2069 EXPECT_NE(0, status.serviceSpecificErrorCode());
2070 }
2071
2072 status = mNetd->networkRemoveRouteParcel(TEST_NETID1, parcel);
2073 if (td.expectSuccess) {
2074 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2075 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
2076 sTun.name().c_str());
2077 } else {
2078 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
2079 EXPECT_NE(0, status.serviceSpecificErrorCode());
2080 }
2081 }
2082 // Remove test physical network
2083 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2084 }
2085
TEST_F(NetdBinderTest,NetworkPermissionDefault)2086 TEST_F(NetdBinderTest, NetworkPermissionDefault) {
2087 // Add test physical network
2088 const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
2089 INetd::PERMISSION_NONE, false);
2090 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
2091 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2092
2093 // Get current default network NetId
2094 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
2095 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
2096
2097 // Test SetDefault
2098 status = mNetd->networkSetDefault(TEST_NETID1);
2099 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2100 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
2101
2102 status = mNetd->networkClearDefault();
2103 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2104 expectNetworkDefaultIpRuleDoesNotExist();
2105
2106 // Set default network back
2107 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
2108 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2109
2110 // Test SetPermission
2111 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
2112 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2113 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
2114 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
2115
2116 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
2117 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2118 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
2119 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
2120
2121 // Remove test physical network
2122 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2123 }
2124
TEST_F(NetdBinderTest,NetworkSetProtectAllowDeny)2125 TEST_F(NetdBinderTest, NetworkSetProtectAllowDeny) {
2126 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
2127 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2128 bool ret = false;
2129 status = mNetd->networkCanProtect(TEST_UID1, &ret);
2130 EXPECT_TRUE(ret);
2131
2132 status = mNetd->networkSetProtectDeny(TEST_UID1);
2133 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2134
2135 // Clear uid permission before calling networkCanProtect to ensure
2136 // the call won't be affected by uid permission.
2137 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
2138
2139 status = mNetd->networkCanProtect(TEST_UID1, &ret);
2140 EXPECT_FALSE(ret);
2141 }
2142
2143 namespace {
2144
readIntFromPath(const std::string & path)2145 int readIntFromPath(const std::string& path) {
2146 std::string result = "";
2147 EXPECT_TRUE(ReadFileToString(path, &result));
2148 return std::stoi(result);
2149 }
2150
getTetherAcceptIPv6Ra(const std::string & ifName)2151 int getTetherAcceptIPv6Ra(const std::string& ifName) {
2152 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
2153 return readIntFromPath(path);
2154 }
2155
getTetherAcceptIPv6Dad(const std::string & ifName)2156 bool getTetherAcceptIPv6Dad(const std::string& ifName) {
2157 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
2158 return readIntFromPath(path);
2159 }
2160
getTetherIPv6DadTransmits(const std::string & ifName)2161 int getTetherIPv6DadTransmits(const std::string& ifName) {
2162 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
2163 return readIntFromPath(path);
2164 }
2165
getTetherEnableIPv6(const std::string & ifName)2166 bool getTetherEnableIPv6(const std::string& ifName) {
2167 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2168 int disableIPv6 = readIntFromPath(path);
2169 return !disableIPv6;
2170 }
2171
interfaceListContains(const std::vector<std::string> & ifList,const std::string & ifName)2172 bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2173 for (const auto& iface : ifList) {
2174 if (iface == ifName) {
2175 return true;
2176 }
2177 }
2178 return false;
2179 }
2180
expectTetherInterfaceConfigureForIPv6Router(const std::string & ifName)2181 void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2182 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2183 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2184 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2185 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2186 }
2187
expectTetherInterfaceConfigureForIPv6Client(const std::string & ifName)2188 void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2189 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2190 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2191 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2192 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2193 }
2194
expectTetherInterfaceExists(const std::vector<std::string> & ifList,const std::string & ifName)2195 void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2196 const std::string& ifName) {
2197 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2198 }
2199
expectTetherInterfaceNotExists(const std::vector<std::string> & ifList,const std::string & ifName)2200 void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2201 const std::string& ifName) {
2202 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2203 }
2204
expectTetherDnsListEquals(const std::vector<std::string> & dnsList,const std::vector<std::string> & testDnsAddrs)2205 void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2206 const std::vector<std::string>& testDnsAddrs) {
2207 EXPECT_TRUE(dnsList == testDnsAddrs);
2208 }
2209
2210 } // namespace
2211
TEST_F(NetdBinderTest,TetherStartStopStatus)2212 TEST_F(NetdBinderTest, TetherStartStopStatus) {
2213 std::vector<std::string> noDhcpRange = {};
2214 for (bool usingLegacyDnsProxy : {true, false}) {
2215 android::net::TetherConfigParcel config;
2216 config.usingLegacyDnsProxy = usingLegacyDnsProxy;
2217 config.dhcpRanges = noDhcpRange;
2218 binder::Status status = mNetd->tetherStartWithConfiguration(config);
2219 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2220 SCOPED_TRACE(StringPrintf("usingLegacyDnsProxy: %d", usingLegacyDnsProxy));
2221 if (usingLegacyDnsProxy == true) {
2222 expectProcessExists(DNSMASQ);
2223 } else {
2224 expectProcessDoesNotExist(DNSMASQ);
2225 }
2226
2227 bool tetherEnabled;
2228 status = mNetd->tetherIsEnabled(&tetherEnabled);
2229 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2230 EXPECT_TRUE(tetherEnabled);
2231
2232 status = mNetd->tetherStop();
2233 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2234 expectProcessDoesNotExist(DNSMASQ);
2235
2236 status = mNetd->tetherIsEnabled(&tetherEnabled);
2237 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2238 EXPECT_FALSE(tetherEnabled);
2239 }
2240 }
2241
TEST_F(NetdBinderTest,TetherInterfaceAddRemoveList)2242 TEST_F(NetdBinderTest, TetherInterfaceAddRemoveList) {
2243 // TODO: verify if dnsmasq update interface successfully
2244
2245 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2246 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2247 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2248
2249 std::vector<std::string> ifList;
2250 status = mNetd->tetherInterfaceList(&ifList);
2251 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2252 expectTetherInterfaceExists(ifList, sTun.name());
2253
2254 status = mNetd->tetherInterfaceRemove(sTun.name());
2255 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2256 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2257
2258 status = mNetd->tetherInterfaceList(&ifList);
2259 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2260 expectTetherInterfaceNotExists(ifList, sTun.name());
2261 }
2262
TEST_F(NetdBinderTest,TetherDnsSetList)2263 TEST_F(NetdBinderTest, TetherDnsSetList) {
2264 // TODO: verify if dnsmasq update dns successfully
2265 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2266 "fe80::1%" + sTun.name()};
2267
2268 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2269 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2270
2271 std::vector<std::string> dnsList;
2272 status = mNetd->tetherDnsList(&dnsList);
2273 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2274 expectTetherDnsListEquals(dnsList, testDnsAddrs);
2275 }
2276
2277 namespace {
2278
findDnsSockets(SockDiag * sd,unsigned numExpected)2279 std::vector<IPAddress> findDnsSockets(SockDiag* sd, unsigned numExpected) {
2280 std::vector<IPAddress> listenAddrs;
2281
2282 // Callback lambda that finds all IPv4 sockets with source port 53.
2283 auto findDnsSockets = [&](uint8_t /* proto */, const inet_diag_msg* msg) {
2284 // Always return false, which means do not destroy this socket.
2285 if (msg->id.idiag_sport != htons(53)) return false;
2286 IPAddress addr(*(in_addr*)msg->id.idiag_src);
2287 listenAddrs.push_back(addr);
2288 return false;
2289 };
2290
2291 // There is no way to know if dnsmasq has finished processing the update_interfaces command and
2292 // opened listening sockets. So, just spin a few times and return the first list of sockets
2293 // that is at least numExpected long.
2294 // Pick a relatively large timeout to avoid flaky tests, particularly when running on shared
2295 // devices.
2296 constexpr int kMaxAttempts = 50;
2297 constexpr int kSleepMs = 100;
2298 for (int i = 0; i < kMaxAttempts; i++) {
2299 listenAddrs.clear();
2300 EXPECT_EQ(0, sd->sendDumpRequest(IPPROTO_TCP, AF_INET, 1 << TCP_LISTEN))
2301 << "Failed to dump sockets, attempt " << i << " of " << kMaxAttempts;
2302 sd->readDiagMsg(IPPROTO_TCP, findDnsSockets);
2303 if (listenAddrs.size() >= numExpected) {
2304 break;
2305 }
2306 usleep(kSleepMs * 1000);
2307 }
2308
2309 return listenAddrs;
2310 }
2311
2312 } // namespace
2313
2314 // Checks that when starting dnsmasq on an interface that no longer exists, it doesn't attempt to
2315 // start on other interfaces instead.
TEST_F(NetdBinderTest,TetherDeletedInterface)2316 TEST_F(NetdBinderTest, TetherDeletedInterface) {
2317 // Do this first so we don't need to clean up anything else if it fails.
2318 SockDiag sd;
2319 ASSERT_TRUE(sd.open()) << "Failed to open SOCK_DIAG socket";
2320
2321 // Create our own TunInterfaces (so we can delete them without affecting other tests), and add
2322 // IP addresses to them. They must be IPv4 because tethering an interface disables and
2323 // re-enables IPv6 on the interface, which clears all addresses.
2324 TunInterface tun1, tun2;
2325 ASSERT_EQ(0, tun1.init());
2326 ASSERT_EQ(0, tun2.init());
2327
2328 // Clean up. It is safe to call TunInterface::destroy multiple times.
2329 auto guard = android::base::make_scope_guard([&] {
2330 tun1.destroy();
2331 tun2.destroy();
2332 mNetd->tetherStop();
2333 mNetd->tetherInterfaceRemove(tun1.name());
2334 mNetd->tetherInterfaceRemove(tun2.name());
2335 });
2336
2337 IPAddress addr1, addr2;
2338 ASSERT_TRUE(IPAddress::forString("192.0.2.1", &addr1));
2339 ASSERT_TRUE(IPAddress::forString("192.0.2.2", &addr2));
2340 EXPECT_EQ(0, tun1.addAddress(addr1.toString(), 32));
2341 EXPECT_EQ(0, tun2.addAddress(addr2.toString(), 32));
2342
2343 // Stop tethering.
2344 binder::Status status = mNetd->tetherStop();
2345 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2346
2347 // Start dnsmasq on an interface that doesn't exist.
2348 // First, tether our tun interface...
2349 status = mNetd->tetherInterfaceAdd(tun1.name());
2350 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2351 expectTetherInterfaceConfigureForIPv6Router(tun1.name());
2352
2353 // ... then delete it...
2354 tun1.destroy();
2355
2356 // ... then start dnsmasq.
2357 android::net::TetherConfigParcel config;
2358 config.usingLegacyDnsProxy = true;
2359 config.dhcpRanges = {};
2360 status = mNetd->tetherStartWithConfiguration(config);
2361 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2362
2363 // Wait for dnsmasq to start.
2364 expectProcessExists(DNSMASQ);
2365
2366 // Make sure that netd thinks the interface is tethered (even though it doesn't exist).
2367 std::vector<std::string> ifList;
2368 status = mNetd->tetherInterfaceList(&ifList);
2369 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2370 ASSERT_EQ(1U, ifList.size());
2371 EXPECT_EQ(tun1.name(), ifList[0]);
2372
2373 // Give dnsmasq some time to start up.
2374 usleep(200 * 1000);
2375
2376 // Check that dnsmasq is not listening on any IP addresses. It shouldn't, because it was only
2377 // told to run on tun1, and tun1 does not exist. Ensure it stays running and doesn't listen on
2378 // any IP addresses.
2379 std::vector<IPAddress> listenAddrs = findDnsSockets(&sd, 0);
2380 EXPECT_EQ(0U, listenAddrs.size()) << "Unexpectedly found IPv4 socket(s) listening on port 53";
2381
2382 // Now add an interface to dnsmasq and check that we can see the sockets. This confirms that
2383 // findDnsSockets is actually able to see sockets when they exist.
2384 status = mNetd->tetherInterfaceAdd(tun2.name());
2385 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2386
2387 in_addr loopback = {htonl(INADDR_LOOPBACK)};
2388 listenAddrs = findDnsSockets(&sd, 2);
2389 EXPECT_EQ(2U, listenAddrs.size()) << "Expected exactly 2 IPv4 sockets listening on port 53";
2390 EXPECT_EQ(1, std::count(listenAddrs.begin(), listenAddrs.end(), addr2));
2391 EXPECT_EQ(1, std::count(listenAddrs.begin(), listenAddrs.end(), IPAddress(loopback)));
2392
2393 // Clean up.
2394 status = mNetd->tetherStop();
2395 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2396
2397 expectProcessDoesNotExist(DNSMASQ);
2398
2399 status = mNetd->tetherInterfaceRemove(tun1.name());
2400 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2401
2402 status = mNetd->tetherInterfaceRemove(tun2.name());
2403 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2404 }
2405
2406 namespace {
2407
2408 constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2409 constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2410 constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2411
expectFirewallAllowlistMode()2412 void expectFirewallAllowlistMode() {
2413 static const char dropRule[] = "DROP all";
2414 static const char rejectRule[] = "REJECT all";
2415 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2416 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2417 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2418 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2419 }
2420 }
2421
expectFirewallDenylistMode()2422 void expectFirewallDenylistMode() {
2423 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2424 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2425 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2426 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2427 }
2428 }
2429
iptablesFirewallInterfaceFirstRuleExists(const char * binary,const char * chainName,const std::string & expectedInterface,const std::string & expectedRule)2430 bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2431 const std::string& expectedInterface,
2432 const std::string& expectedRule) {
2433 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2434 // Expected rule:
2435 // Chain fw_INPUT (1 references)
2436 // pkts bytes target prot opt in out source destination
2437 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2438 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2439 int firstRuleIndex = 2;
2440 if (rules.size() < 4) return false;
2441 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2442 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2443 return true;
2444 }
2445 }
2446 return false;
2447 }
2448
2449 // TODO: It is a duplicate function, need to remove it
iptablesFirewallInterfaceRuleExists(const char * binary,const char * chainName,const std::string & expectedInterface,const std::string & expectedRule)2450 bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2451 const std::string& expectedInterface,
2452 const std::string& expectedRule) {
2453 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2454 for (const auto& rule : rules) {
2455 if (rule.find(expectedInterface) != std::string::npos) {
2456 if (rule.find(expectedRule) != std::string::npos) {
2457 return true;
2458 }
2459 }
2460 }
2461 return false;
2462 }
2463
expectFirewallInterfaceRuleAllowExists(const std::string & ifname)2464 void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2465 static const char returnRule[] = "RETURN all";
2466 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2467 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2468 returnRule));
2469 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2470 returnRule));
2471 }
2472 }
2473
expectFireWallInterfaceRuleAllowDoesNotExist(const std::string & ifname)2474 void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2475 static const char returnRule[] = "RETURN all";
2476 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2477 EXPECT_FALSE(
2478 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2479 EXPECT_FALSE(
2480 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2481 }
2482 }
2483
2484 } // namespace
2485
TEST_F(NetdBinderTest,FirewallSetFirewallType)2486 TEST_F(NetdBinderTest, FirewallSetFirewallType) {
2487 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_ALLOWLIST);
2488 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2489 expectFirewallAllowlistMode();
2490
2491 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_DENYLIST);
2492 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2493 expectFirewallDenylistMode();
2494
2495 // set firewall type blacklist twice
2496 mNetd->firewallSetFirewallType(INetd::FIREWALL_DENYLIST);
2497 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_DENYLIST);
2498 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2499 expectFirewallDenylistMode();
2500
2501 // set firewall type whitelist twice
2502 mNetd->firewallSetFirewallType(INetd::FIREWALL_ALLOWLIST);
2503 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_ALLOWLIST);
2504 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2505 expectFirewallAllowlistMode();
2506
2507 // reset firewall type to default
2508 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_DENYLIST);
2509 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2510 expectFirewallDenylistMode();
2511 }
2512
TEST_F(NetdBinderTest,FirewallSetInterfaceRule)2513 TEST_F(NetdBinderTest, FirewallSetInterfaceRule) {
2514 // setinterfaceRule is not supported in BLACKLIST MODE
2515 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_DENYLIST);
2516 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2517
2518 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2519 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2520
2521 // set WHITELIST mode first
2522 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_ALLOWLIST);
2523 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2524
2525 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2526 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2527 expectFirewallInterfaceRuleAllowExists(sTun.name());
2528
2529 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2530 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2531 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2532
2533 // reset firewall mode to default
2534 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_DENYLIST);
2535 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2536 expectFirewallDenylistMode();
2537 }
2538
2539 namespace {
2540
hwAddrToStr(unsigned char * hwaddr)2541 std::string hwAddrToStr(unsigned char* hwaddr) {
2542 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2543 hwaddr[4], hwaddr[5]);
2544 }
2545
ipv4NetmaskToPrefixLength(in_addr_t mask)2546 int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2547 int prefixLength = 0;
2548 uint32_t m = ntohl(mask);
2549 while (m & (1 << 31)) {
2550 prefixLength++;
2551 m = m << 1;
2552 }
2553 return prefixLength;
2554 }
2555
toStdString(const String16 & s)2556 std::string toStdString(const String16& s) {
2557 return std::string(String8(s.string()));
2558 }
2559
ioctlByIfName(const std::string & ifName,unsigned long flag)2560 android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2561 const auto& sys = sSyscalls.get();
2562 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2563 EXPECT_TRUE(isOk(fd.status()));
2564
2565 struct ifreq ifr = {};
2566 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2567
2568 return sys.ioctl(fd.value(), flag, &ifr);
2569 }
2570
getInterfaceHwAddr(const std::string & ifName)2571 std::string getInterfaceHwAddr(const std::string& ifName) {
2572 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2573
2574 unsigned char hwaddr[ETH_ALEN] = {};
2575 if (isOk(res.status())) {
2576 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2577 }
2578
2579 return hwAddrToStr(hwaddr);
2580 }
2581
getInterfaceIPv4Prefix(const std::string & ifName)2582 int getInterfaceIPv4Prefix(const std::string& ifName) {
2583 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2584
2585 int prefixLength = 0;
2586 if (isOk(res.status())) {
2587 prefixLength = ipv4NetmaskToPrefixLength(
2588 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2589 }
2590
2591 return prefixLength;
2592 }
2593
getInterfaceIPv4Addr(const std::string & ifName)2594 std::string getInterfaceIPv4Addr(const std::string& ifName) {
2595 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2596
2597 struct in_addr addr = {};
2598 if (isOk(res.status())) {
2599 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2600 }
2601
2602 return std::string(inet_ntoa(addr));
2603 }
2604
getInterfaceFlags(const std::string & ifName)2605 std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2606 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2607
2608 unsigned flags = 0;
2609 if (isOk(res.status())) {
2610 flags = res.value().ifr_flags;
2611 }
2612
2613 std::vector<std::string> ifFlags;
2614 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2615 : toStdString(INetd::IF_STATE_DOWN()));
2616
2617 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2618 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2619 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2620 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2621 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2622
2623 return ifFlags;
2624 }
2625
compareListInterface(const std::vector<std::string> & interfaceList)2626 bool compareListInterface(const std::vector<std::string>& interfaceList) {
2627 const auto& res = InterfaceController::getIfaceNames();
2628 EXPECT_TRUE(isOk(res));
2629
2630 std::vector<std::string> resIfList;
2631 resIfList.reserve(res.value().size());
2632 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2633
2634 return resIfList == interfaceList;
2635 }
2636
getInterfaceIPv6PrivacyExtensions(const std::string & ifName)2637 int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2638 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2639 return readIntFromPath(path);
2640 }
2641
getInterfaceEnableIPv6(const std::string & ifName)2642 bool getInterfaceEnableIPv6(const std::string& ifName) {
2643 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2644
2645 int disableIPv6 = readIntFromPath(path);
2646 return !disableIPv6;
2647 }
2648
getInterfaceMtu(const std::string & ifName)2649 int getInterfaceMtu(const std::string& ifName) {
2650 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2651 return readIntFromPath(path);
2652 }
2653
expectInterfaceList(const std::vector<std::string> & interfaceList)2654 void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2655 EXPECT_TRUE(compareListInterface(interfaceList));
2656 }
2657
expectCurrentInterfaceConfigurationEquals(const std::string & ifName,const InterfaceConfigurationParcel & interfaceCfg)2658 void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2659 const InterfaceConfigurationParcel& interfaceCfg) {
2660 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2661 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2662 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2663 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2664 }
2665
expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel & setCfg)2666 void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2667 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2668 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2669
2670 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2671 for (const auto& flag : setCfg.flags) {
2672 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2673 }
2674 }
2675
expectInterfaceIPv6PrivacyExtensions(const std::string & ifName,bool enable)2676 void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2677 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2678 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2679 }
2680
expectInterfaceNoAddr(const std::string & ifName)2681 void expectInterfaceNoAddr(const std::string& ifName) {
2682 // noAddr
2683 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2684 // noPrefix
2685 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2686 }
2687
expectInterfaceEnableIPv6(const std::string & ifName,bool enable)2688 void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2689 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2690 EXPECT_EQ(enableIPv6, enable);
2691 }
2692
expectInterfaceMtu(const std::string & ifName,const int mtu)2693 void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2694 int mtuSize = getInterfaceMtu(ifName);
2695 EXPECT_EQ(mtu, mtuSize);
2696 }
2697
makeInterfaceCfgParcel(const std::string & ifName,const std::string & addr,int prefixLength,const std::vector<std::string> & flags)2698 InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2699 const std::string& addr, int prefixLength,
2700 const std::vector<std::string>& flags) {
2701 InterfaceConfigurationParcel cfg;
2702 cfg.ifName = ifName;
2703 cfg.hwAddr = "";
2704 cfg.ipv4Addr = addr;
2705 cfg.prefixLength = prefixLength;
2706 cfg.flags = flags;
2707 return cfg;
2708 }
2709
expectTunFlags(const InterfaceConfigurationParcel & interfaceCfg)2710 void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2711 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2712 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2713
2714 for (const auto& flag : expectedFlags) {
2715 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2716 interfaceCfg.flags.end());
2717 }
2718
2719 for (const auto& flag : unexpectedFlags) {
2720 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2721 interfaceCfg.flags.end());
2722 }
2723 }
2724
2725 } // namespace
2726
TEST_F(NetdBinderTest,InterfaceList)2727 TEST_F(NetdBinderTest, InterfaceList) {
2728 std::vector<std::string> interfaceListResult;
2729
2730 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2731 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2732 expectInterfaceList(interfaceListResult);
2733 }
2734
TEST_F(NetdBinderTest,InterfaceGetCfg)2735 TEST_F(NetdBinderTest, InterfaceGetCfg) {
2736 InterfaceConfigurationParcel interfaceCfgResult;
2737
2738 // Add test physical network
2739 const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
2740 INetd::PERMISSION_NONE, false);
2741 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
2742 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2743
2744 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2745 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2746 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2747 expectTunFlags(interfaceCfgResult);
2748
2749 // Remove test physical network
2750 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2751 }
2752
TEST_F(NetdBinderTest,InterfaceSetCfg)2753 TEST_F(NetdBinderTest, InterfaceSetCfg) {
2754 const std::string testAddr = "192.0.2.3";
2755 const int testPrefixLength = 24;
2756 std::vector<std::string> upFlags = {"up"};
2757 std::vector<std::string> downFlags = {"down"};
2758
2759 // Add test physical network
2760 const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
2761 INetd::PERMISSION_NONE, false);
2762 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
2763 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2764
2765 // Set tun interface down.
2766 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2767 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2768 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2769 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2770
2771 // Set tun interface up again.
2772 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2773 status = mNetd->interfaceSetCfg(interfaceCfg);
2774 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2775 status = mNetd->interfaceClearAddrs(sTun.name());
2776 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2777
2778 // Remove test physical network
2779 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2780 }
2781
TEST_F(NetdBinderTest,InterfaceSetIPv6PrivacyExtensions)2782 TEST_F(NetdBinderTest, InterfaceSetIPv6PrivacyExtensions) {
2783 // enable
2784 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2785 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2786 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2787
2788 // disable
2789 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2790 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2791 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2792 }
2793
TEST_F(NetdBinderTest,InterfaceClearAddr)2794 TEST_F(NetdBinderTest, InterfaceClearAddr) {
2795 const std::string testAddr = "192.0.2.3";
2796 const int testPrefixLength = 24;
2797 std::vector<std::string> noFlags{};
2798
2799 // Add test physical network
2800 const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
2801 INetd::PERMISSION_NONE, false);
2802 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
2803 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2804
2805 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2806 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2807 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2808 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2809
2810 status = mNetd->interfaceClearAddrs(sTun.name());
2811 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2812 expectInterfaceNoAddr(sTun.name());
2813
2814 // Remove test physical network
2815 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2816 }
2817
TEST_F(NetdBinderTest,InterfaceSetEnableIPv6)2818 TEST_F(NetdBinderTest, InterfaceSetEnableIPv6) {
2819 // Add test physical network
2820 const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
2821 INetd::PERMISSION_NONE, false);
2822 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
2823 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2824
2825 // disable
2826 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2827 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2828 expectInterfaceEnableIPv6(sTun.name(), false);
2829
2830 // enable
2831 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2832 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2833 expectInterfaceEnableIPv6(sTun.name(), true);
2834
2835 // Remove test physical network
2836 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2837 }
2838
TEST_F(NetdBinderTest,InterfaceSetMtu)2839 TEST_F(NetdBinderTest, InterfaceSetMtu) {
2840 const int testMtu = 1200;
2841
2842 // Add test physical network
2843 const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
2844 INetd::PERMISSION_NONE, false);
2845 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
2846 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2847
2848 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2849 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2850 expectInterfaceMtu(sTun.name(), testMtu);
2851
2852 // Remove test physical network
2853 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2854 }
2855
2856 namespace {
2857
2858 constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2859 constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
2860 constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
2861 constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2862
iptablesCountRules(const char * binary,const char * table,const char * chainName)2863 int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
2864 return listIptablesRuleByTable(binary, table, chainName).size();
2865 }
2866
iptablesChainMatch(const char * binary,const char * table,const char * chainName,const std::vector<std::string> & targetVec)2867 bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2868 const std::vector<std::string>& targetVec) {
2869 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2870 if (targetVec.size() != rules.size() - 2) {
2871 return false;
2872 }
2873
2874 /*
2875 * Check that the rules match. Note that this function matches substrings, not entire rules,
2876 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
2877 * Skip first two lines since rules start from third line.
2878 * Chain chainName (x references)
2879 * pkts bytes target prot opt in out source destination
2880 * ...
2881 */
2882 int rIndex = 2;
2883 for (const auto& target : targetVec) {
2884 if (rules[rIndex].find(target) == std::string::npos) {
2885 return false;
2886 }
2887 rIndex++;
2888 }
2889 return true;
2890 }
2891
expectNatEnable(const std::string & intIf,const std::string & extIf)2892 void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2893 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2894 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2895 std::vector<std::string> forwardV4Match = {
2896 "bw_global_alert", "state RELATED", "state INVALID",
2897 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2898 "DROP"};
2899
2900 // V4
2901 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2902 postroutingV4Match));
2903 EXPECT_TRUE(
2904 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
2905 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2906
2907 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
2908 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2909
2910 // V6
2911 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
2912 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2913 preroutingV6Match));
2914
2915 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2916 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2917 extIf));
2918 }
2919 }
2920
expectNatDisable()2921 void expectNatDisable() {
2922 // It is the default DROP rule with tethering disable.
2923 // Chain tetherctrl_FORWARD (1 references)
2924 // pkts bytes target prot opt in out source destination
2925 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2926 std::vector<std::string> forwardV4Match = {"DROP"};
2927 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2928
2929 // We expect that these chains should be empty.
2930 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2931 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
2932
2933 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2934 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
2935
2936 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2937 }
2938
2939 } // namespace
2940
TEST_F(NetdBinderTest,TetherForwardAddRemove)2941 TEST_F(NetdBinderTest, TetherForwardAddRemove) {
2942 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2943 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2944 expectNatEnable(sTun.name(), sTun2.name());
2945
2946 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2947 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2948 expectNatDisable();
2949 }
2950
2951 namespace {
2952
2953 using TripleInt = std::array<int, 3>;
2954
readProcFileToTripleInt(const std::string & path)2955 TripleInt readProcFileToTripleInt(const std::string& path) {
2956 std::string valueString;
2957 int min, def, max;
2958 EXPECT_TRUE(ReadFileToString(path, &valueString));
2959 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2960 return {min, def, max};
2961 }
2962
updateAndCheckTcpBuffer(sp<INetd> & netd,TripleInt & rmemValues,TripleInt & wmemValues)2963 void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2964 std::string testRmemValues =
2965 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2966 std::string testWmemValues =
2967 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2968 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2969
2970 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2971 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2972
2973 for (int i = 0; i < 3; i++) {
2974 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2975 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2976 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2977 }
2978 }
2979
2980 } // namespace
2981
TEST_F(NetdBinderTest,TcpBufferSet)2982 TEST_F(NetdBinderTest, TcpBufferSet) {
2983 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2984 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2985 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2986 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2987
2988 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2989 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2990 }
2991
2992 namespace {
2993
checkUidsInPermissionMap(std::vector<int32_t> & uids,bool exist)2994 void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
2995 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(UID_PERMISSION_MAP_PATH);
2996 for (int32_t uid : uids) {
2997 android::base::Result<uint8_t> permission = uidPermissionMap.readValue(uid);
2998 if (exist) {
2999 ASSERT_RESULT_OK(permission);
3000 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
3001 } else {
3002 ASSERT_FALSE(permission.ok());
3003 EXPECT_EQ(ENOENT, permission.error().code());
3004 }
3005 }
3006 }
3007
3008 } // namespace
3009
TEST_F(NetdBinderTest,TestInternetPermission)3010 TEST_F(NetdBinderTest, TestInternetPermission) {
3011 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
3012
3013 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
3014 checkUidsInPermissionMap(appUids, false);
3015 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
3016 checkUidsInPermissionMap(appUids, true);
3017 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
3018 checkUidsInPermissionMap(appUids, false);
3019 }
3020
TEST_F(NetdBinderTest,UnsolEvents)3021 TEST_F(NetdBinderTest, UnsolEvents) {
3022 auto testUnsolService = android::net::TestUnsolService::start();
3023 std::string oldTunName = sTun.name();
3024 std::string newTunName = "unsolTest";
3025 testUnsolService->tarVec.push_back(oldTunName);
3026 testUnsolService->tarVec.push_back(newTunName);
3027 auto& cv = testUnsolService->getCv();
3028 auto& cvMutex = testUnsolService->getCvMutex();
3029 binder::Status status = mNetd->registerUnsolicitedEventListener(
3030 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
3031 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3032
3033 // TODO: Add test for below events
3034 // StrictCleartextDetected / InterfaceDnsServersAdded
3035 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
3036
3037 {
3038 std::unique_lock lock(cvMutex);
3039
3040 // Re-init test Tun, and we expect that we will get some unsol events.
3041 // Use the test Tun device name to verify if we receive its unsol events.
3042 sTun.destroy();
3043 // Use predefined name
3044 sTun.init(newTunName);
3045
3046 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3047 }
3048
3049 // bit mask 1101101000
3050 // Test only covers below events currently
3051 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
3052 InterfaceLinkStatusChanged | RouteChanged;
3053 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
3054
3055 // Re-init sTun to clear predefined name
3056 sTun.destroy();
3057 sTun.init();
3058 }
3059
TEST_F(NetdBinderTest,NDC)3060 TEST_F(NetdBinderTest, NDC) {
3061 struct Command {
3062 const std::string cmdString;
3063 const std::string expectedResult;
3064 };
3065
3066 // clang-format off
3067 // Do not change the commands order
3068 const Command networkCmds[] = {
3069 {StringPrintf("ndc network create %d", TEST_NETID1),
3070 "200 0 success"},
3071 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
3072 "200 0 success"},
3073 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
3074 "200 0 success"},
3075 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
3076 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
3077 {StringPrintf("ndc network destroy %d", TEST_NETID1),
3078 "200 0 success"},
3079 };
3080
3081 const std::vector<Command> ipfwdCmds = {
3082 {"ndc ipfwd enable " + sTun.name(),
3083 "200 0 ipfwd operation succeeded"},
3084 {"ndc ipfwd disable " + sTun.name(),
3085 "200 0 ipfwd operation succeeded"},
3086 {"ndc ipfwd add lo2 lo3",
3087 "400 0 ipfwd operation failed (No such process)"},
3088 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
3089 "200 0 ipfwd operation succeeded"},
3090 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
3091 "200 0 ipfwd operation succeeded"},
3092 };
3093
3094 static const struct {
3095 const char* ipVersion;
3096 const char* testDest;
3097 const char* testNextHop;
3098 const bool expectSuccess;
3099 const std::string expectedResult;
3100 } kTestData[] = {
3101 {IP_RULE_V4, "0.0.0.0/0", "", true,
3102 "200 0 success"},
3103 {IP_RULE_V4, "10.251.0.0/16", "", true,
3104 "200 0 success"},
3105 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
3106 "400 0 addRoute() failed (Invalid argument)",},
3107 {IP_RULE_V6, "::/0", "", true,
3108 "200 0 success"},
3109 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
3110 "200 0 success"},
3111 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
3112 "400 0 addRoute() failed (Invalid argument)"},
3113 };
3114 // clang-format on
3115
3116 for (const auto& cmd : networkCmds) {
3117 const std::vector<std::string> result = runCommand(cmd.cmdString);
3118 SCOPED_TRACE(cmd.cmdString);
3119 EXPECT_EQ(result.size(), 1U);
3120 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3121 }
3122
3123 for (const auto& cmd : ipfwdCmds) {
3124 const std::vector<std::string> result = runCommand(cmd.cmdString);
3125 SCOPED_TRACE(cmd.cmdString);
3126 EXPECT_EQ(result.size(), 1U);
3127 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3128 }
3129
3130 // Add test physical network
3131 const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
3132 INetd::PERMISSION_NONE, false);
3133 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
3134 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3135
3136 for (const auto& td : kTestData) {
3137 const std::string routeAddCmd =
3138 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
3139 td.testDest, td.testNextHop);
3140 const std::string routeRemoveCmd =
3141 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
3142 sTun.name().c_str(), td.testDest, td.testNextHop);
3143 std::vector<std::string> result = runCommand(routeAddCmd);
3144 SCOPED_TRACE(routeAddCmd);
3145 EXPECT_EQ(result.size(), 1U);
3146 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3147 if (td.expectSuccess) {
3148 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3149 sTun.name().c_str());
3150 result = runCommand(routeRemoveCmd);
3151 EXPECT_EQ(result.size(), 1U);
3152 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3153 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3154 sTun.name().c_str());
3155 }
3156 }
3157 // Remove test physical network
3158 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
3159 }
3160
TEST_F(NetdBinderTest,OemNetdRelated)3161 TEST_F(NetdBinderTest, OemNetdRelated) {
3162 sp<IBinder> binder;
3163 binder::Status status = mNetd->getOemNetd(&binder);
3164 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3165 sp<com::android::internal::net::IOemNetd> oemNetd;
3166 if (binder != nullptr) {
3167 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3168 }
3169 ASSERT_NE(nullptr, oemNetd.get());
3170
3171 TimedOperation t("OemNetd isAlive RPC");
3172 bool isAlive = false;
3173 oemNetd->isAlive(&isAlive);
3174 ASSERT_TRUE(isAlive);
3175
3176 class TestOemUnsolListener
3177 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3178 public:
3179 android::binder::Status onRegistered() override {
3180 std::lock_guard lock(mCvMutex);
3181 mCv.notify_one();
3182 return android::binder::Status::ok();
3183 }
3184 std::condition_variable& getCv() { return mCv; }
3185 std::mutex& getCvMutex() { return mCvMutex; }
3186
3187 private:
3188 std::mutex mCvMutex;
3189 std::condition_variable mCv;
3190 };
3191
3192 // Start the Binder thread pool.
3193 android::ProcessState::self()->startThreadPool();
3194
3195 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3196
3197 auto& cv = testListener->getCv();
3198 auto& cvMutex = testListener->getCvMutex();
3199
3200 {
3201 std::unique_lock lock(cvMutex);
3202
3203 status = oemNetd->registerOemUnsolicitedEventListener(
3204 ::android::interface_cast<
3205 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3206 testListener));
3207 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3208
3209 // Wait for receiving expected events.
3210 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3211 }
3212 }
3213
createVpnNetworkWithUid(bool secure,uid_t uid,int vpnNetId,int fallthroughNetId)3214 void NetdBinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3215 int fallthroughNetId) {
3216 // Re-init sTun* to ensure route rule exists.
3217 sTun.destroy();
3218 sTun.init();
3219 sTun2.destroy();
3220 sTun2.init();
3221
3222 // Create physical network with fallthroughNetId but not set it as default network
3223 auto config = makeNativeNetworkConfig(fallthroughNetId, NativeNetworkType::PHYSICAL,
3224 INetd::PERMISSION_NONE, false);
3225 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
3226 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3227
3228 // Create VPN with vpnNetId
3229 config.netId = vpnNetId;
3230 config.networkType = NativeNetworkType::VIRTUAL;
3231 config.secure = secure;
3232 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
3233
3234 // Add uid to VPN
3235 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3236 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3237
3238 // Add default route to fallthroughNetwork
3239 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3240 // Add limited route
3241 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3242 }
3243
createAndSetDefaultNetwork(int netId,const std::string & interface,int permission)3244 void NetdBinderTest::createAndSetDefaultNetwork(int netId, const std::string& interface,
3245 int permission) {
3246 // backup current default network.
3247 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3248
3249 const auto& config =
3250 makeNativeNetworkConfig(netId, NativeNetworkType::PHYSICAL, permission, false);
3251 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
3252 EXPECT_TRUE(mNetd->networkAddInterface(netId, interface).isOk());
3253 EXPECT_TRUE(mNetd->networkSetDefault(netId).isOk());
3254 }
3255
createPhysicalNetwork(int netId,const std::string & interface,int permission)3256 void NetdBinderTest::createPhysicalNetwork(int netId, const std::string& interface,
3257 int permission) {
3258 const auto& config =
3259 makeNativeNetworkConfig(netId, NativeNetworkType::PHYSICAL, permission, false);
3260 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
3261 EXPECT_TRUE(mNetd->networkAddInterface(netId, interface).isOk());
3262 }
3263
3264 // 1. Create a physical network on sTun, and set it as the system default network.
3265 // 2. Create another physical network on sTun2.
createDefaultAndOtherPhysicalNetwork(int defaultNetId,int otherNetId)3266 void NetdBinderTest::createDefaultAndOtherPhysicalNetwork(int defaultNetId, int otherNetId) {
3267 createAndSetDefaultNetwork(defaultNetId, sTun.name());
3268 EXPECT_TRUE(mNetd->networkAddRoute(defaultNetId, sTun.name(), "::/0", "").isOk());
3269
3270 createPhysicalNetwork(otherNetId, sTun2.name());
3271 EXPECT_TRUE(mNetd->networkAddRoute(otherNetId, sTun2.name(), "::/0", "").isOk());
3272 }
3273
3274 // 1. Create a system default network and a physical network.
3275 // 2. Create a VPN on sTun3.
createVpnAndOtherPhysicalNetwork(int systemDefaultNetId,int otherNetId,int vpnNetId,bool secure)3276 void NetdBinderTest::createVpnAndOtherPhysicalNetwork(int systemDefaultNetId, int otherNetId,
3277 int vpnNetId, bool secure) {
3278 createDefaultAndOtherPhysicalNetwork(systemDefaultNetId, otherNetId);
3279
3280 auto config = makeNativeNetworkConfig(vpnNetId, NativeNetworkType::VIRTUAL,
3281 INetd::PERMISSION_NONE, secure);
3282 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
3283 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun3.name()).isOk());
3284 EXPECT_TRUE(mNetd->networkAddRoute(vpnNetId, sTun3.name(), "2001:db8::/32", "").isOk());
3285 }
3286
3287 // 1. Create system default network, a physical network (for per-app default), and a VPN.
3288 // 2. Add per-app uid ranges and VPN ranges.
createVpnAndAppDefaultNetworkWithUid(int systemDefaultNetId,int appDefaultNetId,int vpnNetId,bool secure,std::vector<UidRangeParcel> && appDefaultUidRanges,std::vector<UidRangeParcel> && vpnUidRanges)3289 void NetdBinderTest::createVpnAndAppDefaultNetworkWithUid(
3290 int systemDefaultNetId, int appDefaultNetId, int vpnNetId, bool secure,
3291 std::vector<UidRangeParcel>&& appDefaultUidRanges,
3292 std::vector<UidRangeParcel>&& vpnUidRanges) {
3293 createVpnAndOtherPhysicalNetwork(systemDefaultNetId, appDefaultNetId, vpnNetId, secure);
3294 // add per-app uid ranges.
3295 EXPECT_TRUE(mNetd->networkAddUidRanges(appDefaultNetId, appDefaultUidRanges).isOk());
3296 // add VPN uid ranges.
3297 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, vpnUidRanges).isOk());
3298 }
3299
3300 namespace {
3301
3302 class ScopedUidChange {
3303 public:
ScopedUidChange(uid_t uid)3304 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3305 mStoredUid = geteuid();
3306 if (mInputUid == mStoredUid) return;
3307 EXPECT_TRUE(seteuid(uid) == 0);
3308 }
~ScopedUidChange()3309 ~ScopedUidChange() {
3310 if (mInputUid == mStoredUid) return;
3311 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3312 }
3313
3314 private:
3315 uid_t mInputUid;
3316 uid_t mStoredUid;
3317 };
3318
clearQueue(int tunFd)3319 void clearQueue(int tunFd) {
3320 char buf[4096];
3321 int ret;
3322 do {
3323 ret = read(tunFd, buf, sizeof(buf));
3324 } while (ret > 0);
3325 }
3326
checkDataReceived(int udpSocket,int tunFd,sockaddr * dstAddr,int addrLen)3327 void checkDataReceived(int udpSocket, int tunFd, sockaddr* dstAddr, int addrLen) {
3328 char buf[4096] = {};
3329 // Clear tunFd's queue before write something because there might be some
3330 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3331 clearQueue(tunFd);
3332 EXPECT_EQ(4, sendto(udpSocket, "foo", sizeof("foo"), 0, dstAddr, addrLen));
3333 // TODO: extract header and verify data
3334 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3335 }
3336
sendIPv6PacketFromUid(uid_t uid,const in6_addr & dstAddr,Fwmark * fwmark,int tunFd,bool doConnect=true)3337 bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd,
3338 bool doConnect = true) {
3339 ScopedUidChange scopedUidChange(uid);
3340 unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
3341 if (testSocket < 0) return false;
3342
3343 const sockaddr_in6 dst6 = {
3344 .sin6_family = AF_INET6,
3345 .sin6_port = 42,
3346 .sin6_addr = dstAddr,
3347 };
3348 if (doConnect && connect(testSocket, (sockaddr*)&dst6, sizeof(dst6)) == -1) return false;
3349
3350 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3351 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3352
3353 char addr[INET6_ADDRSTRLEN];
3354 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3355 SCOPED_TRACE(StringPrintf("sendIPv6Packet, addr: %s, uid: %u, doConnect: %s", addr, uid,
3356 doConnect ? "true" : "false"));
3357 if (doConnect) {
3358 checkDataReceived(testSocket, tunFd, nullptr, 0);
3359 } else {
3360 checkDataReceived(testSocket, tunFd, (sockaddr*)&dst6, sizeof(dst6));
3361 }
3362 return true;
3363 }
3364
3365 // Send an IPv6 packet from the uid. Expect to fail and get specified errno.
sendIPv6PacketFromUidFail(uid_t uid,const in6_addr & dstAddr,Fwmark * fwmark,bool doConnect,int expectedErr)3366 bool sendIPv6PacketFromUidFail(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, bool doConnect,
3367 int expectedErr) {
3368 ScopedUidChange scopedUidChange(uid);
3369 unique_fd s(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
3370 if (s < 0) return false;
3371
3372 const sockaddr_in6 dst6 = {
3373 .sin6_family = AF_INET6,
3374 .sin6_port = 42,
3375 .sin6_addr = dstAddr,
3376 };
3377 if (doConnect) {
3378 if (connect(s, (sockaddr*)&dst6, sizeof(dst6)) == 0) return false;
3379 if (errno != expectedErr) return false;
3380 }
3381
3382 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3383 EXPECT_NE(-1, getsockopt(s, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3384
3385 char addr[INET6_ADDRSTRLEN];
3386 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3387 SCOPED_TRACE(StringPrintf("sendIPv6PacketFail, addr: %s, uid: %u, doConnect: %s", addr, uid,
3388 doConnect ? "true" : "false"));
3389 if (!doConnect) {
3390 if (sendto(s, "foo", sizeof("foo"), 0, (sockaddr*)&dst6, sizeof(dst6)) == 0) return false;
3391 if (errno != expectedErr) return false;
3392 }
3393 return true;
3394 }
3395
expectVpnFallthroughRuleExists(const std::string & ifName,int vpnNetId)3396 void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3397 std::string vpnFallthroughRule =
3398 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3399 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3400 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3401 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3402 }
3403 }
3404
expectVpnFallthroughWorks(android::net::INetd * netdService,bool bypassable,uid_t uid,const TunInterface & fallthroughNetwork,const TunInterface & vpnNetwork,int vpnNetId=TEST_NETID2,int fallthroughNetId=TEST_NETID1)3405 void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3406 const TunInterface& fallthroughNetwork,
3407 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3408 int fallthroughNetId = TEST_NETID1) {
3409 // Set default network to NETID_UNSET
3410 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3411
3412 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3413 in6_addr insideVpnAddr = {
3414 {// 2001:db8:cafe::1
3415 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3416 // outsideVpnAddr will hit the route in the fallthrough network route table
3417 // because we added default route in createVpnNetworkWithUid
3418 in6_addr outsideVpnAddr = {
3419 {// 2607:f0d0:1002::4
3420 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3421
3422 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3423 int vpnFd = vpnNetwork.getFdForTesting();
3424 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3425 // default network.
3426 Fwmark fwmark;
3427 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3428 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3429
3430 // Set default network
3431 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3432
3433 // Connections go on the default network because UID 0 is not subject to the VPN.
3434 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3435 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3436 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3437 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3438
3439 // Check if fallthrough rule exists
3440 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3441
3442 // Expect fallthrough to default network
3443 // The fwmark differs depending on whether the VPN is bypassable or not.
3444 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3445 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3446
3447 // Expect connect success, packet will be sent to vpnFd.
3448 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3449 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3450
3451 // Explicitly select vpn network
3452 setNetworkForProcess(vpnNetId);
3453
3454 // Expect fallthrough to default network
3455 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3456 // Expect the mark contains all the bit because we've selected network.
3457 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3458
3459 // Expect connect success, packet will be sent to vpnFd.
3460 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3461 // Expect the mark contains all the bit because we've selected network.
3462 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3463
3464 // Explicitly select fallthrough network
3465 setNetworkForProcess(fallthroughNetId);
3466
3467 // The mark is set to fallthrough network because we've selected it.
3468 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3469 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3470
3471 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3472 if (bypassable) {
3473 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3474 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3475 } else {
3476 // If not, no permission to bypass vpn.
3477 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3478 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3479 }
3480 }
3481
3482 } // namespace
3483
TEST_F(NetdBinderTest,SecureVPNFallthrough)3484 TEST_F(NetdBinderTest, SecureVPNFallthrough) {
3485 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3486 // Get current default network NetId
3487 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3488 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3489 }
3490
TEST_F(NetdBinderTest,BypassableVPNFallthrough)3491 TEST_F(NetdBinderTest, BypassableVPNFallthrough) {
3492 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3493 // Get current default network NetId
3494 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3495 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
3496 }
3497
3498 namespace {
3499
createIpv6SocketAndCheckMark(int type,const in6_addr & dstAddr)3500 int32_t createIpv6SocketAndCheckMark(int type, const in6_addr& dstAddr) {
3501 const sockaddr_in6 dst6 = {
3502 .sin6_family = AF_INET6,
3503 .sin6_port = 1234,
3504 .sin6_addr = dstAddr,
3505 };
3506 // create non-blocking socket.
3507 int sockFd = socket(AF_INET6, type | SOCK_NONBLOCK, 0);
3508 EXPECT_NE(-1, sockFd);
3509 EXPECT_EQ((type == SOCK_STREAM) ? -1 : 0, connect(sockFd, (sockaddr*)&dst6, sizeof(dst6)));
3510
3511 // Get socket fwmark.
3512 Fwmark fwmark;
3513 socklen_t fwmarkLen = sizeof(fwmark.intValue);
3514 EXPECT_EQ(0, getsockopt(sockFd, SOL_SOCKET, SO_MARK, &fwmark.intValue, &fwmarkLen));
3515 EXPECT_EQ(0, close(sockFd));
3516 return fwmark.intValue;
3517 }
3518
3519 } // namespace
3520
TEST_F(NetdBinderTest,GetFwmarkForNetwork)3521 TEST_F(NetdBinderTest, GetFwmarkForNetwork) {
3522 // Save current default network.
3523 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3524
3525 // Add test physical network 1 and set as default network.
3526 auto config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
3527 INetd::PERMISSION_NONE, false);
3528 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
3529 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3530 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "2001:db8::/32", "").isOk());
3531 EXPECT_TRUE(mNetd->networkSetDefault(TEST_NETID1).isOk());
3532 // Add test physical network 2
3533 config.netId = TEST_NETID2;
3534 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
3535 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
3536
3537 // Get fwmark for network 1.
3538 MarkMaskParcel maskMarkNet1;
3539 ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID1, &maskMarkNet1).isOk());
3540
3541 uint32_t fwmarkTcp = createIpv6SocketAndCheckMark(SOCK_STREAM, V6_ADDR);
3542 uint32_t fwmarkUdp = createIpv6SocketAndCheckMark(SOCK_DGRAM, V6_ADDR);
3543 EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkTcp & maskMarkNet1.mask));
3544 EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkUdp & maskMarkNet1.mask));
3545
3546 // Get fwmark for network 2.
3547 MarkMaskParcel maskMarkNet2;
3548 ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID2, &maskMarkNet2).isOk());
3549 EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkTcp & maskMarkNet2.mask));
3550 EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkUdp & maskMarkNet2.mask));
3551
3552 // Remove test physical network.
3553 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
3554 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
3555 }
3556
3557 namespace {
3558
makeTetherOffloadRule(int inputInterfaceIndex,int outputInterfaceIndex,const std::vector<uint8_t> & destination,int prefixLength,const std::vector<uint8_t> & srcL2Address,const std::vector<uint8_t> & dstL2Address,int pmtu)3559 TetherOffloadRuleParcel makeTetherOffloadRule(int inputInterfaceIndex, int outputInterfaceIndex,
3560 const std::vector<uint8_t>& destination,
3561 int prefixLength,
3562 const std::vector<uint8_t>& srcL2Address,
3563 const std::vector<uint8_t>& dstL2Address, int pmtu) {
3564 android::net::TetherOffloadRuleParcel parcel;
3565 parcel.inputInterfaceIndex = inputInterfaceIndex;
3566 parcel.outputInterfaceIndex = outputInterfaceIndex;
3567 parcel.destination = destination;
3568 parcel.prefixLength = prefixLength;
3569 parcel.srcL2Address = srcL2Address;
3570 parcel.dstL2Address = dstL2Address;
3571 parcel.pmtu = pmtu;
3572 return parcel;
3573 }
3574
3575 } // namespace
3576
3577 // TODO: probably remove the test because TetherOffload* binder calls are deprecated.
TEST_F(NetdBinderTest,DISABLED_TetherOffloadRule)3578 TEST_F(NetdBinderTest, DISABLED_TetherOffloadRule) {
3579 // TODO: Perhaps verify invalid interface index once the netd handle the error in methods.
3580 constexpr uint32_t kIfaceInt = 101;
3581 constexpr uint32_t kIfaceExt = 102;
3582 constexpr uint32_t kIfaceNonExistent = 103;
3583
3584 const std::vector<uint8_t> kAddr6 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0x00, 0x00,
3585 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88};
3586 const std::vector<uint8_t> kSrcMac = {0x00, 0x00, 0x00, 0x00, 0x00, 0x0a};
3587 const std::vector<uint8_t> kDstMac = {0x00, 0x00, 0x00, 0x00, 0x00, 0x0b};
3588
3589 const std::vector<uint8_t> kInvalidAddr4 = {0xac, 0x0a, 0x0d, 0xb8}; // should be IPv6 address
3590 const std::vector<uint8_t> kInvalidMac = {0xde, 0xad, 0xbe, 0xef}; // should be 6-byte length
3591
3592 // Invalid IP address, add rule
3593 TetherOffloadRuleParcel rule = makeTetherOffloadRule(
3594 kIfaceExt, kIfaceInt, kInvalidAddr4 /*bad*/, 128, kSrcMac, kDstMac, 1500);
3595 auto status = mNetd->tetherOffloadRuleAdd(rule);
3596 EXPECT_FALSE(status.isOk());
3597 EXPECT_EQ(EAFNOSUPPORT, status.serviceSpecificErrorCode());
3598
3599 // Invalid source L2 address, add rule
3600 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kInvalidMac /*bad*/, kDstMac,
3601 1500);
3602 status = mNetd->tetherOffloadRuleAdd(rule);
3603 EXPECT_FALSE(status.isOk());
3604 EXPECT_EQ(ENXIO, status.serviceSpecificErrorCode());
3605
3606 // Invalid destination L2 address, add rule
3607 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kSrcMac, kInvalidMac /*bad*/,
3608 1500);
3609 status = mNetd->tetherOffloadRuleAdd(rule);
3610 EXPECT_FALSE(status.isOk());
3611 EXPECT_EQ(ENXIO, status.serviceSpecificErrorCode());
3612
3613 // Invalid IP address, remove rule
3614 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kInvalidAddr4 /*bad*/, 128, kSrcMac, kDstMac,
3615 1500);
3616 status = mNetd->tetherOffloadRuleRemove(rule);
3617 EXPECT_FALSE(status.isOk());
3618 EXPECT_EQ(EAFNOSUPPORT, status.serviceSpecificErrorCode());
3619
3620 // Invalid prefix length
3621 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 64 /*bad*/, kSrcMac, kDstMac, 1500);
3622 status = mNetd->tetherOffloadRuleAdd(rule);
3623 EXPECT_FALSE(status.isOk());
3624 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
3625 status = mNetd->tetherOffloadRuleRemove(rule);
3626 EXPECT_FALSE(status.isOk());
3627 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
3628
3629 // Invalid interface index
3630 rule = makeTetherOffloadRule(kIfaceExt, 0, kAddr6, 128, kSrcMac, kDstMac, 1500);
3631 status = mNetd->tetherOffloadRuleAdd(rule);
3632 EXPECT_FALSE(status.isOk());
3633 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
3634 rule = makeTetherOffloadRule(0, kIfaceInt, kAddr6, 64, kSrcMac, kDstMac, 1500);
3635 status = mNetd->tetherOffloadRuleRemove(rule);
3636 EXPECT_FALSE(status.isOk());
3637 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
3638
3639 // Invalid pmtu (too low)
3640 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kSrcMac, kDstMac, 1279);
3641 status = mNetd->tetherOffloadRuleAdd(rule);
3642 EXPECT_FALSE(status.isOk());
3643 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
3644
3645 // Invalid pmtu (too high)
3646 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kSrcMac, kDstMac, 65536);
3647 status = mNetd->tetherOffloadRuleAdd(rule);
3648 EXPECT_FALSE(status.isOk());
3649 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
3650
3651 // Remove non existent rule. Expect that silently return success if the rule did not exist.
3652 rule = makeTetherOffloadRule(kIfaceNonExistent, kIfaceInt, kAddr6, 128, kSrcMac, kDstMac, 1500);
3653 EXPECT_TRUE(mNetd->tetherOffloadRuleRemove(rule).isOk());
3654
3655 // Add and remove rule normally.
3656 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kSrcMac, kDstMac, 1500);
3657 EXPECT_TRUE(mNetd->tetherOffloadRuleAdd(rule).isOk());
3658 EXPECT_TRUE(mNetd->tetherOffloadRuleRemove(rule).isOk());
3659 }
3660
expectPacket(int fd,uint8_t * ipPacket,ssize_t ipLen)3661 static bool expectPacket(int fd, uint8_t* ipPacket, ssize_t ipLen) {
3662 constexpr bool kDebug = false;
3663
3664 uint8_t buf[ETHER_HDR_LEN + 1500];
3665
3666 // Wait a bit to ensure that the packet we're interested in has arrived.
3667 // TODO: speed this up.
3668 usleep(100 * 1000);
3669
3670 ssize_t bytesRead;
3671 ssize_t expectedLen = ipLen + ETHER_HDR_LEN;
3672 while ((bytesRead = read(fd, buf, sizeof(buf))) >= 0) {
3673 if (kDebug) {
3674 std::cerr << fmt::format(
3675 "Expected: {:02x}\n Actual: {:02x}\n",
3676 fmt::join(ipPacket, ipPacket + ipLen, " "),
3677 fmt::join(buf + ETHER_HDR_LEN, buf + ETHER_HDR_LEN + ipLen, " "));
3678 }
3679
3680 if (bytesRead != expectedLen) {
3681 continue;
3682 }
3683
3684 if (!memcmp(ipPacket, buf + ETHER_HDR_LEN, ipLen)) {
3685 return true;
3686 }
3687 }
3688
3689 return false;
3690 }
3691
tcQdiscExists(const std::string & interface)3692 static bool tcQdiscExists(const std::string& interface) {
3693 std::string command = StringPrintf("tc qdisc show dev %s", interface.c_str());
3694 std::vector<std::string> lines = runCommand(command);
3695 for (const auto& line : lines) {
3696 if (StartsWith(line, "qdisc clsact ffff:")) return true;
3697 }
3698 return false;
3699 }
3700
tcFilterExists(const std::string & interface)3701 static bool tcFilterExists(const std::string& interface) {
3702 std::string command = StringPrintf("tc filter show dev %s ingress", interface.c_str());
3703 std::vector<std::string> lines = runCommand(command);
3704 const std::basic_regex regex("^filter .* bpf .* prog_offload_schedcls_tether_.*$");
3705 for (const auto& line : lines) {
3706 if (std::regex_match(Trim(line), regex)) return true;
3707 }
3708 return false;
3709 }
3710
3711 // TODO: probably remove the test because TetherOffload* binder calls are deprecated.
TEST_F(NetdBinderTest,DISABLED_TetherOffloadForwarding)3712 TEST_F(NetdBinderTest, DISABLED_TetherOffloadForwarding) {
3713 SKIP_IF_EXTENDED_BPF_NOT_SUPPORTED;
3714
3715 constexpr const char* kDownstreamPrefix = "2001:db8:2::/64";
3716
3717 // 1500-byte packet.
3718 constexpr unsigned short kPayloadLen = 1500 - sizeof(ipv6hdr);
3719 struct packet {
3720 ipv6hdr hdr;
3721 char data[kPayloadLen];
3722 } __attribute__((packed)) pkt = {
3723 .hdr =
3724 {
3725 .version = 6,
3726 .payload_len = htons(kPayloadLen),
3727 .nexthdr = 59, // No next header.
3728 .hop_limit = 64,
3729 .saddr = {{{0x20, 0x01, 0x0d, 0xb8, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
3730 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}},
3731 .daddr = {{{0x20, 0x01, 0x0d, 0xb8, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
3732 0x00, 0x00, 0x0f, 0x00, 0xca, 0xfe}}},
3733 },
3734 };
3735 ASSERT_EQ(1500U, sizeof(pkt));
3736
3737 // Use one of the test's tun interfaces as upstream.
3738 // It must be part of a network or it will not have the clsact attached.
3739 const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
3740 INetd::PERMISSION_NONE, false);
3741 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
3742 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3743 int fd1 = sTun.getFdForTesting();
3744 EXPECT_TRUE(tcQdiscExists(sTun.name()));
3745
3746 // Create our own tap as a downstream.
3747 TunInterface tap;
3748 ASSERT_EQ(0, tap.init(true /* isTap */));
3749 ASSERT_LE(tap.name().size(), static_cast<size_t>(IFNAMSIZ));
3750 int fd2 = tap.getFdForTesting();
3751
3752 // Set it to nonblocking so that expectPacket can work.
3753 int flags = fcntl(fd2, F_GETFL, 0);
3754 fcntl(fd2, F_SETFL, flags | O_NONBLOCK);
3755
3756 // Downstream interface setup. Add to local network, add directly-connected route, etc.
3757 binder::Status status = mNetd->networkAddInterface(INetd::LOCAL_NET_ID, tap.name());
3758 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3759 status = mNetd->tetherInterfaceAdd(tap.name());
3760 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3761 expectTetherInterfaceConfigureForIPv6Router(tap.name());
3762 EXPECT_TRUE(tcQdiscExists(tap.name()));
3763
3764 // Can't easily use INetd::NEXTHOP_NONE because it is a String16 constant. Use "" instead.
3765 status = mNetd->networkAddRoute(INetd::LOCAL_NET_ID, tap.name(), kDownstreamPrefix, "");
3766 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3767
3768 // Set up forwarding. All methods take intIface first and extIface second.
3769 status = mNetd->tetherAddForward(tap.name(), sTun.name());
3770 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3771 status = mNetd->ipfwdAddInterfaceForward(tap.name(), sTun.name());
3772 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3773 EXPECT_TRUE(tcFilterExists(sTun.name()));
3774
3775 std::vector<uint8_t> kDummyMac = {02, 00, 00, 00, 00, 00};
3776 uint8_t* daddr = reinterpret_cast<uint8_t*>(&pkt.hdr.daddr);
3777 std::vector<uint8_t> dstAddr(daddr, daddr + sizeof(pkt.hdr.daddr));
3778
3779 TetherOffloadRuleParcel rule = makeTetherOffloadRule(sTun.ifindex(), tap.ifindex(), dstAddr,
3780 128, kDummyMac, kDummyMac, sizeof(pkt));
3781 status = mNetd->tetherOffloadRuleAdd(rule);
3782 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3783
3784 // Set data limit to one byte less than two packets.
3785 // If you get rid of the '- 1' then the second packet will get forwarded
3786 // and the EXPECT_FALSE(expectPacket(...)) a dozen lines down will fail.
3787 status = mNetd->tetherOffloadSetInterfaceQuota(sTun.ifindex(), sizeof(pkt) * 2 - 1);
3788 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3789
3790 // Receive a packet on sTun.
3791 EXPECT_EQ((ssize_t)sizeof(pkt), write(fd1, &pkt, sizeof(pkt)));
3792
3793 // Expect a packet identical to pkt, except with a TTL of 63.
3794 struct packet pkt2 = pkt;
3795 ASSERT_EQ(1500U, sizeof(pkt2));
3796 pkt2.hdr.hop_limit = pkt.hdr.hop_limit - 1;
3797 EXPECT_TRUE(expectPacket(fd2, (uint8_t*)&pkt2, sizeof(pkt2)));
3798
3799 // Receive a second packet on sTun.
3800 EXPECT_EQ((ssize_t)sizeof(pkt), write(fd1, &pkt, sizeof(pkt)));
3801
3802 // Should fail to forward due to quota limit.
3803 EXPECT_FALSE(expectPacket(fd2, (uint8_t*)&pkt2, sizeof(pkt2)));
3804
3805 // Clean up.
3806 EXPECT_TRUE(mNetd->tetherOffloadRuleRemove(rule).isOk());
3807
3808 TetherStatsParcel tetherStats;
3809 EXPECT_TRUE(mNetd->tetherOffloadGetAndClearStats(sTun.ifindex(), &tetherStats).isOk());
3810 EXPECT_EQ("", tetherStats.iface);
3811 EXPECT_EQ(static_cast<int64_t>(sizeof(pkt)), tetherStats.rxBytes);
3812 EXPECT_EQ(1, tetherStats.rxPackets);
3813 EXPECT_EQ(0, tetherStats.txBytes);
3814 EXPECT_EQ(0, tetherStats.txPackets);
3815 EXPECT_EQ(sTun.ifindex(), tetherStats.ifIndex);
3816
3817 EXPECT_TRUE(mNetd->ipfwdRemoveInterfaceForward(tap.name(), sTun.name()).isOk());
3818 EXPECT_TRUE(mNetd->tetherRemoveForward(tap.name(), sTun.name()).isOk());
3819 EXPECT_TRUE(mNetd->networkRemoveRoute(INetd::LOCAL_NET_ID, tap.name(), kDownstreamPrefix, "")
3820 .isOk());
3821 EXPECT_TRUE(mNetd->tetherInterfaceRemove(tap.name()).isOk());
3822 EXPECT_TRUE(mNetd->networkRemoveInterface(INetd::LOCAL_NET_ID, tap.name()).isOk());
3823 EXPECT_TRUE(mNetd->networkRemoveInterface(TEST_NETID1, sTun.name()).isOk());
3824 }
3825
3826 namespace {
3827
dumpService(const sp<IBinder> & binder)3828 std::vector<std::string> dumpService(const sp<IBinder>& binder) {
3829 unique_fd localFd, remoteFd;
3830 bool success = Pipe(&localFd, &remoteFd);
3831 EXPECT_TRUE(success) << "Failed to open pipe for dumping: " << strerror(errno);
3832 if (!success) return {};
3833
3834 // dump() blocks until another thread has consumed all its output.
3835 std::thread dumpThread = std::thread([binder, remoteFd{std::move(remoteFd)}]() {
3836 android::status_t ret = binder->dump(remoteFd, {});
3837 EXPECT_EQ(android::OK, ret) << "Error dumping service: " << android::statusToString(ret);
3838 });
3839
3840 std::string dumpContent;
3841
3842 EXPECT_TRUE(ReadFdToString(localFd.get(), &dumpContent))
3843 << "Error during dump: " << strerror(errno);
3844 dumpThread.join();
3845
3846 std::stringstream dumpStream(std::move(dumpContent));
3847 std::vector<std::string> lines;
3848 std::string line;
3849 while (std::getline(dumpStream, line)) {
3850 lines.push_back(line);
3851 }
3852
3853 return lines;
3854 }
3855
3856 } // namespace
3857
TEST_F(NetdBinderTest,TestServiceDump)3858 TEST_F(NetdBinderTest, TestServiceDump) {
3859 sp<IBinder> binder = INetd::asBinder(mNetd);
3860 ASSERT_NE(nullptr, binder);
3861
3862 struct TestData {
3863 // Expected contents of the dump command.
3864 const std::string output;
3865 // A regex that might be helpful in matching relevant lines in the output.
3866 // Used to make it easier to add test cases for this code.
3867 const std::string hintRegex;
3868 };
3869 std::vector<TestData> testData;
3870
3871 // Send some IPCs and for each one add an element to testData telling us what to expect.
3872 const auto& config = makeNativeNetworkConfig(TEST_DUMP_NETID, NativeNetworkType::PHYSICAL,
3873 INetd::PERMISSION_NONE, false);
3874 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
3875 testData.push_back(
3876 {"networkCreate(NativeNetworkConfig{netId: 65123, networkType: PHYSICAL, "
3877 "permission: 0, secure: false, vpnType: PLATFORM})",
3878 "networkCreate.*65123"});
3879
3880 EXPECT_EQ(EEXIST, mNetd->networkCreate(config).serviceSpecificErrorCode());
3881 testData.push_back(
3882 {"networkCreate(NativeNetworkConfig{netId: 65123, networkType: PHYSICAL, "
3883 "permission: 0, secure: false, vpnType: PLATFORM}) "
3884 "-> ServiceSpecificException(17, \"File exists\")",
3885 "networkCreate.*65123.*17"});
3886
3887 EXPECT_TRUE(mNetd->networkAddInterface(TEST_DUMP_NETID, sTun.name()).isOk());
3888 testData.push_back({StringPrintf("networkAddInterface(65123, %s)", sTun.name().c_str()),
3889 StringPrintf("networkAddInterface.*65123.*%s", sTun.name().c_str())});
3890
3891 android::net::RouteInfoParcel parcel;
3892 parcel.ifName = sTun.name();
3893 parcel.destination = "2001:db8:dead:beef::/64";
3894 parcel.nextHop = "fe80::dead:beef";
3895 parcel.mtu = 1234;
3896 EXPECT_TRUE(mNetd->networkAddRouteParcel(TEST_DUMP_NETID, parcel).isOk());
3897 testData.push_back(
3898 {StringPrintf("networkAddRouteParcel(65123, RouteInfoParcel{destination:"
3899 " 2001:db8:dead:beef::/64, ifName: %s, nextHop: fe80::dead:beef,"
3900 " mtu: 1234})",
3901 sTun.name().c_str()),
3902 "networkAddRouteParcel.*65123.*dead:beef"});
3903
3904 EXPECT_TRUE(mNetd->networkDestroy(TEST_DUMP_NETID).isOk());
3905 testData.push_back({"networkDestroy(65123)", "networkDestroy.*65123"});
3906
3907 // Send the service dump request to netd.
3908 std::vector<std::string> lines = dumpService(binder);
3909
3910 // Basic regexp to match dump output lines. Matches the beginning and end of the line, and
3911 // puts the output of the command itself into the first match group.
3912 // Example: " 11-05 00:23:39.481 myCommand(args) <2.02ms>".
3913 const std::basic_regex lineRegex(
3914 "^ [0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}[.][0-9]{3} "
3915 "(.*)"
3916 " <[0-9]+[.][0-9]{2}ms>$");
3917
3918 // For each element of testdata, check that the expected output appears in the dump output.
3919 // If not, fail the test and use hintRegex to print similar lines to assist in debugging.
3920 for (const TestData& td : testData) {
3921 const bool found = std::any_of(lines.begin(), lines.end(), [&](const std::string& line) {
3922 std::smatch match;
3923 if (!std::regex_match(line, match, lineRegex)) return false;
3924 return (match.size() == 2) && (match[1].str() == td.output);
3925 });
3926 EXPECT_TRUE(found) << "Didn't find line '" << td.output << "' in dumpsys output.";
3927 if (found) continue;
3928 std::cerr << "Similar lines" << std::endl;
3929 for (const auto& line : lines) {
3930 if (std::regex_search(line, std::basic_regex(td.hintRegex))) {
3931 std::cerr << line << std::endl;
3932 }
3933 }
3934 }
3935 }
3936
TEST_F(NetdBinderTest,DeprecatedTetherOffloadRuleAdd)3937 TEST_F(NetdBinderTest, DeprecatedTetherOffloadRuleAdd) {
3938 TetherOffloadRuleParcel emptyRule;
3939 auto status = mNetd->tetherOffloadRuleAdd(emptyRule);
3940 ASSERT_FALSE(status.isOk());
3941 ASSERT_EQ(status.exceptionCode(), binder::Status::EX_UNSUPPORTED_OPERATION);
3942 }
3943
TEST_F(NetdBinderTest,DeprecatedTetherOffloadRuleRemove)3944 TEST_F(NetdBinderTest, DeprecatedTetherOffloadRuleRemove) {
3945 TetherOffloadRuleParcel emptyRule;
3946 auto status = mNetd->tetherOffloadRuleRemove(emptyRule);
3947 ASSERT_FALSE(status.isOk());
3948 ASSERT_EQ(status.exceptionCode(), binder::Status::EX_UNSUPPORTED_OPERATION);
3949 }
3950
TEST_F(NetdBinderTest,DeprecatedTetherOffloadGetStats)3951 TEST_F(NetdBinderTest, DeprecatedTetherOffloadGetStats) {
3952 std::vector<TetherStatsParcel> tetherStatsList;
3953 auto status = mNetd->tetherOffloadGetStats(&tetherStatsList);
3954 ASSERT_FALSE(status.isOk());
3955 ASSERT_EQ(status.exceptionCode(), binder::Status::EX_UNSUPPORTED_OPERATION);
3956 }
3957
TEST_F(NetdBinderTest,DeprecatedTetherOffloadSetInterfaceQuota)3958 TEST_F(NetdBinderTest, DeprecatedTetherOffloadSetInterfaceQuota) {
3959 auto status = mNetd->tetherOffloadSetInterfaceQuota(0 /* ifIndex */, 0 /* quotaBytes */);
3960 ASSERT_FALSE(status.isOk());
3961 ASSERT_EQ(status.exceptionCode(), binder::Status::EX_UNSUPPORTED_OPERATION);
3962 }
3963
TEST_F(NetdBinderTest,DeprecatedTetherOffloadGetAndClearStats)3964 TEST_F(NetdBinderTest, DeprecatedTetherOffloadGetAndClearStats) {
3965 TetherStatsParcel tetherStats;
3966 auto status = mNetd->tetherOffloadGetAndClearStats(0 /* ifIndex */, &tetherStats);
3967 ASSERT_FALSE(status.isOk());
3968 ASSERT_EQ(status.exceptionCode(), binder::Status::EX_UNSUPPORTED_OPERATION);
3969 }
3970
3971 namespace {
3972
3973 // aliases for better reading
3974 #define SYSTEM_DEFAULT_NETID TEST_NETID1
3975 #define APP_DEFAULT_NETID TEST_NETID2
3976 #define VPN_NETID TEST_NETID3
3977
verifyAppUidRules(std::vector<bool> && expectedResults,std::vector<UidRangeParcel> & uidRanges,const std::string & iface,uint32_t subPriority)3978 void verifyAppUidRules(std::vector<bool>&& expectedResults, std::vector<UidRangeParcel>& uidRanges,
3979 const std::string& iface, uint32_t subPriority) {
3980 ASSERT_EQ(expectedResults.size(), uidRanges.size());
3981 if (iface.size()) {
3982 std::string action = StringPrintf("lookup %s ", iface.c_str());
3983 for (unsigned long i = 0; i < uidRanges.size(); i++) {
3984 EXPECT_EQ(expectedResults[i],
3985 ipRuleExistsForRange(RULE_PRIORITY_UID_EXPLICIT_NETWORK + subPriority,
3986 uidRanges[i], action));
3987 EXPECT_EQ(expectedResults[i],
3988 ipRuleExistsForRange(RULE_PRIORITY_UID_IMPLICIT_NETWORK + subPriority,
3989 uidRanges[i], action));
3990 EXPECT_EQ(expectedResults[i],
3991 ipRuleExistsForRange(RULE_PRIORITY_UID_DEFAULT_NETWORK + subPriority,
3992 uidRanges[i], action));
3993 }
3994 } else {
3995 std::string action = "unreachable";
3996 for (unsigned long i = 0; i < uidRanges.size(); i++) {
3997 EXPECT_EQ(expectedResults[i],
3998 ipRuleExistsForRange(RULE_PRIORITY_UID_EXPLICIT_NETWORK + subPriority,
3999 uidRanges[i], action));
4000 EXPECT_EQ(expectedResults[i],
4001 ipRuleExistsForRange(RULE_PRIORITY_UID_IMPLICIT_NETWORK + subPriority,
4002 uidRanges[i], action));
4003 EXPECT_EQ(expectedResults[i],
4004 ipRuleExistsForRange(RULE_PRIORITY_UID_DEFAULT_UNREACHABLE + subPriority,
4005 uidRanges[i], action));
4006 }
4007 }
4008 }
4009
verifyAppUidRules(std::vector<bool> && expectedResults,NativeUidRangeConfig & uidRangeConfig,const std::string & iface)4010 void verifyAppUidRules(std::vector<bool>&& expectedResults, NativeUidRangeConfig& uidRangeConfig,
4011 const std::string& iface) {
4012 verifyAppUidRules(move(expectedResults), uidRangeConfig.uidRanges, iface,
4013 uidRangeConfig.subPriority);
4014 }
4015
verifyVpnUidRules(std::vector<bool> && expectedResults,NativeUidRangeConfig & uidRangeConfig,const std::string & iface,bool secure)4016 void verifyVpnUidRules(std::vector<bool>&& expectedResults, NativeUidRangeConfig& uidRangeConfig,
4017 const std::string& iface, bool secure) {
4018 ASSERT_EQ(expectedResults.size(), uidRangeConfig.uidRanges.size());
4019 std::string action = StringPrintf("lookup %s ", iface.c_str());
4020
4021 uint32_t priority;
4022 if (secure) {
4023 priority = RULE_PRIORITY_SECURE_VPN;
4024 } else {
4025 priority = RULE_PRIORITY_BYPASSABLE_VPN;
4026 }
4027 for (unsigned long i = 0; i < uidRangeConfig.uidRanges.size(); i++) {
4028 EXPECT_EQ(expectedResults[i], ipRuleExistsForRange(priority + uidRangeConfig.subPriority,
4029 uidRangeConfig.uidRanges[i], action));
4030 EXPECT_EQ(expectedResults[i],
4031 ipRuleExistsForRange(RULE_PRIORITY_EXPLICIT_NETWORK + uidRangeConfig.subPriority,
4032 uidRangeConfig.uidRanges[i], action));
4033 EXPECT_EQ(expectedResults[i],
4034 ipRuleExistsForRange(RULE_PRIORITY_OUTPUT_INTERFACE + uidRangeConfig.subPriority,
4035 uidRangeConfig.uidRanges[i], action, iface.c_str()));
4036 }
4037 }
4038
4039 constexpr int SUB_PRIORITY_1 = UidRanges::DEFAULT_SUB_PRIORITY + 1;
4040 constexpr int SUB_PRIORITY_2 = UidRanges::DEFAULT_SUB_PRIORITY + 2;
4041
4042 constexpr int IMPLICITLY_SELECT = 0;
4043 constexpr int EXPLICITLY_SELECT = 1;
4044 constexpr int UNCONNECTED_SOCKET = 2;
4045
4046 // 1. Send data with the specified UID, on a connected or unconnected socket.
4047 // 2. Verify if data is received from the specified fd. The fd should belong to a TUN, which has
4048 // been assigned to the test network.
4049 // 3. Verify if fwmark of data is correct.
4050 // Note: This is a helper function used by per-app default network tests. It does not implement full
4051 // fwmark logic in netd, and it's currently sufficient. Extension may be required for more
4052 // complicated tests.
expectPacketSentOnNetId(uid_t uid,unsigned netId,int fd,int selectionMode)4053 void expectPacketSentOnNetId(uid_t uid, unsigned netId, int fd, int selectionMode) {
4054 Fwmark fwmark;
4055 const bool doConnect = (selectionMode != UNCONNECTED_SOCKET);
4056 EXPECT_TRUE(sendIPv6PacketFromUid(uid, V6_ADDR, &fwmark, fd, doConnect));
4057
4058 Fwmark expected;
4059 expected.netId = netId;
4060 expected.explicitlySelected = (selectionMode == EXPLICITLY_SELECT);
4061 if (uid == AID_ROOT && selectionMode == EXPLICITLY_SELECT) {
4062 expected.protectedFromVpn = true;
4063 } else {
4064 expected.protectedFromVpn = false;
4065 }
4066 if (selectionMode == UNCONNECTED_SOCKET) {
4067 expected.permission = PERMISSION_NONE;
4068 } else {
4069 expected.permission = (uid == AID_ROOT) ? PERMISSION_SYSTEM : PERMISSION_NONE;
4070 }
4071
4072 EXPECT_EQ(expected.intValue, fwmark.intValue);
4073 }
4074
expectUnreachableError(uid_t uid,unsigned netId,int selectionMode)4075 void expectUnreachableError(uid_t uid, unsigned netId, int selectionMode) {
4076 Fwmark fwmark;
4077 const bool doConnect = (selectionMode != UNCONNECTED_SOCKET);
4078 EXPECT_TRUE(sendIPv6PacketFromUidFail(uid, V6_ADDR, &fwmark, doConnect, ENETUNREACH));
4079
4080 Fwmark expected;
4081 expected.netId = netId;
4082 expected.explicitlySelected = (selectionMode == EXPLICITLY_SELECT);
4083 if (uid == AID_ROOT && selectionMode == EXPLICITLY_SELECT) {
4084 expected.protectedFromVpn = true;
4085 } else {
4086 expected.protectedFromVpn = false;
4087 }
4088 if (selectionMode == UNCONNECTED_SOCKET) {
4089 expected.permission = PERMISSION_NONE;
4090 } else {
4091 expected.permission = (uid == AID_ROOT) ? PERMISSION_SYSTEM : PERMISSION_NONE;
4092 }
4093
4094 EXPECT_EQ(expected.intValue, fwmark.intValue);
4095 }
4096
4097 } // namespace
4098
4099 // Verify whether API reject overlapped UID ranges
TEST_F(NetdBinderTest,PerAppDefaultNetwork_OverlappedUidRanges)4100 TEST_F(NetdBinderTest, PerAppDefaultNetwork_OverlappedUidRanges) {
4101 const auto& config = makeNativeNetworkConfig(APP_DEFAULT_NETID, NativeNetworkType::PHYSICAL,
4102 INetd::PERMISSION_NONE, false);
4103 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
4104 EXPECT_TRUE(mNetd->networkAddInterface(APP_DEFAULT_NETID, sTun.name()).isOk());
4105
4106 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 1, BASE_UID + 1),
4107 makeUidRangeParcel(BASE_UID + 10, BASE_UID + 12)};
4108 EXPECT_TRUE(mNetd->networkAddUidRanges(APP_DEFAULT_NETID, uidRanges).isOk());
4109
4110 binder::Status status;
4111 status = mNetd->networkAddUidRanges(APP_DEFAULT_NETID,
4112 {makeUidRangeParcel(BASE_UID + 1, BASE_UID + 1)});
4113 EXPECT_FALSE(status.isOk());
4114 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
4115
4116 status = mNetd->networkAddUidRanges(APP_DEFAULT_NETID,
4117 {makeUidRangeParcel(BASE_UID + 9, BASE_UID + 10)});
4118 EXPECT_FALSE(status.isOk());
4119 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
4120
4121 status = mNetd->networkAddUidRanges(APP_DEFAULT_NETID,
4122 {makeUidRangeParcel(BASE_UID + 11, BASE_UID + 11)});
4123 EXPECT_FALSE(status.isOk());
4124 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
4125
4126 status = mNetd->networkAddUidRanges(APP_DEFAULT_NETID,
4127 {makeUidRangeParcel(BASE_UID + 12, BASE_UID + 13)});
4128 EXPECT_FALSE(status.isOk());
4129 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
4130
4131 status = mNetd->networkAddUidRanges(APP_DEFAULT_NETID,
4132 {makeUidRangeParcel(BASE_UID + 9, BASE_UID + 13)});
4133 EXPECT_FALSE(status.isOk());
4134 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
4135
4136 std::vector<UidRangeParcel> selfOverlappedUidRanges = {
4137 makeUidRangeParcel(BASE_UID + 20, BASE_UID + 20),
4138 makeUidRangeParcel(BASE_UID + 20, BASE_UID + 21)};
4139 status = mNetd->networkAddUidRanges(APP_DEFAULT_NETID, selfOverlappedUidRanges);
4140 EXPECT_FALSE(status.isOk());
4141 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
4142 }
4143
4144 // Verify whether IP rules for app default network are correctly configured.
TEST_F(NetdBinderTest,PerAppDefaultNetwork_VerifyIpRules)4145 TEST_F(NetdBinderTest, PerAppDefaultNetwork_VerifyIpRules) {
4146 const auto& config = makeNativeNetworkConfig(APP_DEFAULT_NETID, NativeNetworkType::PHYSICAL,
4147 INetd::PERMISSION_NONE, false);
4148 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
4149 EXPECT_TRUE(mNetd->networkAddInterface(APP_DEFAULT_NETID, sTun.name()).isOk());
4150
4151 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
4152 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
4153
4154 EXPECT_TRUE(mNetd->networkAddUidRanges(APP_DEFAULT_NETID, uidRanges).isOk());
4155 verifyAppUidRules({true, true} /*expectedResults*/, uidRanges, sTun.name(),
4156 UidRanges::DEFAULT_SUB_PRIORITY);
4157 EXPECT_TRUE(mNetd->networkRemoveUidRanges(APP_DEFAULT_NETID, {uidRanges.at(0)}).isOk());
4158 verifyAppUidRules({false, true} /*expectedResults*/, uidRanges, sTun.name(),
4159 UidRanges::DEFAULT_SUB_PRIORITY);
4160 EXPECT_TRUE(mNetd->networkRemoveUidRanges(APP_DEFAULT_NETID, {uidRanges.at(1)}).isOk());
4161 verifyAppUidRules({false, false} /*expectedResults*/, uidRanges, sTun.name(),
4162 UidRanges::DEFAULT_SUB_PRIORITY);
4163
4164 EXPECT_TRUE(mNetd->networkAddUidRanges(INetd::UNREACHABLE_NET_ID, uidRanges).isOk());
4165 verifyAppUidRules({true, true} /*expectedResults*/, uidRanges, "",
4166 UidRanges::DEFAULT_SUB_PRIORITY);
4167 EXPECT_TRUE(mNetd->networkRemoveUidRanges(INetd::UNREACHABLE_NET_ID, {uidRanges.at(0)}).isOk());
4168 verifyAppUidRules({false, true} /*expectedResults*/, uidRanges, "",
4169 UidRanges::DEFAULT_SUB_PRIORITY);
4170 EXPECT_TRUE(mNetd->networkRemoveUidRanges(INetd::UNREACHABLE_NET_ID, {uidRanges.at(1)}).isOk());
4171 verifyAppUidRules({false, false} /*expectedResults*/, uidRanges, "",
4172 UidRanges::DEFAULT_SUB_PRIORITY);
4173 }
4174
4175 // Verify whether packets go through the right network with and without per-app default network.
4176 // Meaning of Fwmark bits (from Fwmark.h):
4177 // 0x0000ffff - Network ID
4178 // 0x00010000 - Explicit mark bit
4179 // 0x00020000 - VPN protect bit
4180 // 0x000c0000 - Permission bits
TEST_F(NetdBinderTest,PerAppDefaultNetwork_ImplicitlySelectNetwork)4181 TEST_F(NetdBinderTest, PerAppDefaultNetwork_ImplicitlySelectNetwork) {
4182 createDefaultAndOtherPhysicalNetwork(SYSTEM_DEFAULT_NETID, APP_DEFAULT_NETID);
4183
4184 int systemDefaultFd = sTun.getFdForTesting();
4185 int appDefaultFd = sTun2.getFdForTesting();
4186
4187 // Connections go through the system default network.
4188 expectPacketSentOnNetId(AID_ROOT, SYSTEM_DEFAULT_NETID, systemDefaultFd, IMPLICITLY_SELECT);
4189 expectPacketSentOnNetId(TEST_UID1, SYSTEM_DEFAULT_NETID, systemDefaultFd, IMPLICITLY_SELECT);
4190
4191 // Add TEST_UID1 to per-app default network.
4192 EXPECT_TRUE(mNetd->networkAddUidRanges(APP_DEFAULT_NETID,
4193 {makeUidRangeParcel(TEST_UID1, TEST_UID1)})
4194 .isOk());
4195 expectPacketSentOnNetId(AID_ROOT, SYSTEM_DEFAULT_NETID, systemDefaultFd, IMPLICITLY_SELECT);
4196 expectPacketSentOnNetId(TEST_UID1, APP_DEFAULT_NETID, appDefaultFd, IMPLICITLY_SELECT);
4197
4198 // Remove TEST_UID1 from per-app default network.
4199 EXPECT_TRUE(mNetd->networkRemoveUidRanges(APP_DEFAULT_NETID,
4200 {makeUidRangeParcel(TEST_UID1, TEST_UID1)})
4201 .isOk());
4202 expectPacketSentOnNetId(AID_ROOT, SYSTEM_DEFAULT_NETID, systemDefaultFd, IMPLICITLY_SELECT);
4203 expectPacketSentOnNetId(TEST_UID1, SYSTEM_DEFAULT_NETID, systemDefaultFd, IMPLICITLY_SELECT);
4204
4205 // Prohibit TEST_UID1 from using the default network.
4206 EXPECT_TRUE(mNetd->networkAddUidRanges(INetd::UNREACHABLE_NET_ID,
4207 {makeUidRangeParcel(TEST_UID1, TEST_UID1)})
4208 .isOk());
4209 expectPacketSentOnNetId(AID_ROOT, SYSTEM_DEFAULT_NETID, systemDefaultFd, IMPLICITLY_SELECT);
4210 expectUnreachableError(TEST_UID1, INetd::UNREACHABLE_NET_ID, IMPLICITLY_SELECT);
4211
4212 // restore IP rules
4213 EXPECT_TRUE(mNetd->networkRemoveUidRanges(INetd::UNREACHABLE_NET_ID,
4214 {makeUidRangeParcel(TEST_UID1, TEST_UID1)})
4215 .isOk());
4216 }
4217
4218 // Verify whether packets go through the right network when app explicitly selects a network.
TEST_F(NetdBinderTest,PerAppDefaultNetwork_ExplicitlySelectNetwork)4219 TEST_F(NetdBinderTest, PerAppDefaultNetwork_ExplicitlySelectNetwork) {
4220 createDefaultAndOtherPhysicalNetwork(SYSTEM_DEFAULT_NETID, APP_DEFAULT_NETID);
4221
4222 int systemDefaultFd = sTun.getFdForTesting();
4223 int appDefaultFd = sTun2.getFdForTesting();
4224
4225 // Explicitly select the system default network.
4226 setNetworkForProcess(SYSTEM_DEFAULT_NETID);
4227 // Connections go through the system default network.
4228 expectPacketSentOnNetId(AID_ROOT, SYSTEM_DEFAULT_NETID, systemDefaultFd, EXPLICITLY_SELECT);
4229 expectPacketSentOnNetId(TEST_UID1, SYSTEM_DEFAULT_NETID, systemDefaultFd, EXPLICITLY_SELECT);
4230
4231 // Set TEST_UID1 to default unreachable, which won't affect the explicitly selected network.
4232 // Connections go through the system default network.
4233 EXPECT_TRUE(mNetd->networkAddUidRanges(INetd::UNREACHABLE_NET_ID,
4234 {makeUidRangeParcel(TEST_UID1, TEST_UID1)})
4235 .isOk());
4236 expectPacketSentOnNetId(AID_ROOT, SYSTEM_DEFAULT_NETID, systemDefaultFd, EXPLICITLY_SELECT);
4237 expectPacketSentOnNetId(TEST_UID1, SYSTEM_DEFAULT_NETID, systemDefaultFd, EXPLICITLY_SELECT);
4238
4239 // restore IP rules
4240 EXPECT_TRUE(mNetd->networkRemoveUidRanges(INetd::UNREACHABLE_NET_ID,
4241 {makeUidRangeParcel(TEST_UID1, TEST_UID1)})
4242 .isOk());
4243
4244 // Add TEST_UID1 to per-app default network, which won't affect the explicitly selected network.
4245 EXPECT_TRUE(mNetd->networkAddUidRanges(APP_DEFAULT_NETID,
4246 {makeUidRangeParcel(TEST_UID1, TEST_UID1)})
4247 .isOk());
4248 expectPacketSentOnNetId(AID_ROOT, SYSTEM_DEFAULT_NETID, systemDefaultFd, EXPLICITLY_SELECT);
4249 expectPacketSentOnNetId(TEST_UID1, SYSTEM_DEFAULT_NETID, systemDefaultFd, EXPLICITLY_SELECT);
4250
4251 // Explicitly select the per-app default network.
4252 setNetworkForProcess(APP_DEFAULT_NETID);
4253 // Connections go through the per-app default network.
4254 expectPacketSentOnNetId(AID_ROOT, APP_DEFAULT_NETID, appDefaultFd, EXPLICITLY_SELECT);
4255 expectPacketSentOnNetId(TEST_UID1, APP_DEFAULT_NETID, appDefaultFd, EXPLICITLY_SELECT);
4256 }
4257
4258 // Verify whether packets go through the right network if app does not implicitly or explicitly
4259 // select any network.
TEST_F(NetdBinderTest,PerAppDefaultNetwork_UnconnectedSocket)4260 TEST_F(NetdBinderTest, PerAppDefaultNetwork_UnconnectedSocket) {
4261 createDefaultAndOtherPhysicalNetwork(SYSTEM_DEFAULT_NETID, APP_DEFAULT_NETID);
4262
4263 int systemDefaultFd = sTun.getFdForTesting();
4264 int appDefaultFd = sTun2.getFdForTesting();
4265
4266 // Connections go through the system default network.
4267 expectPacketSentOnNetId(AID_ROOT, NETID_UNSET, systemDefaultFd, UNCONNECTED_SOCKET);
4268 expectPacketSentOnNetId(TEST_UID1, NETID_UNSET, systemDefaultFd, UNCONNECTED_SOCKET);
4269
4270 // Add TEST_UID1 to per-app default network. Traffic should go through the per-app default
4271 // network if UID is in range. Otherwise, go through the system default network.
4272 EXPECT_TRUE(mNetd->networkAddUidRanges(APP_DEFAULT_NETID,
4273 {makeUidRangeParcel(TEST_UID1, TEST_UID1)})
4274 .isOk());
4275 expectPacketSentOnNetId(AID_ROOT, NETID_UNSET, systemDefaultFd, UNCONNECTED_SOCKET);
4276 expectPacketSentOnNetId(TEST_UID1, NETID_UNSET, appDefaultFd, UNCONNECTED_SOCKET);
4277
4278 // Set TEST_UID1's default network to unreachable. Its traffic should still go through the
4279 // per-app default network. Other traffic go through the system default network.
4280 // PS: per-app default network take precedence over unreachable network. This should happens
4281 // only in the transition period when both rules are briefly set.
4282 EXPECT_TRUE(mNetd->networkAddUidRanges(INetd::UNREACHABLE_NET_ID,
4283 {makeUidRangeParcel(TEST_UID1, TEST_UID1)})
4284 .isOk());
4285 expectPacketSentOnNetId(AID_ROOT, NETID_UNSET, systemDefaultFd, UNCONNECTED_SOCKET);
4286 expectPacketSentOnNetId(TEST_UID1, NETID_UNSET, appDefaultFd, UNCONNECTED_SOCKET);
4287
4288 // Remove TEST_UID1's default network from OEM-paid network. Its traffic should get ENETUNREACH
4289 // error. Other traffic still go through the system default network.
4290 EXPECT_TRUE(mNetd->networkRemoveUidRanges(APP_DEFAULT_NETID,
4291 {makeUidRangeParcel(TEST_UID1, TEST_UID1)})
4292 .isOk());
4293 expectPacketSentOnNetId(AID_ROOT, NETID_UNSET, systemDefaultFd, UNCONNECTED_SOCKET);
4294 expectUnreachableError(TEST_UID1, NETID_UNSET, UNCONNECTED_SOCKET);
4295
4296 // restore IP rules
4297 EXPECT_TRUE(mNetd->networkRemoveUidRanges(INetd::UNREACHABLE_NET_ID,
4298 {makeUidRangeParcel(TEST_UID1, TEST_UID1)})
4299 .isOk());
4300 }
4301
TEST_F(NetdBinderTest,PerAppDefaultNetwork_PermissionCheck)4302 TEST_F(NetdBinderTest, PerAppDefaultNetwork_PermissionCheck) {
4303 createPhysicalNetwork(APP_DEFAULT_NETID, sTun2.name(), INetd::PERMISSION_SYSTEM);
4304
4305 { // uid is not in app range. Can not set network for process.
4306 ScopedUidChange scopedUidChange(TEST_UID1);
4307 EXPECT_EQ(-EACCES, setNetworkForProcess(APP_DEFAULT_NETID));
4308 }
4309
4310 EXPECT_TRUE(mNetd->networkAddUidRanges(APP_DEFAULT_NETID,
4311 {makeUidRangeParcel(TEST_UID1, TEST_UID1)})
4312 .isOk());
4313
4314 { // uid is in app range. Can set network for process.
4315 ScopedUidChange scopedUidChange(TEST_UID1);
4316 EXPECT_EQ(0, setNetworkForProcess(APP_DEFAULT_NETID));
4317 }
4318 }
4319
4320 class VpnParameterizedTest : public NetdBinderTest, public testing::WithParamInterface<bool> {};
4321
4322 // Exercise secure and bypassable VPN.
4323 INSTANTIATE_TEST_SUITE_P(PerAppDefaultNetwork, VpnParameterizedTest, testing::Bool(),
__anon784447132002(const testing::TestParamInfo<bool>& info) 4324 [](const testing::TestParamInfo<bool>& info) {
4325 return info.param ? "SecureVPN" : "BypassableVPN";
4326 });
4327
4328 // Verify per-app default network + VPN.
TEST_P(VpnParameterizedTest,ImplicitlySelectNetwork)4329 TEST_P(VpnParameterizedTest, ImplicitlySelectNetwork) {
4330 const bool isSecureVPN = GetParam();
4331 createVpnAndAppDefaultNetworkWithUid(
4332 SYSTEM_DEFAULT_NETID, APP_DEFAULT_NETID, VPN_NETID, isSecureVPN,
4333 {makeUidRangeParcel(TEST_UID2, TEST_UID1)} /* app range */,
4334 {makeUidRangeParcel(TEST_UID3, TEST_UID2)} /* VPN range */);
4335
4336 int systemDefaultFd = sTun.getFdForTesting();
4337 int appDefaultFd = sTun2.getFdForTesting();
4338 int vpnFd = sTun3.getFdForTesting();
4339
4340 // uid is neither in app range, nor in VPN range. Traffic goes through system default network.
4341 expectPacketSentOnNetId(AID_ROOT, SYSTEM_DEFAULT_NETID, systemDefaultFd, IMPLICITLY_SELECT);
4342 // uid is in VPN range, not in app range. Traffic goes through VPN.
4343 expectPacketSentOnNetId(TEST_UID3, (isSecureVPN ? SYSTEM_DEFAULT_NETID : VPN_NETID), vpnFd,
4344 IMPLICITLY_SELECT);
4345 // uid is in app range, not in VPN range. Traffic goes through per-app default network.
4346 expectPacketSentOnNetId(TEST_UID1, APP_DEFAULT_NETID, appDefaultFd, IMPLICITLY_SELECT);
4347 // uid is in both app and VPN range. Traffic goes through VPN.
4348 expectPacketSentOnNetId(TEST_UID2, (isSecureVPN ? APP_DEFAULT_NETID : VPN_NETID), vpnFd,
4349 IMPLICITLY_SELECT);
4350 }
4351
4352 class VpnAndSelectNetworkParameterizedTest
4353 : public NetdBinderTest,
4354 public testing::WithParamInterface<std::tuple<bool, int>> {};
4355
4356 // Exercise the combination of different VPN types and different user selected networks. e.g.
4357 // secure VPN + select on system default network
4358 // secure VPN + select on app default network
4359 // secure VPN + select on VPN
4360 // bypassable VPN + select on system default network
4361 // ...
4362 INSTANTIATE_TEST_SUITE_P(PerAppDefaultNetwork, VpnAndSelectNetworkParameterizedTest,
4363 testing::Combine(testing::Bool(),
4364 testing::Values(SYSTEM_DEFAULT_NETID, APP_DEFAULT_NETID,
4365 VPN_NETID)),
__anon784447132102(const testing::TestParamInfo<std::tuple<bool, int>>& info) 4366 [](const testing::TestParamInfo<std::tuple<bool, int>>& info) {
4367 const std::string vpnType = std::get<0>(info.param)
4368 ? std::string("SecureVPN")
4369 : std::string("BypassableVPN");
4370 std::string selectedNetwork;
4371 switch (std::get<1>(info.param)) {
4372 case SYSTEM_DEFAULT_NETID:
4373 selectedNetwork = "SystemDefaultNetwork";
4374 break;
4375 case APP_DEFAULT_NETID:
4376 selectedNetwork = "AppDefaultNetwork";
4377 break;
4378 case VPN_NETID:
4379 selectedNetwork = "VPN";
4380 break;
4381 default:
4382 selectedNetwork = "InvalidParameter"; // Should not happen.
4383 }
4384 return vpnType + "_select" + selectedNetwork;
4385 });
4386
TEST_P(VpnAndSelectNetworkParameterizedTest,ExplicitlySelectNetwork)4387 TEST_P(VpnAndSelectNetworkParameterizedTest, ExplicitlySelectNetwork) {
4388 bool isSecureVPN;
4389 int selectedNetId;
4390 std::tie(isSecureVPN, selectedNetId) = GetParam();
4391 createVpnAndAppDefaultNetworkWithUid(
4392 SYSTEM_DEFAULT_NETID, APP_DEFAULT_NETID, VPN_NETID, isSecureVPN,
4393 {makeUidRangeParcel(TEST_UID2, TEST_UID1)} /* app range */,
4394 {makeUidRangeParcel(TEST_UID3, TEST_UID2)} /* VPN range */);
4395
4396 int expectedFd = -1;
4397 switch (selectedNetId) {
4398 case SYSTEM_DEFAULT_NETID:
4399 expectedFd = sTun.getFdForTesting();
4400 break;
4401 case APP_DEFAULT_NETID:
4402 expectedFd = sTun2.getFdForTesting();
4403 break;
4404 case VPN_NETID:
4405 expectedFd = sTun3.getFdForTesting();
4406 break;
4407 default:
4408 GTEST_LOG_(ERROR) << "unexpected netId:" << selectedNetId; // Should not happen.
4409 }
4410
4411 // In all following permutations, Traffic should go through the specified network if a process
4412 // can select network for itself. The fwmark should contain process UID and the explicit select
4413 // bit.
4414 { // uid is neither in app range, nor in VPN range. Permission bits, protect bit, and explicit
4415 // select bit are all set because of AID_ROOT.
4416 ScopedUidChange scopedUidChange(AID_ROOT);
4417 EXPECT_EQ(0, setNetworkForProcess(selectedNetId));
4418 expectPacketSentOnNetId(AID_ROOT, selectedNetId, expectedFd, EXPLICITLY_SELECT);
4419 }
4420 { // uid is in VPN range, not in app range.
4421 ScopedUidChange scopedUidChange(TEST_UID3);
4422 // Cannot select non-VPN networks when uid is subject to secure VPN.
4423 if (isSecureVPN && selectedNetId != VPN_NETID) {
4424 EXPECT_EQ(-EPERM, setNetworkForProcess(selectedNetId));
4425 } else {
4426 EXPECT_EQ(0, setNetworkForProcess(selectedNetId));
4427 expectPacketSentOnNetId(TEST_UID3, selectedNetId, expectedFd, EXPLICITLY_SELECT);
4428 }
4429 }
4430 { // uid is in app range, not in VPN range.
4431 ScopedUidChange scopedUidChange(TEST_UID1);
4432 // Cannot select the VPN because the VPN does not applies to the UID.
4433 if (selectedNetId == VPN_NETID) {
4434 EXPECT_EQ(-EPERM, setNetworkForProcess(selectedNetId));
4435 } else {
4436 EXPECT_EQ(0, setNetworkForProcess(selectedNetId));
4437 expectPacketSentOnNetId(TEST_UID1, selectedNetId, expectedFd, EXPLICITLY_SELECT);
4438 }
4439 }
4440 { // uid is in both app range and VPN range.
4441 ScopedUidChange scopedUidChange(TEST_UID2);
4442 // Cannot select non-VPN networks when uid is subject to secure VPN.
4443 if (isSecureVPN && selectedNetId != VPN_NETID) {
4444 EXPECT_EQ(-EPERM, setNetworkForProcess(selectedNetId));
4445 } else {
4446 EXPECT_EQ(0, setNetworkForProcess(selectedNetId));
4447 expectPacketSentOnNetId(TEST_UID2, selectedNetId, expectedFd, EXPLICITLY_SELECT);
4448 }
4449 }
4450 }
4451
TEST_P(VpnParameterizedTest,UnconnectedSocket)4452 TEST_P(VpnParameterizedTest, UnconnectedSocket) {
4453 const bool isSecureVPN = GetParam();
4454 createVpnAndAppDefaultNetworkWithUid(
4455 SYSTEM_DEFAULT_NETID, APP_DEFAULT_NETID, VPN_NETID, isSecureVPN,
4456 {makeUidRangeParcel(TEST_UID2, TEST_UID1)} /* app range */,
4457 {makeUidRangeParcel(TEST_UID3, TEST_UID2)} /* VPN range */);
4458
4459 int systemDefaultFd = sTun.getFdForTesting();
4460 int appDefaultFd = sTun2.getFdForTesting();
4461 int vpnFd = sTun3.getFdForTesting();
4462
4463 // uid is neither in app range, nor in VPN range. Traffic goes through system default network.
4464 expectPacketSentOnNetId(AID_ROOT, NETID_UNSET, systemDefaultFd, UNCONNECTED_SOCKET);
4465 // uid is in VPN range, not in app range. Traffic goes through VPN.
4466 expectPacketSentOnNetId(TEST_UID3, NETID_UNSET, vpnFd, UNCONNECTED_SOCKET);
4467 // uid is in app range, not in VPN range. Traffic goes through per-app default network.
4468 expectPacketSentOnNetId(TEST_UID1, NETID_UNSET, appDefaultFd, UNCONNECTED_SOCKET);
4469 // uid is in both app and VPN range. Traffic goes through VPN.
4470 expectPacketSentOnNetId(TEST_UID2, NETID_UNSET, vpnFd, UNCONNECTED_SOCKET);
4471 }
4472
TEST_F(NetdBinderTest,NetworkCreate)4473 TEST_F(NetdBinderTest, NetworkCreate) {
4474 auto config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
4475 INetd::PERMISSION_NONE, false);
4476 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
4477 EXPECT_TRUE(mNetd->networkDestroy(config.netId).isOk());
4478
4479 config.networkType = NativeNetworkType::VIRTUAL;
4480 config.secure = true;
4481 config.vpnType = NativeVpnType::OEM;
4482 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
4483
4484 // invalid network type
4485 auto wrongConfig = makeNativeNetworkConfig(TEST_NETID2, static_cast<NativeNetworkType>(-1),
4486 INetd::PERMISSION_NONE, false);
4487 EXPECT_EQ(EINVAL, mNetd->networkCreate(wrongConfig).serviceSpecificErrorCode());
4488
4489 // invalid VPN type
4490 wrongConfig.networkType = NativeNetworkType::VIRTUAL;
4491 wrongConfig.vpnType = static_cast<NativeVpnType>(-1);
4492 EXPECT_EQ(EINVAL, mNetd->networkCreate(wrongConfig).serviceSpecificErrorCode());
4493 }
4494
4495 // Verifies valid and invalid inputs on networkAddUidRangesParcel method.
TEST_F(NetdBinderTest,UidRangeSubPriority_ValidateInputs)4496 TEST_F(NetdBinderTest, UidRangeSubPriority_ValidateInputs) {
4497 createVpnAndOtherPhysicalNetwork(SYSTEM_DEFAULT_NETID, APP_DEFAULT_NETID, VPN_NETID,
4498 /*isSecureVPN=*/true);
4499 // Invalid priority -1 on a physical network.
4500 NativeUidRangeConfig uidRangeConfig =
4501 makeNativeUidRangeConfig(APP_DEFAULT_NETID, {makeUidRangeParcel(BASE_UID, BASE_UID)},
4502 UidRanges::DEFAULT_SUB_PRIORITY - 1);
4503 binder::Status status = mNetd->networkAddUidRangesParcel(uidRangeConfig);
4504 EXPECT_FALSE(status.isOk());
4505 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
4506
4507 // Invalid priority 1000 on a physical network.
4508 uidRangeConfig.subPriority = UidRanges::LOWEST_SUB_PRIORITY + 1;
4509 status = mNetd->networkAddUidRangesParcel(uidRangeConfig);
4510 EXPECT_FALSE(status.isOk());
4511 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
4512
4513 // Virtual networks support only default priority.
4514 uidRangeConfig.netId = VPN_NETID;
4515 uidRangeConfig.subPriority = SUB_PRIORITY_1;
4516 status = mNetd->networkAddUidRangesParcel(uidRangeConfig);
4517 EXPECT_FALSE(status.isOk());
4518 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
4519
4520 // For a single network, identical UID ranges with different priorities are allowed.
4521 uidRangeConfig.netId = APP_DEFAULT_NETID;
4522 uidRangeConfig.subPriority = SUB_PRIORITY_1;
4523 EXPECT_TRUE(mNetd->networkAddUidRangesParcel(uidRangeConfig).isOk());
4524 uidRangeConfig.subPriority = SUB_PRIORITY_2;
4525 EXPECT_TRUE(mNetd->networkAddUidRangesParcel(uidRangeConfig).isOk());
4526
4527 // For a single network, identical UID ranges with the same priority is invalid.
4528 status = mNetd->networkAddUidRangesParcel(uidRangeConfig);
4529 EXPECT_FALSE(status.isOk());
4530 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
4531
4532 // Overlapping ranges is invalid.
4533 uidRangeConfig.uidRanges = {makeUidRangeParcel(BASE_UID + 1, BASE_UID + 1),
4534 makeUidRangeParcel(BASE_UID + 1, BASE_UID + 1)};
4535 status = mNetd->networkAddUidRangesParcel(uidRangeConfig);
4536 EXPECT_FALSE(status.isOk());
4537 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
4538 }
4539
4540 // Examines whether IP rules for app default network with subsidiary priorities are correctly added
4541 // and removed.
TEST_F(NetdBinderTest,UidRangeSubPriority_VerifyPhysicalNwIpRules)4542 TEST_F(NetdBinderTest, UidRangeSubPriority_VerifyPhysicalNwIpRules) {
4543 createPhysicalNetwork(TEST_NETID1, sTun.name());
4544 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
4545 createPhysicalNetwork(TEST_NETID2, sTun2.name());
4546 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "::/0", "").isOk());
4547
4548 // Adds priority 1 setting
4549 NativeUidRangeConfig uidRangeConfig1 = makeNativeUidRangeConfig(
4550 TEST_NETID1, {makeUidRangeParcel(BASE_UID, BASE_UID)}, SUB_PRIORITY_1);
4551 EXPECT_TRUE(mNetd->networkAddUidRangesParcel(uidRangeConfig1).isOk());
4552 verifyAppUidRules({true}, uidRangeConfig1, sTun.name());
4553 // Adds priority 2 setting
4554 NativeUidRangeConfig uidRangeConfig2 = makeNativeUidRangeConfig(
4555 TEST_NETID2, {makeUidRangeParcel(BASE_UID + 1, BASE_UID + 1)}, SUB_PRIORITY_2);
4556 EXPECT_TRUE(mNetd->networkAddUidRangesParcel(uidRangeConfig2).isOk());
4557 verifyAppUidRules({true}, uidRangeConfig2, sTun2.name());
4558 // Adds another priority 2 setting
4559 NativeUidRangeConfig uidRangeConfig3 = makeNativeUidRangeConfig(
4560 INetd::UNREACHABLE_NET_ID, {makeUidRangeParcel(BASE_UID + 2, BASE_UID + 2)},
4561 SUB_PRIORITY_2);
4562 EXPECT_TRUE(mNetd->networkAddUidRangesParcel(uidRangeConfig3).isOk());
4563 verifyAppUidRules({true}, uidRangeConfig3, "");
4564
4565 // Removes.
4566 EXPECT_TRUE(mNetd->networkRemoveUidRangesParcel(uidRangeConfig1).isOk());
4567 verifyAppUidRules({false}, uidRangeConfig1, sTun.name());
4568 verifyAppUidRules({true}, uidRangeConfig2, sTun2.name());
4569 verifyAppUidRules({true}, uidRangeConfig3, "");
4570 EXPECT_TRUE(mNetd->networkRemoveUidRangesParcel(uidRangeConfig2).isOk());
4571 verifyAppUidRules({false}, uidRangeConfig1, sTun.name());
4572 verifyAppUidRules({false}, uidRangeConfig2, sTun2.name());
4573 verifyAppUidRules({true}, uidRangeConfig3, "");
4574 EXPECT_TRUE(mNetd->networkRemoveUidRangesParcel(uidRangeConfig3).isOk());
4575 verifyAppUidRules({false}, uidRangeConfig1, sTun.name());
4576 verifyAppUidRules({false}, uidRangeConfig2, sTun2.name());
4577 verifyAppUidRules({false}, uidRangeConfig3, "");
4578 }
4579
4580 // Verify uid range rules on virtual network.
TEST_P(VpnParameterizedTest,UidRangeSubPriority_VerifyVpnIpRules)4581 TEST_P(VpnParameterizedTest, UidRangeSubPriority_VerifyVpnIpRules) {
4582 const bool isSecureVPN = GetParam();
4583 constexpr int VPN_NETID2 = TEST_NETID2;
4584
4585 // Create 2 VPNs, using sTun and sTun2.
4586 auto config = makeNativeNetworkConfig(VPN_NETID, NativeNetworkType::VIRTUAL,
4587 INetd::PERMISSION_NONE, isSecureVPN);
4588 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
4589 EXPECT_TRUE(mNetd->networkAddInterface(VPN_NETID, sTun.name()).isOk());
4590
4591 config = makeNativeNetworkConfig(VPN_NETID2, NativeNetworkType::VIRTUAL, INetd::PERMISSION_NONE,
4592 isSecureVPN);
4593 EXPECT_TRUE(mNetd->networkCreate(config).isOk());
4594 EXPECT_TRUE(mNetd->networkAddInterface(VPN_NETID2, sTun2.name()).isOk());
4595
4596 // Assign uid ranges to different VPNs. Check if rules match.
4597 NativeUidRangeConfig uidRangeConfig1 = makeNativeUidRangeConfig(
4598 VPN_NETID, {makeUidRangeParcel(BASE_UID, BASE_UID)}, UidRanges::DEFAULT_SUB_PRIORITY);
4599 EXPECT_TRUE(mNetd->networkAddUidRangesParcel(uidRangeConfig1).isOk());
4600 verifyVpnUidRules({true}, uidRangeConfig1, sTun.name(), isSecureVPN);
4601
4602 NativeUidRangeConfig uidRangeConfig2 =
4603 makeNativeUidRangeConfig(VPN_NETID2, {makeUidRangeParcel(BASE_UID + 1, BASE_UID + 1)},
4604 UidRanges::DEFAULT_SUB_PRIORITY);
4605 EXPECT_TRUE(mNetd->networkAddUidRangesParcel(uidRangeConfig2).isOk());
4606 verifyVpnUidRules({true}, uidRangeConfig2, sTun2.name(), isSecureVPN);
4607
4608 // Remove uid configs one-by-one. Check if rules match.
4609 EXPECT_TRUE(mNetd->networkRemoveUidRangesParcel(uidRangeConfig1).isOk());
4610 verifyVpnUidRules({false}, uidRangeConfig1, sTun.name(), isSecureVPN);
4611 verifyVpnUidRules({true}, uidRangeConfig2, sTun2.name(), isSecureVPN);
4612 EXPECT_TRUE(mNetd->networkRemoveUidRangesParcel(uidRangeConfig2).isOk());
4613 verifyVpnUidRules({false}, uidRangeConfig1, sTun.name(), isSecureVPN);
4614 verifyVpnUidRules({false}, uidRangeConfig2, sTun2.name(), isSecureVPN);
4615 }
4616
4617 // Verify if packets go through the right network when subsidiary priority and VPN works together.
4618 //
4619 // Test config:
4620 // +----------+------------------------+-------------------------------------------+
4621 // | Priority | UID | Assigned Network |
4622 // +----------+------------------------+-------------------------------------------+
4623 // | 0 | TEST_UID1 | VPN bypassable (VPN_NETID) |
4624 // +----------+------------------------+-------------------------------------------+
4625 // | 1 | TEST_UID1, TEST_UID2, | Physical Network 1 (APP_DEFAULT_1_NETID) |
4626 // | 1 | TEST_UID3 | Physical Network 2 (APP_DEFAULT_2_NETID) |
4627 // | 1 | TEST_UID5 | Unreachable Network (UNREACHABLE_NET_ID) |
4628 // +----------+------------------------+-------------------------------------------+
4629 // | 2 | TEST_UID3 | Physical Network 1 (APP_DEFAULT_1_NETID) |
4630 // | 2 | TEST_UID4, TEST_UID5 | Physical Network 2 (APP_DEFAULT_2_NETID) |
4631 // +----------+------------------------+-------------------------------------------+
4632 //
4633 // Expected results:
4634 // +-----------+------------------------+
4635 // | UID | Using Network |
4636 // +-----------+------------------------+
4637 // | TEST_UID1 | VPN |
4638 // | TEST_UID2 | Physical Network 1 |
4639 // | TEST_UID3 | Physical Network 2 |
4640 // | TEST_UID4 | Physical Network 2 |
4641 // | TEST_UID5 | Unreachable Network |
4642 // | TEST_UID6 | System Default Network |
4643 // +-----------+------------------------+
4644 //
4645 // SYSTEM_DEFAULT_NETID uses sTun.
4646 // APP_DEFAULT_1_NETID uses sTun2.
4647 // VPN_NETID uses sTun3.
4648 // APP_DEFAULT_2_NETID uses sTun4.
4649 //
TEST_F(NetdBinderTest,UidRangeSubPriority_ImplicitlySelectNetwork)4650 TEST_F(NetdBinderTest, UidRangeSubPriority_ImplicitlySelectNetwork) {
4651 constexpr int APP_DEFAULT_1_NETID = TEST_NETID2;
4652 constexpr int APP_DEFAULT_2_NETID = TEST_NETID4;
4653
4654 // Creates 4 networks.
4655 createVpnAndOtherPhysicalNetwork(SYSTEM_DEFAULT_NETID, APP_DEFAULT_1_NETID, VPN_NETID,
4656 /*isSecureVPN=*/false);
4657 createPhysicalNetwork(APP_DEFAULT_2_NETID, sTun4.name());
4658 EXPECT_TRUE(mNetd->networkAddRoute(APP_DEFAULT_2_NETID, sTun4.name(), "::/0", "").isOk());
4659
4660 // Adds VPN setting.
4661 NativeUidRangeConfig uidRangeConfigVpn = makeNativeUidRangeConfig(
4662 VPN_NETID, {makeUidRangeParcel(TEST_UID1, TEST_UID1)}, UidRanges::DEFAULT_SUB_PRIORITY);
4663 EXPECT_TRUE(mNetd->networkAddUidRangesParcel(uidRangeConfigVpn).isOk());
4664
4665 // Adds uidRangeConfig1 setting.
4666 NativeUidRangeConfig uidRangeConfig1 = makeNativeUidRangeConfig(
4667 APP_DEFAULT_1_NETID,
4668 {makeUidRangeParcel(TEST_UID1, TEST_UID1), makeUidRangeParcel(TEST_UID2, TEST_UID2)},
4669 SUB_PRIORITY_1);
4670 EXPECT_TRUE(mNetd->networkAddUidRangesParcel(uidRangeConfig1).isOk());
4671 uidRangeConfig1.netId = APP_DEFAULT_2_NETID;
4672 uidRangeConfig1.uidRanges = {makeUidRangeParcel(TEST_UID3, TEST_UID3)};
4673 EXPECT_TRUE(mNetd->networkAddUidRangesParcel(uidRangeConfig1).isOk());
4674 uidRangeConfig1.netId = INetd::UNREACHABLE_NET_ID;
4675 uidRangeConfig1.uidRanges = {makeUidRangeParcel(TEST_UID5, TEST_UID5)};
4676 EXPECT_TRUE(mNetd->networkAddUidRangesParcel(uidRangeConfig1).isOk());
4677
4678 // Adds uidRangeConfig2 setting.
4679 NativeUidRangeConfig uidRangeConfig2 = makeNativeUidRangeConfig(
4680 APP_DEFAULT_1_NETID, {makeUidRangeParcel(TEST_UID3, TEST_UID3)}, SUB_PRIORITY_2);
4681 EXPECT_TRUE(mNetd->networkAddUidRangesParcel(uidRangeConfig2).isOk());
4682 uidRangeConfig2.netId = APP_DEFAULT_2_NETID;
4683 uidRangeConfig2.uidRanges = {makeUidRangeParcel(TEST_UID4, TEST_UID4),
4684 makeUidRangeParcel(TEST_UID5, TEST_UID5)};
4685 EXPECT_TRUE(mNetd->networkAddUidRangesParcel(uidRangeConfig2).isOk());
4686
4687 int systemDefaultFd = sTun.getFdForTesting();
4688 int appDefault_1_Fd = sTun2.getFdForTesting();
4689 int vpnFd = sTun3.getFdForTesting();
4690 int appDefault_2_Fd = sTun4.getFdForTesting();
4691 // Verify routings.
4692 expectPacketSentOnNetId(TEST_UID1, VPN_NETID, vpnFd, IMPLICITLY_SELECT);
4693 expectPacketSentOnNetId(TEST_UID2, APP_DEFAULT_1_NETID, appDefault_1_Fd, IMPLICITLY_SELECT);
4694 expectPacketSentOnNetId(TEST_UID3, APP_DEFAULT_2_NETID, appDefault_2_Fd, IMPLICITLY_SELECT);
4695 expectPacketSentOnNetId(TEST_UID4, APP_DEFAULT_2_NETID, appDefault_2_Fd, IMPLICITLY_SELECT);
4696 expectUnreachableError(TEST_UID5, INetd::UNREACHABLE_NET_ID, IMPLICITLY_SELECT);
4697 expectPacketSentOnNetId(TEST_UID6, SYSTEM_DEFAULT_NETID, systemDefaultFd, IMPLICITLY_SELECT);
4698
4699 // Remove test rules from the unreachable network.
4700 EXPECT_TRUE(mNetd->networkRemoveUidRangesParcel(uidRangeConfig1).isOk());
4701 }