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