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 <set>
28 #include <vector>
29 
30 #include <dirent.h>
31 #include <fcntl.h>
32 #include <ifaddrs.h>
33 #include <linux/if.h>
34 #include <linux/if_tun.h>
35 #include <net/ethernet.h>
36 #include <net/if.h>
37 #include <netdb.h>
38 #include <netinet/in.h>
39 #include <netinet/tcp.h>
40 #include <openssl/base64.h>
41 #include <sys/socket.h>
42 #include <sys/types.h>
43 
44 #include <android-base/file.h>
45 #include <android-base/format.h>
46 #include <android-base/macros.h>
47 #include <android-base/scopeguard.h>
48 #include <android-base/stringprintf.h>
49 #include <android-base/strings.h>
50 #include <android/multinetwork.h>
51 #include <binder/IPCThreadState.h>
52 #include <bpf/BpfMap.h>
53 #include <bpf/BpfUtils.h>
54 #include <com/android/internal/net/BnOemNetdUnsolicitedEventListener.h>
55 #include <com/android/internal/net/IOemNetd.h>
56 #include <cutils/multiuser.h>
57 #include <gtest/gtest.h>
58 #include <netdbpf/bpf_shared.h>
59 #include <netutils/ifc.h>
60 #include "Fwmark.h"
61 #include "InterfaceController.h"
62 #include "NetdClient.h"
63 #include "NetdConstants.h"
64 #include "NetworkController.h"
65 #include "SockDiag.h"
66 #include "TestUnsolService.h"
67 #include "XfrmController.h"
68 #include "android/net/INetd.h"
69 #include "binder/IServiceManager.h"
70 #include "netdutils/InternetAddresses.h"
71 #include "netdutils/Stopwatch.h"
72 #include "netdutils/Syscalls.h"
73 #include "netid_client.h"  // NETID_UNSET
74 #include "test_utils.h"
75 #include "tun_interface.h"
76 
77 #define IP6TABLES_PATH "/system/bin/ip6tables"
78 #define IPTABLES_PATH "/system/bin/iptables"
79 #define RAW_TABLE "raw"
80 #define MANGLE_TABLE "mangle"
81 #define FILTER_TABLE "filter"
82 #define NAT_TABLE "nat"
83 
84 namespace binder = android::binder;
85 
86 using android::IBinder;
87 using android::IServiceManager;
88 using android::sp;
89 using android::String16;
90 using android::String8;
91 using android::base::Join;
92 using android::base::make_scope_guard;
93 using android::base::ReadFileToString;
94 using android::base::StartsWith;
95 using android::base::StringPrintf;
96 using android::base::Trim;
97 using android::base::unique_fd;
98 using android::net::INetd;
99 using android::net::InterfaceConfigurationParcel;
100 using android::net::InterfaceController;
101 using android::net::MarkMaskParcel;
102 using android::net::SockDiag;
103 using android::net::TetherOffloadRuleParcel;
104 using android::net::TetherStatsParcel;
105 using android::net::TunInterface;
106 using android::net::UidRangeParcel;
107 using android::netdutils::IPAddress;
108 using android::netdutils::ScopedAddrinfo;
109 using android::netdutils::sSyscalls;
110 using android::netdutils::Stopwatch;
111 
112 static const char* IP_RULE_V4 = "-4";
113 static const char* IP_RULE_V6 = "-6";
114 static const int TEST_NETID1 = 65501;
115 static const int TEST_NETID2 = 65502;
116 static const char* DNSMASQ = "dnsmasq";
117 
118 // Use maximum reserved appId for applications to avoid conflict with existing
119 // uids.
120 static const int TEST_UID1 = 99999;
121 static const int TEST_UID2 = 99998;
122 
123 constexpr int BASE_UID = AID_USER_OFFSET * 5;
124 
125 static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
126 static const std::string ESP_ALLOW_RULE("esp");
127 
128 class NetdBinderTest : public ::testing::Test {
129   public:
NetdBinderTest()130     NetdBinderTest() {
131         sp<IServiceManager> sm = android::defaultServiceManager();
132         sp<IBinder> binder = sm->getService(String16("netd"));
133         if (binder != nullptr) {
134             mNetd = android::interface_cast<INetd>(binder);
135         }
136     }
137 
SetUp()138     void SetUp() override {
139         ASSERT_NE(nullptr, mNetd.get());
140     }
141 
TearDown()142     void TearDown() override {
143         mNetd->networkDestroy(TEST_NETID1);
144         mNetd->networkDestroy(TEST_NETID2);
145         setNetworkForProcess(NETID_UNSET);
146         // Restore default network
147         if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
148     }
149 
150     bool allocateIpSecResources(bool expectOk, int32_t* spi);
151 
152     // Static because setting up the tun interface takes about 40ms.
SetUpTestCase()153     static void SetUpTestCase() {
154         ASSERT_EQ(0, sTun.init());
155         ASSERT_EQ(0, sTun2.init());
156         ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
157         ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
158     }
159 
TearDownTestCase()160     static void TearDownTestCase() {
161         // Closing the socket removes the interface and IP addresses.
162         sTun.destroy();
163         sTun2.destroy();
164     }
165 
166     static void fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
167                                      unique_fd* acceptedSocket);
168 
169     void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
170                                  int fallthroughNetId = TEST_NETID1);
171 
172   protected:
173     // Use -1 to represent that default network was not modified because
174     // real netId must be an unsigned value.
175     int mStoredDefaultNetwork = -1;
176     sp<INetd> mNetd;
177     static TunInterface sTun;
178     static TunInterface sTun2;
179 };
180 
181 TunInterface NetdBinderTest::sTun;
182 TunInterface NetdBinderTest::sTun2;
183 
184 class TimedOperation : public Stopwatch {
185   public:
TimedOperation(const std::string & name)186     explicit TimedOperation(const std::string &name): mName(name) {}
~TimedOperation()187     virtual ~TimedOperation() {
188         std::cerr << "    " << mName << ": " << timeTakenUs() << "us" << std::endl;
189     }
190 
191   private:
192     std::string mName;
193 };
194 
TEST_F(NetdBinderTest,IsAlive)195 TEST_F(NetdBinderTest, IsAlive) {
196     TimedOperation t("isAlive RPC");
197     bool isAlive = false;
198     mNetd->isAlive(&isAlive);
199     ASSERT_TRUE(isAlive);
200 }
201 
iptablesNoSocketAllowRuleExists(const char * chainName)202 static bool iptablesNoSocketAllowRuleExists(const char *chainName){
203     return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
204            iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
205 }
206 
iptablesEspAllowRuleExists(const char * chainName)207 static bool iptablesEspAllowRuleExists(const char *chainName){
208     return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
209            iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
210 }
211 
TEST_F(NetdBinderTest,FirewallReplaceUidChain)212 TEST_F(NetdBinderTest, FirewallReplaceUidChain) {
213     SKIP_IF_BPF_SUPPORTED;
214 
215     std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
216     const int kNumUids = 500;
217     std::vector<int32_t> noUids(0);
218     std::vector<int32_t> uids(kNumUids);
219     for (int i = 0; i < kNumUids; i++) {
220         uids[i] = randomUid();
221     }
222 
223     bool ret;
224     {
225         TimedOperation op(StringPrintf("Programming %d-UID allowlist chain", kNumUids));
226         mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
227     }
228     EXPECT_EQ(true, ret);
229     EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
230     EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
231     EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
232     EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
233     {
234         TimedOperation op("Clearing allowlist chain");
235         mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
236     }
237     EXPECT_EQ(true, ret);
238     EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
239     EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
240 
241     {
242         TimedOperation op(StringPrintf("Programming %d-UID denylist chain", kNumUids));
243         mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
244     }
245     EXPECT_EQ(true, ret);
246     EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
247     EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
248     EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
249     EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
250 
251     {
252         TimedOperation op("Clearing denylist chain");
253         mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
254     }
255     EXPECT_EQ(true, ret);
256     EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
257     EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
258 
259     // Check that the call fails if iptables returns an error.
260     std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
261     mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
262     EXPECT_EQ(false, ret);
263 }
264 
TEST_F(NetdBinderTest,IpSecTunnelInterface)265 TEST_F(NetdBinderTest, IpSecTunnelInterface) {
266     const struct TestData {
267         const std::string family;
268         const std::string deviceName;
269         const std::string localAddress;
270         const std::string remoteAddress;
271         int32_t iKey;
272         int32_t oKey;
273         int32_t ifId;
274     } kTestData[] = {
275             {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
276             {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
277              0xFFFE},
278     };
279 
280     for (size_t i = 0; i < std::size(kTestData); i++) {
281         const auto& td = kTestData[i];
282 
283         binder::Status status;
284 
285         // Create Tunnel Interface.
286         status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
287                                                 td.iKey, td.oKey, td.ifId);
288         EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
289 
290         // Check that the interface exists
291         EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
292 
293         // Update Tunnel Interface.
294         status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
295                                                    td.iKey, td.oKey, td.ifId);
296         EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
297 
298         // Remove Tunnel Interface.
299         status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
300         EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
301 
302         // Check that the interface no longer exists
303         EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
304     }
305 }
306 
TEST_F(NetdBinderTest,IpSecSetEncapSocketOwner)307 TEST_F(NetdBinderTest, IpSecSetEncapSocketOwner) {
308     unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
309     android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
310 
311     int sockOptVal = UDP_ENCAP_ESPINUDP;
312     setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
313 
314     binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
315     EXPECT_TRUE(res.isOk());
316 
317     struct stat info;
318     EXPECT_EQ(0, fstat(sockFd.get(), &info));
319     EXPECT_EQ(1001, (int) info.st_uid);
320 }
321 
322 // IPsec tests are not run in 32 bit mode; both 32-bit kernels and
323 // mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
324 #if INTPTR_MAX != INT32_MAX
325 
326 using android::net::XfrmController;
327 
328 static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
329                                       static_cast<int>(android::net::XfrmDirection::OUT)};
330 static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
331 
332 #define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
333         do { if ((_expect_) != (_ret_)) return false; } while(false)
allocateIpSecResources(bool expectOk,int32_t * spi)334 bool NetdBinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
335     android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
336     SCOPED_TRACE(status);
337     RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
338 
339     // Add a policy
340     status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
341     SCOPED_TRACE(status);
342     RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
343 
344     // Add an ipsec interface
345     return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
346                                                                0xD00D, 0xE00D, false)
347                                .ok();
348 }
349 
TEST_F(NetdBinderTest,XfrmDualSelectorTunnelModePoliciesV4)350 TEST_F(NetdBinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
351     android::binder::Status status;
352 
353     // Repeat to ensure cleanup and recreation works correctly
354     for (int i = 0; i < 2; i++) {
355         for (int direction : XFRM_DIRECTIONS) {
356             for (int addrFamily : ADDRESS_FAMILIES) {
357                 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
358                                                        "127.0.0.6", 123, 0, 0, 0);
359                 EXPECT_TRUE(status.isOk())
360                         << " family: " << addrFamily << " direction: " << direction;
361             }
362         }
363 
364         // Cleanup
365         for (int direction : XFRM_DIRECTIONS) {
366             for (int addrFamily : ADDRESS_FAMILIES) {
367                 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
368                 EXPECT_TRUE(status.isOk());
369             }
370         }
371     }
372 }
373 
TEST_F(NetdBinderTest,XfrmDualSelectorTunnelModePoliciesV6)374 TEST_F(NetdBinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
375     binder::Status status;
376 
377     // Repeat to ensure cleanup and recreation works correctly
378     for (int i = 0; i < 2; i++) {
379         for (int direction : XFRM_DIRECTIONS) {
380             for (int addrFamily : ADDRESS_FAMILIES) {
381                 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
382                                                        "2001:db8::d00d", 123, 0, 0, 0);
383                 EXPECT_TRUE(status.isOk())
384                         << " family: " << addrFamily << " direction: " << direction;
385             }
386         }
387 
388         // Cleanup
389         for (int direction : XFRM_DIRECTIONS) {
390             for (int addrFamily : ADDRESS_FAMILIES) {
391                 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
392                 EXPECT_TRUE(status.isOk());
393             }
394         }
395     }
396 }
397 
TEST_F(NetdBinderTest,XfrmControllerInit)398 TEST_F(NetdBinderTest, XfrmControllerInit) {
399     android::netdutils::Status status;
400     status = XfrmController::Init();
401     SCOPED_TRACE(status);
402 
403     // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
404     // feature.
405     if (status.code() == EOPNOTSUPP) return;
406 
407     ASSERT_TRUE(status.ok());
408 
409     int32_t spi = 0;
410 
411     ASSERT_TRUE(allocateIpSecResources(true, &spi));
412     ASSERT_TRUE(allocateIpSecResources(false, &spi));
413 
414     status = XfrmController::Init();
415     ASSERT_TRUE(status.ok());
416     ASSERT_TRUE(allocateIpSecResources(true, &spi));
417 
418     // Clean up
419     status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
420     SCOPED_TRACE(status);
421     ASSERT_TRUE(status.ok());
422 
423     status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
424     SCOPED_TRACE(status);
425     ASSERT_TRUE(status.ok());
426 
427     // Remove Virtual Tunnel Interface.
428     ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
429 }
430 
431 #endif  // INTPTR_MAX != INT32_MAX
432 
bandwidthDataSaverEnabled(const char * binary)433 static int bandwidthDataSaverEnabled(const char *binary) {
434     std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
435 
436     // Output looks like this:
437     //
438     // Chain bw_data_saver (1 references)
439     // target     prot opt source               destination
440     // RETURN     all  --  0.0.0.0/0            0.0.0.0/0
441     //
442     // or:
443     //
444     // Chain bw_data_saver (1 references)
445     // target     prot opt source               destination
446     // ... possibly connectivity critical packet rules here ...
447     // REJECT     all  --  ::/0            ::/0
448 
449     EXPECT_GE(lines.size(), 3U);
450 
451     if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
452         // Data saver disabled.
453         return 0;
454     }
455 
456     size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
457 
458     if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
459         // Data saver enabled.
460         return 1;
461     }
462 
463     return -1;
464 }
465 
enableDataSaver(sp<INetd> & netd,bool enable)466 bool enableDataSaver(sp<INetd>& netd, bool enable) {
467     TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
468     bool ret;
469     netd->bandwidthEnableDataSaver(enable, &ret);
470     return ret;
471 }
472 
getDataSaverState()473 int getDataSaverState() {
474     const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
475     const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
476     EXPECT_EQ(enabled4, enabled6);
477     EXPECT_NE(-1, enabled4);
478     EXPECT_NE(-1, enabled6);
479     if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
480         return -1;
481     }
482     return enabled6;
483 }
484 
TEST_F(NetdBinderTest,BandwidthEnableDataSaver)485 TEST_F(NetdBinderTest, BandwidthEnableDataSaver) {
486     const int wasEnabled = getDataSaverState();
487     ASSERT_NE(-1, wasEnabled);
488 
489     if (wasEnabled) {
490         ASSERT_TRUE(enableDataSaver(mNetd, false));
491         EXPECT_EQ(0, getDataSaverState());
492     }
493 
494     ASSERT_TRUE(enableDataSaver(mNetd, false));
495     EXPECT_EQ(0, getDataSaverState());
496 
497     ASSERT_TRUE(enableDataSaver(mNetd, true));
498     EXPECT_EQ(1, getDataSaverState());
499 
500     ASSERT_TRUE(enableDataSaver(mNetd, true));
501     EXPECT_EQ(1, getDataSaverState());
502 
503     if (!wasEnabled) {
504         ASSERT_TRUE(enableDataSaver(mNetd, false));
505         EXPECT_EQ(0, getDataSaverState());
506     }
507 }
508 
ipRuleExistsForRange(const uint32_t priority,const UidRangeParcel & range,const std::string & action,const char * ipVersion)509 static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
510                                  const std::string& action, const char* ipVersion) {
511     // Output looks like this:
512     //   "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
513     std::vector<std::string> rules = listIpRules(ipVersion);
514 
515     std::string prefix = StringPrintf("%" PRIu32 ":", priority);
516     std::string suffix =
517             StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
518     for (const auto& line : rules) {
519         if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
520             return true;
521         }
522     }
523     return false;
524 }
525 
ipRuleExistsForRange(const uint32_t priority,const UidRangeParcel & range,const std::string & action)526 static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
527                                  const std::string& action) {
528     bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
529     bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
530     EXPECT_EQ(existsIp4, existsIp6);
531     return existsIp4;
532 }
533 
534 namespace {
535 
makeUidRangeParcel(int start,int stop)536 UidRangeParcel makeUidRangeParcel(int start, int stop) {
537     UidRangeParcel res;
538     res.start = start;
539     res.stop = stop;
540 
541     return res;
542 }
543 
544 }  // namespace
545 
TEST_F(NetdBinderTest,NetworkInterfaces)546 TEST_F(NetdBinderTest, NetworkInterfaces) {
547     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
548     EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
549                               .serviceSpecificErrorCode());
550     EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
551     EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
552 
553     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
554     EXPECT_EQ(EBUSY,
555               mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
556 
557     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
558     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
559     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
560     EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
561 }
562 
TEST_F(NetdBinderTest,NetworkUidRules)563 TEST_F(NetdBinderTest, NetworkUidRules) {
564     const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
565 
566     EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
567     EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
568     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
569 
570     std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
571                                              makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
572     UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
573     std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
574 
575     EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
576 
577     EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
578     EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
579     EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
580     EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
581 
582     EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
583     EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
584     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
585     EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
586 
587     EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
588 }
589 
TEST_F(NetdBinderTest,NetworkRejectNonSecureVpn)590 TEST_F(NetdBinderTest, NetworkRejectNonSecureVpn) {
591     constexpr uint32_t RULE_PRIORITY = 12500;
592 
593     std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
594                                              makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
595     // Make sure no rules existed before calling commands.
596     for (auto const& range : uidRanges) {
597         EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
598     }
599     // Create two valid rules.
600     ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
601     for (auto const& range : uidRanges) {
602         EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
603     }
604 
605     // Remove the rules.
606     ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
607     for (auto const& range : uidRanges) {
608         EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
609     }
610 
611     // Fail to remove the rules a second time after they are already deleted.
612     binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
613     ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
614     EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
615 }
616 
617 // Create a socket pair that isLoopbackSocket won't think is local.
fakeRemoteSocketPair(unique_fd * clientSocket,unique_fd * serverSocket,unique_fd * acceptedSocket)618 void NetdBinderTest::fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
619                                           unique_fd* acceptedSocket) {
620     serverSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
621     struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
622     ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
623 
624     socklen_t addrlen = sizeof(server6);
625     ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
626     ASSERT_EQ(0, listen(*serverSocket, 10));
627 
628     clientSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
629     struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
630     ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
631     ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
632     ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
633 
634     acceptedSocket->reset(
635             accept4(*serverSocket, (struct sockaddr*)&server6, &addrlen, SOCK_CLOEXEC));
636     ASSERT_NE(-1, *acceptedSocket);
637 
638     ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
639 }
640 
checkSocketpairOpen(int clientSocket,int acceptedSocket)641 void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
642     char buf[4096];
643     EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
644     EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
645     EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
646 }
647 
checkSocketpairClosed(int clientSocket,int acceptedSocket)648 void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
649     // Check that the client socket was closed with ECONNABORTED.
650     int ret = write(clientSocket, "foo", sizeof("foo"));
651     int err = errno;
652     EXPECT_EQ(-1, ret);
653     EXPECT_EQ(ECONNABORTED, err);
654 
655     // Check that it sent a RST to the server.
656     ret = write(acceptedSocket, "foo", sizeof("foo"));
657     err = errno;
658     EXPECT_EQ(-1, ret);
659     EXPECT_EQ(ECONNRESET, err);
660 }
661 
TEST_F(NetdBinderTest,SocketDestroy)662 TEST_F(NetdBinderTest, SocketDestroy) {
663     unique_fd clientSocket, serverSocket, acceptedSocket;
664     ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
665 
666     // Pick a random UID in the system UID range.
667     constexpr int baseUid = AID_APP - 2000;
668     static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
669     int uid = baseUid + 500 + arc4random_uniform(1000);
670     EXPECT_EQ(0, fchown(clientSocket, uid, -1));
671 
672     // UID ranges that don't contain uid.
673     std::vector<UidRangeParcel> uidRanges = {
674             makeUidRangeParcel(baseUid + 42, baseUid + 449),
675             makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
676             makeUidRangeParcel(baseUid + 498, uid - 1),
677             makeUidRangeParcel(uid + 1, baseUid + 1520),
678     };
679     // A skip list that doesn't contain UID.
680     std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
681 
682     // Close sockets. Our test socket should be intact.
683     EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
684     checkSocketpairOpen(clientSocket, acceptedSocket);
685 
686     // UID ranges that do contain uid.
687     uidRanges = {
688             makeUidRangeParcel(baseUid + 42, baseUid + 449),
689             makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
690             makeUidRangeParcel(baseUid + 498, baseUid + 1520),
691     };
692     // Add uid to the skip list.
693     skipUids.push_back(uid);
694 
695     // Close sockets. Our test socket should still be intact because it's in the skip list.
696     EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
697     checkSocketpairOpen(clientSocket, acceptedSocket);
698 
699     // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
700     skipUids.resize(skipUids.size() - 1);
701     EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
702     checkSocketpairClosed(clientSocket, acceptedSocket);
703 }
704 
705 namespace {
706 
netmaskToPrefixLength(const uint8_t * buf,size_t buflen)707 int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
708     if (buf == nullptr) return -1;
709 
710     int prefixLength = 0;
711     bool endOfContiguousBits = false;
712     for (unsigned int i = 0; i < buflen; i++) {
713         const uint8_t value = buf[i];
714 
715         // Bad bit sequence: check for a contiguous set of bits from the high
716         // end by verifying that the inverted value + 1 is a power of 2
717         // (power of 2 iff. (v & (v - 1)) == 0).
718         const uint8_t inverse = ~value + 1;
719         if ((inverse & (inverse - 1)) != 0) return -1;
720 
721         prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
722 
723         // Bogus netmask.
724         if (endOfContiguousBits && value != 0) return -1;
725 
726         if (value != 0xff) endOfContiguousBits = true;
727     }
728 
729     return prefixLength;
730 }
731 
732 template<typename T>
netmaskToPrefixLength(const T * p)733 int netmaskToPrefixLength(const T *p) {
734     return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
735 }
736 
737 
interfaceHasAddress(const std::string & ifname,const char * addrString,int prefixLength)738 static bool interfaceHasAddress(
739         const std::string &ifname, const char *addrString, int prefixLength) {
740     struct addrinfo *addrinfoList = nullptr;
741 
742     const struct addrinfo hints = {
743         .ai_flags    = AI_NUMERICHOST,
744         .ai_family   = AF_UNSPEC,
745         .ai_socktype = SOCK_DGRAM,
746     };
747     if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
748         addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
749         return false;
750     }
751     ScopedAddrinfo addrinfoCleanup(addrinfoList);
752 
753     struct ifaddrs *ifaddrsList = nullptr;
754     ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
755 
756     if (getifaddrs(&ifaddrsList) != 0) {
757         return false;
758     }
759 
760     for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
761         if (std::string(addr->ifa_name) != ifname ||
762             addr->ifa_addr == nullptr ||
763             addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
764             continue;
765         }
766 
767         switch (addr->ifa_addr->sa_family) {
768         case AF_INET: {
769             auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
770             auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
771             if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
772                 continue;
773             }
774 
775             if (prefixLength < 0) return true;  // not checking prefix lengths
776 
777             if (addr->ifa_netmask == nullptr) return false;
778             auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
779             EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
780             return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
781         }
782         case AF_INET6: {
783             auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
784             auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
785             if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
786                 continue;
787             }
788 
789             if (prefixLength < 0) return true;  // not checking prefix lengths
790 
791             if (addr->ifa_netmask == nullptr) return false;
792             auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
793             EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
794             return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
795         }
796         default:
797             // Cannot happen because we have already screened for matching
798             // address families at the top of each iteration.
799             continue;
800         }
801     }
802 
803     return false;
804 }
805 
806 }  // namespace
807 
TEST_F(NetdBinderTest,InterfaceAddRemoveAddress)808 TEST_F(NetdBinderTest, InterfaceAddRemoveAddress) {
809     static const struct TestData {
810         const char *addrString;
811         const int   prefixLength;
812         const int expectAddResult;
813         const int expectRemoveResult;
814     } kTestData[] = {
815             {"192.0.2.1", 24, 0, 0},
816             {"192.0.2.2", 25, 0, 0},
817             {"192.0.2.3", 32, 0, 0},
818             {"192.0.2.4", 33, EINVAL, EADDRNOTAVAIL},
819             {"192.not.an.ip", 24, EINVAL, EINVAL},
820             {"2001:db8::1", 64, 0, 0},
821             {"2001:db8::2", 65, 0, 0},
822             {"2001:db8::3", 128, 0, 0},
823             {"2001:db8::4", 129, EINVAL, EINVAL},
824             {"foo:bar::bad", 64, EINVAL, EINVAL},
825             {"2001:db8::1/64", 64, EINVAL, EINVAL},
826     };
827 
828     for (size_t i = 0; i < std::size(kTestData); i++) {
829         const auto &td = kTestData[i];
830 
831         SCOPED_TRACE(String8::format("Offending IP address %s/%d", td.addrString, td.prefixLength));
832 
833         // [1.a] Add the address.
834         binder::Status status = mNetd->interfaceAddAddress(
835                 sTun.name(), td.addrString, td.prefixLength);
836         if (td.expectAddResult == 0) {
837             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
838         } else {
839             ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
840             ASSERT_EQ(td.expectAddResult, status.serviceSpecificErrorCode());
841         }
842 
843         // [1.b] Verify the addition meets the expectation.
844         if (td.expectAddResult == 0) {
845             EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
846         } else {
847             EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
848         }
849 
850         // [2.a] Try to remove the address.  If it was not previously added, removing it fails.
851         status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
852         if (td.expectRemoveResult == 0) {
853             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
854         } else {
855             ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
856             ASSERT_EQ(td.expectRemoveResult, status.serviceSpecificErrorCode());
857         }
858 
859         // [2.b] No matter what, the address should not be present.
860         EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
861     }
862 
863     // Check that netlink errors are returned correctly.
864     // We do this by attempting to create an IPv6 address on an interface that has IPv6 disabled,
865     // which returns EACCES.
866     TunInterface tun;
867     ASSERT_EQ(0, tun.init());
868     binder::Status status =
869             mNetd->setProcSysNet(INetd::IPV6, INetd::CONF, tun.name(), "disable_ipv6", "1");
870     ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
871     status = mNetd->interfaceAddAddress(tun.name(), "2001:db8::1", 64);
872     EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
873     EXPECT_EQ(EACCES, status.serviceSpecificErrorCode());
874     tun.destroy();
875 }
876 
TEST_F(NetdBinderTest,GetProcSysNet)877 TEST_F(NetdBinderTest, GetProcSysNet) {
878     const char LOOPBACK[] = "lo";
879     static const struct {
880         const int ipversion;
881         const int which;
882         const char* ifname;
883         const char* parameter;
884         const char* expectedValue;
885         const int expectedReturnCode;
886     } kTestData[] = {
887             {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
888             {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
889             {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
890             {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
891             {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
892             {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
893             {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
894     };
895 
896     for (size_t i = 0; i < std::size(kTestData); i++) {
897         const auto& td = kTestData[i];
898 
899         std::string value;
900         const binder::Status status =
901                 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
902 
903         if (td.expectedReturnCode == 0) {
904             SCOPED_TRACE(String8::format("test case %zu should have passed", i));
905             EXPECT_EQ(0, status.exceptionCode());
906             EXPECT_EQ(0, status.serviceSpecificErrorCode());
907             EXPECT_EQ(td.expectedValue, value);
908         } else {
909             SCOPED_TRACE(String8::format("test case %zu should have failed", i));
910             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
911             EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
912         }
913     }
914 }
915 
TEST_F(NetdBinderTest,SetProcSysNet)916 TEST_F(NetdBinderTest, SetProcSysNet) {
917     static const struct {
918         const int ipversion;
919         const int which;
920         const char* ifname;
921         const char* parameter;
922         const char* value;
923         const int expectedReturnCode;
924     } kTestData[] = {
925             {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
926             {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
927             {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
928             {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
929             {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
930             {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
931             {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
932     };
933 
934     for (size_t i = 0; i < std::size(kTestData); i++) {
935         const auto& td = kTestData[i];
936         const binder::Status status =
937                 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
938 
939         if (td.expectedReturnCode == 0) {
940             SCOPED_TRACE(String8::format("test case %zu should have passed", i));
941             EXPECT_EQ(0, status.exceptionCode());
942             EXPECT_EQ(0, status.serviceSpecificErrorCode());
943         } else {
944             SCOPED_TRACE(String8::format("test case %zu should have failed", i));
945             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
946             EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
947         }
948     }
949 }
950 
TEST_F(NetdBinderTest,GetSetProcSysNet)951 TEST_F(NetdBinderTest, GetSetProcSysNet) {
952     const int ipversion = INetd::IPV6;
953     const int category = INetd::NEIGH;
954     const std::string& tun = sTun.name();
955     const std::string parameter("ucast_solicit");
956 
957     std::string value{};
958     EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
959     ASSERT_FALSE(value.empty());
960     const int ival = std::stoi(value);
961     EXPECT_GT(ival, 0);
962     // Try doubling the parameter value (always best!).
963     EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
964             .isOk());
965     EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
966     EXPECT_EQ(2 * ival, std::stoi(value));
967     // Try resetting the parameter.
968     EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
969             .isOk());
970     EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
971     EXPECT_EQ(ival, std::stoi(value));
972 }
973 
974 namespace {
975 
expectNoTestCounterRules()976 void expectNoTestCounterRules() {
977     for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
978         std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
979         std::string allRules = Join(runCommand(command), "\n");
980         EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
981     }
982 }
983 
addTetherCounterValues(const char * path,const std::string & if1,const std::string & if2,int byte,int pkt)984 void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
985                             int byte, int pkt) {
986     runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
987                             path, if1.c_str(), if2.c_str(), pkt, byte));
988 }
989 
delTetherCounterValues(const char * path,const std::string & if1,const std::string & if2)990 void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
991     runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
992                             path, if1.c_str(), if2.c_str()));
993     runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
994                             path, if2.c_str(), if1.c_str()));
995 }
996 
getStatsVectorByIf(const std::vector<TetherStatsParcel> & statsVec,const std::string & iface)997 std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
998                                         const std::string& iface) {
999     for (auto& stats : statsVec) {
1000         if (stats.iface == iface) {
1001             return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1002         }
1003     }
1004     return {};
1005 }
1006 
1007 }  // namespace
1008 
TEST_F(NetdBinderTest,TetherGetStats)1009 TEST_F(NetdBinderTest, TetherGetStats) {
1010     expectNoTestCounterRules();
1011 
1012     // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1013     // disabling tethering. We don't check the return value because these commands will fail if
1014     // tethering is already enabled.
1015     runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1016     runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1017 
1018     std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1019     std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1020     std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1021 
1022     // Ensure we won't use the same interface name, otherwise the test will fail.
1023     u_int32_t rNumber = arc4random_uniform(10000);
1024     std::string extIface1 = StringPrintf("netdtest_%u", rNumber);
1025     std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1);
1026 
1027     addTetherCounterValues(IPTABLES_PATH,  intIface1, extIface1, 123, 111);
1028     addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456,  10);
1029     addTetherCounterValues(IPTABLES_PATH,  extIface1, intIface1, 321, 222);
1030     addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654,  20);
1031     // RX is from external to internal, and TX is from internal to external.
1032     // So rxBytes is 321 + 654  = 975, txBytes is 123 + 456 = 579, etc.
1033     std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1034 
1035     addTetherCounterValues(IPTABLES_PATH,  intIface2, extIface2, 1000, 333);
1036     addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000,  30);
1037 
1038     addTetherCounterValues(IPTABLES_PATH,  extIface2, intIface2, 2000, 444);
1039     addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000,  40);
1040 
1041     addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000,  25);
1042     addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000,  35);
1043     std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1044 
1045     std::vector<TetherStatsParcel> statsVec;
1046     binder::Status status = mNetd->tetherGetStats(&statsVec);
1047     EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1048 
1049     EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
1050 
1051     EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
1052 
1053     for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1054         delTetherCounterValues(path, intIface1, extIface1);
1055         delTetherCounterValues(path, intIface2, extIface2);
1056         if (path == IP6TABLES_PATH) {
1057             delTetherCounterValues(path, intIface3, extIface2);
1058         }
1059     }
1060 
1061     expectNoTestCounterRules();
1062 }
1063 
1064 namespace {
1065 
1066 constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1067 constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
1068 
listIptablesRuleByTable(const char * binary,const char * table,const char * chainName)1069 static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1070                                                         const char* chainName) {
1071     std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1072     return runCommand(command);
1073 }
1074 
1075 // 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)1076 bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
1077                                           const std::string& expectedInterface,
1078                                           const std::string& expectedRule, const char* table) {
1079     std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1080     for (const auto& rule : rules) {
1081         if (rule.find(expectedInterface) != std::string::npos) {
1082             if (rule.find(expectedRule) != std::string::npos) {
1083                 return true;
1084             }
1085         }
1086     }
1087     return false;
1088 }
1089 
expectIdletimerInterfaceRuleExists(const std::string & ifname,int timeout,const std::string & classLabel)1090 void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
1091                                         const std::string& classLabel) {
1092     std::string IdletimerRule =
1093             StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
1094     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1095         EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1096                                                          IdletimerRule, RAW_TABLE));
1097         EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
1098                                                          ifname, IdletimerRule, MANGLE_TABLE));
1099     }
1100 }
1101 
expectIdletimerInterfaceRuleNotExists(const std::string & ifname,int timeout,const std::string & classLabel)1102 void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
1103                                            const std::string& classLabel) {
1104     std::string IdletimerRule =
1105             StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
1106     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1107         EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1108                                                           IdletimerRule, RAW_TABLE));
1109         EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
1110                                                           ifname, IdletimerRule, MANGLE_TABLE));
1111     }
1112 }
1113 
1114 }  // namespace
1115 
TEST_F(NetdBinderTest,IdletimerAddRemoveInterface)1116 TEST_F(NetdBinderTest, IdletimerAddRemoveInterface) {
1117     // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1118     // rule in the table. Because we only check the result after calling remove function. We might
1119     // check the actual rule which is removed by our function (maybe compare the results between
1120     // calling function before and after)
1121     binder::Status status;
1122     const struct TestData {
1123         const std::string ifname;
1124         int32_t timeout;
1125         const std::string classLabel;
1126     } idleTestData[] = {
1127             {"wlan0", 1234, "happyday"},
1128             {"rmnet_data0", 4567, "friday"},
1129     };
1130     for (const auto& td : idleTestData) {
1131         status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1132         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1133         expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1134 
1135         status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1136         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1137         expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1138     }
1139 }
1140 
1141 namespace {
1142 
1143 constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1144 constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1145 
expectStrictSetUidAccept(const int uid)1146 void expectStrictSetUidAccept(const int uid) {
1147     std::string uidRule = StringPrintf("owner UID match %u", uid);
1148     std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1149     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1150         EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1151         EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
1152         EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1153     }
1154 }
1155 
expectStrictSetUidLog(const int uid)1156 void expectStrictSetUidLog(const int uid) {
1157     static const char logRule[] = "st_penalty_log  all";
1158     std::string uidRule = StringPrintf("owner UID match %u", uid);
1159     std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1160     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1161         EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1162         EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
1163         EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1164     }
1165 }
1166 
expectStrictSetUidReject(const int uid)1167 void expectStrictSetUidReject(const int uid) {
1168     static const char rejectRule[] = "st_penalty_reject  all";
1169     std::string uidRule = StringPrintf("owner UID match %u", uid);
1170     std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1171     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1172         EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1173         EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
1174         EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1175     }
1176 }
1177 
1178 }  // namespace
1179 
TEST_F(NetdBinderTest,StrictSetUidCleartextPenalty)1180 TEST_F(NetdBinderTest, StrictSetUidCleartextPenalty) {
1181     binder::Status status;
1182     int32_t uid = randomUid();
1183 
1184     // setUidCleartextPenalty Policy:Log with randomUid
1185     status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1186     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1187     expectStrictSetUidLog(uid);
1188 
1189     // setUidCleartextPenalty Policy:Accept with randomUid
1190     status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1191     expectStrictSetUidAccept(uid);
1192 
1193     // setUidCleartextPenalty Policy:Reject with randomUid
1194     status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1195     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1196     expectStrictSetUidReject(uid);
1197 
1198     // setUidCleartextPenalty Policy:Accept with randomUid
1199     status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1200     expectStrictSetUidAccept(uid);
1201 
1202     // test wrong policy
1203     int32_t wrongPolicy = -123;
1204     status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1205     EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1206 }
1207 
1208 namespace {
1209 
tryToFindProcesses(const std::string & processName,uint32_t maxTries=1,uint32_t intervalMs=50)1210 std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
1211                                             uint32_t intervalMs = 50) {
1212     // Output looks like:(clatd)
1213     // clat          4963   850 1 12:16:51 ?     00:00:00 clatd-netd10a88 -i netd10a88 ...
1214     // ...
1215     // root          5221  5219 0 12:18:12 ?     00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1216 
1217     // (dnsmasq)
1218     // dns_tether    4620   792 0 16:51:28 ?     00:00:00 dnsmasq --keep-in-foreground ...
1219 
1220     if (maxTries == 0) return {};
1221 
1222     std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
1223     std::vector<std::string> result;
1224     for (uint32_t run = 1;;) {
1225         result = runCommand(cmd);
1226         if (result.size() || ++run > maxTries) {
1227             break;
1228         }
1229 
1230         usleep(intervalMs * 1000);
1231     }
1232     return result;
1233 }
1234 
expectProcessExists(const std::string & processName)1235 void expectProcessExists(const std::string& processName) {
1236     EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
1237 }
1238 
expectProcessDoesNotExist(const std::string & processName)1239 void expectProcessDoesNotExist(const std::string& processName) {
1240     EXPECT_FALSE(tryToFindProcesses(processName).size());
1241 }
1242 
1243 }  // namespace
1244 
TEST_F(NetdBinderTest,ClatdStartStop)1245 TEST_F(NetdBinderTest, ClatdStartStop) {
1246     binder::Status status;
1247 
1248     const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1249     std::string clatAddress;
1250     std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
1251 
1252     // Can't start clatd on an interface that's not part of any network...
1253     status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1254     EXPECT_FALSE(status.isOk());
1255     EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1256 
1257     // ... so create a test physical network and add our tun to it.
1258     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1259     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1260 
1261     // Prefix must be 96 bits long.
1262     status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1263     EXPECT_FALSE(status.isOk());
1264     EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1265 
1266     // Can't start clatd unless there's a default route...
1267     status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1268     EXPECT_FALSE(status.isOk());
1269     EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1270 
1271     // so add a default route.
1272     EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1273 
1274     // Can't start clatd unless there's a global address...
1275     status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1276     EXPECT_FALSE(status.isOk());
1277     EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1278 
1279     // ... so add a global address.
1280     const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
1281     EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
1282 
1283     // Now expect clatd to start successfully.
1284     status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1285     EXPECT_TRUE(status.isOk());
1286     EXPECT_EQ(0, status.serviceSpecificErrorCode());
1287 
1288     // Starting it again returns EBUSY.
1289     status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1290     EXPECT_FALSE(status.isOk());
1291     EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1292 
1293     expectProcessExists(clatdName);
1294 
1295     // Expect clatd to stop successfully.
1296     status = mNetd->clatdStop(sTun.name());
1297     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1298     expectProcessDoesNotExist(clatdName);
1299 
1300     // Stopping a clatd that doesn't exist returns ENODEV.
1301     status = mNetd->clatdStop(sTun.name());
1302     EXPECT_FALSE(status.isOk());
1303     EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1304     expectProcessDoesNotExist(clatdName);
1305 
1306     // Clean up.
1307     EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1308     EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1309     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1310 }
1311 
1312 namespace {
1313 
getIpfwdV4Enable()1314 bool getIpfwdV4Enable() {
1315     static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1316     std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1317     EXPECT_TRUE(!result.empty());
1318     int v4Enable = std::stoi(result[0]);
1319     return v4Enable;
1320 }
1321 
getIpfwdV6Enable()1322 bool getIpfwdV6Enable() {
1323     static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
1324     std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1325     EXPECT_TRUE(!result.empty());
1326     int v6Enable = std::stoi(result[0]);
1327     return v6Enable;
1328 }
1329 
expectIpfwdEnable(bool enable)1330 void expectIpfwdEnable(bool enable) {
1331     int enableIPv4 = getIpfwdV4Enable();
1332     int enableIPv6 = getIpfwdV6Enable();
1333     EXPECT_EQ(enable, enableIPv4);
1334     EXPECT_EQ(enable, enableIPv6);
1335 }
1336 
ipRuleIpfwdExists(const char * ipVersion,const std::string & ipfwdRule)1337 bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
1338     std::vector<std::string> rules = listIpRules(ipVersion);
1339     for (const auto& rule : rules) {
1340         if (rule.find(ipfwdRule) != std::string::npos) {
1341             return true;
1342         }
1343     }
1344     return false;
1345 }
1346 
expectIpfwdRuleExists(const char * fromIf,const char * toIf)1347 void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1348     std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1349 
1350     for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1351         EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1352     }
1353 }
1354 
expectIpfwdRuleNotExists(const char * fromIf,const char * toIf)1355 void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1356     std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1357 
1358     for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1359         EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1360     }
1361 }
1362 
1363 }  // namespace
1364 
TEST_F(NetdBinderTest,TestIpfwdEnableDisableStatusForwarding)1365 TEST_F(NetdBinderTest, TestIpfwdEnableDisableStatusForwarding) {
1366     // Get ipfwd requester list from Netd
1367     std::vector<std::string> requesterList;
1368     binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
1369     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1370 
1371     bool ipfwdEnabled;
1372     if (requesterList.size() == 0) {
1373         // No requester in Netd, ipfwd should be disabled
1374         // So add one test requester and verify
1375         status = mNetd->ipfwdEnableForwarding("TestRequester");
1376         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1377 
1378         expectIpfwdEnable(true);
1379         status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1380         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1381         EXPECT_TRUE(ipfwdEnabled);
1382 
1383         // Remove test one, verify again
1384         status = mNetd->ipfwdDisableForwarding("TestRequester");
1385         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1386 
1387         expectIpfwdEnable(false);
1388         status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1389         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1390         EXPECT_FALSE(ipfwdEnabled);
1391     } else {
1392         // Disable all requesters
1393         for (const auto& requester : requesterList) {
1394             status = mNetd->ipfwdDisableForwarding(requester);
1395             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1396         }
1397 
1398         // After disable all requester, ipfwd should be disabled
1399         expectIpfwdEnable(false);
1400         status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1401         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1402         EXPECT_FALSE(ipfwdEnabled);
1403 
1404         // Enable them back
1405         for (const auto& requester : requesterList) {
1406             status = mNetd->ipfwdEnableForwarding(requester);
1407             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1408         }
1409 
1410         // ipfwd should be enabled
1411         expectIpfwdEnable(true);
1412         status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1413         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1414         EXPECT_TRUE(ipfwdEnabled);
1415     }
1416 }
1417 
TEST_F(NetdBinderTest,TestIpfwdAddRemoveInterfaceForward)1418 TEST_F(NetdBinderTest, TestIpfwdAddRemoveInterfaceForward) {
1419     // Add test physical network
1420     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1421     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1422     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1423     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
1424 
1425     binder::Status status = mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1426     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1427     expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
1428 
1429     status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1430     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1431     expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
1432 }
1433 
1434 namespace {
1435 
1436 constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1437 constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1438 constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1439 constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1440 constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
1441 constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
1442 
1443 // TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1444 //       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)1445 bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1446                            const char* chainName, const std::string& expectedTargetA,
1447                            const std::string& expectedTargetB) {
1448     std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1449     int matchCount = 0;
1450 
1451     for (const auto& rule : rules) {
1452         if (rule.find(expectedTargetA) != std::string::npos) {
1453             if (rule.find(expectedTargetB) != std::string::npos) {
1454                 matchCount++;
1455             }
1456         }
1457     }
1458     return matchCount == expectedCount;
1459 }
1460 
expectXtQuotaValueEqual(const char * ifname,long quotaBytes)1461 void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1462     std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1463     std::string result = "";
1464 
1465     EXPECT_TRUE(ReadFileToString(path, &result));
1466     // Quota value might be decreased while matching packets
1467     EXPECT_GE(quotaBytes, std::stol(Trim(result)));
1468 }
1469 
expectBandwidthInterfaceQuotaRuleExists(const char * ifname,long quotaBytes)1470 void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1471     std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1472     std::string quotaRule = StringPrintf("quota %s", ifname);
1473 
1474     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1475         EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1476                                           BANDWIDTH_COSTLY_IF));
1477         EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1478                                           BANDWIDTH_COSTLY_IF));
1479         EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1480                                           BANDWIDTH_COSTLY_IF));
1481         EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1482         EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1483     }
1484     expectXtQuotaValueEqual(ifname, quotaBytes);
1485 }
1486 
expectBandwidthInterfaceQuotaRuleDoesNotExist(const char * ifname)1487 void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1488     std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1489     std::string quotaRule = StringPrintf("quota %s", ifname);
1490 
1491     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1492         EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1493                                            BANDWIDTH_COSTLY_IF));
1494         EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1495                                            BANDWIDTH_COSTLY_IF));
1496         EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1497                                            BANDWIDTH_COSTLY_IF));
1498         EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1499         EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1500     }
1501 }
1502 
expectBandwidthInterfaceAlertRuleExists(const char * ifname,long alertBytes)1503 void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1504     std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1505     std::string alertRule = StringPrintf("quota %sAlert", ifname);
1506     std::string alertName = StringPrintf("%sAlert", ifname);
1507 
1508     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1509         EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1510     }
1511     expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1512 }
1513 
expectBandwidthInterfaceAlertRuleDoesNotExist(const char * ifname)1514 void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1515     std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1516     std::string alertRule = StringPrintf("quota %sAlert", ifname);
1517 
1518     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1519         EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1520     }
1521 }
1522 
expectBandwidthGlobalAlertRuleExists(long alertBytes)1523 void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1524     static const char globalAlertRule[] = "quota globalAlert";
1525     static const char globalAlertName[] = "globalAlert";
1526 
1527     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1528         EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
1529     }
1530     expectXtQuotaValueEqual(globalAlertName, alertBytes);
1531 }
1532 
expectBandwidthManipulateSpecialAppRuleExists(const char * chain,const char * target,int uid)1533 void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1534     std::string uidRule = StringPrintf("owner UID match %u", uid);
1535 
1536     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1537         EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1538     }
1539 }
1540 
expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char * chain,int uid)1541 void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1542     std::string uidRule = StringPrintf("owner UID match %u", uid);
1543 
1544     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1545         EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1546     }
1547 }
1548 
1549 }  // namespace
1550 
TEST_F(NetdBinderTest,BandwidthSetRemoveInterfaceQuota)1551 TEST_F(NetdBinderTest, BandwidthSetRemoveInterfaceQuota) {
1552     long testQuotaBytes = 5550;
1553 
1554     // Add test physical network
1555     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1556     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1557 
1558     binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1559     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1560     expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1561 
1562     status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1563     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1564     expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1565 
1566     // Remove test physical network
1567     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1568 }
1569 
TEST_F(NetdBinderTest,BandwidthSetRemoveInterfaceAlert)1570 TEST_F(NetdBinderTest, BandwidthSetRemoveInterfaceAlert) {
1571     long testAlertBytes = 373;
1572     // Add test physical network
1573     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1574     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1575     // Need to have a prior interface quota set to set an alert
1576     binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1577     status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1578     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1579     expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1580 
1581     status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1582     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1583     expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1584 
1585     // Remove interface quota
1586     status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1587     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1588     expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1589 
1590     // Remove test physical network
1591     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1592 }
1593 
TEST_F(NetdBinderTest,BandwidthSetGlobalAlert)1594 TEST_F(NetdBinderTest, BandwidthSetGlobalAlert) {
1595     int64_t testAlertBytes = 2097200;
1596 
1597     binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1598     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1599     expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1600 
1601     testAlertBytes = 2098230;
1602     status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1603     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1604     expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1605 }
1606 
TEST_F(NetdBinderTest,BandwidthManipulateSpecialApp)1607 TEST_F(NetdBinderTest, BandwidthManipulateSpecialApp) {
1608     SKIP_IF_BPF_SUPPORTED;
1609 
1610     int32_t uid = randomUid();
1611     static const char targetReject[] = "REJECT";
1612     static const char targetReturn[] = "RETURN";
1613 
1614     // add NaughtyApp
1615     binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1616     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1617     expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1618 
1619     // remove NaughtyApp
1620     status = mNetd->bandwidthRemoveNaughtyApp(uid);
1621     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1622     expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1623 
1624     // add NiceApp
1625     status = mNetd->bandwidthAddNiceApp(uid);
1626     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1627     expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1628 
1629     // remove NiceApp
1630     status = mNetd->bandwidthRemoveNiceApp(uid);
1631     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1632     expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1633 }
1634 
1635 namespace {
1636 
ipRouteString(const std::string & ifName,const std::string & dst,const std::string & nextHop,const std::string & mtu)1637 std::string ipRouteString(const std::string& ifName, const std::string& dst,
1638                           const std::string& nextHop, const std::string& mtu) {
1639     std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1640 
1641     if (!nextHop.empty()) {
1642         dstString += " via " + nextHop;
1643     }
1644 
1645     dstString += " dev " + ifName;
1646 
1647     if (!mtu.empty()) {
1648         dstString += " proto static";
1649         // IPv6 routes report the metric, IPv4 routes report the scope.
1650         // TODO: move away from specifying the entire string and use a regexp instead.
1651         if (dst.find(':') != std::string::npos) {
1652             dstString += " metric 1024";
1653         } else {
1654             if (nextHop.empty()) {
1655                 dstString += " scope link";
1656             }
1657         }
1658         dstString += " mtu " + mtu;
1659     }
1660 
1661     return dstString;
1662 }
1663 
expectNetworkRouteExistsWithMtu(const char * ipVersion,const std::string & ifName,const std::string & dst,const std::string & nextHop,const std::string & mtu,const char * table)1664 void expectNetworkRouteExistsWithMtu(const char* ipVersion, const std::string& ifName,
1665                                      const std::string& dst, const std::string& nextHop,
1666                                      const std::string& mtu, const char* table) {
1667     std::string routeString = ipRouteString(ifName, dst, nextHop, mtu);
1668     EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop, mtu)))
1669             << "Couldn't find route to " << dst << ": '" << routeString << "' in table " << table;
1670 }
1671 
expectNetworkRouteExists(const char * ipVersion,const std::string & ifName,const std::string & dst,const std::string & nextHop,const char * table)1672 void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1673                               const std::string& dst, const std::string& nextHop,
1674                               const char* table) {
1675     expectNetworkRouteExistsWithMtu(ipVersion, ifName, dst, nextHop, "", table);
1676 }
1677 
expectNetworkRouteDoesNotExist(const char * ipVersion,const std::string & ifName,const std::string & dst,const std::string & nextHop,const char * table)1678 void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
1679                                     const std::string& dst, const std::string& nextHop,
1680                                     const char* table) {
1681     std::string routeString = ipRouteString(ifName, dst, nextHop, "");
1682     EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop, "")))
1683             << "Found unexpected route " << routeString << " in table " << table;
1684 }
1685 
ipRuleExists(const char * ipVersion,const std::string & ipRule)1686 bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1687     std::vector<std::string> rules = listIpRules(ipVersion);
1688     for (const auto& rule : rules) {
1689         if (rule.find(ipRule) != std::string::npos) {
1690             return true;
1691         }
1692     }
1693     return false;
1694 }
1695 
expectNetworkDefaultIpRuleExists(const char * ifName)1696 void expectNetworkDefaultIpRuleExists(const char* ifName) {
1697     std::string networkDefaultRule =
1698             StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1699 
1700     for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1701         EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1702     }
1703 }
1704 
expectNetworkDefaultIpRuleDoesNotExist()1705 void expectNetworkDefaultIpRuleDoesNotExist() {
1706     static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1707 
1708     for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1709         EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1710     }
1711 }
1712 
expectNetworkPermissionIpRuleExists(const char * ifName,int permission)1713 void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1714     std::string networkPermissionRule = "";
1715     switch (permission) {
1716         case INetd::PERMISSION_NONE:
1717             networkPermissionRule = StringPrintf(
1718                     "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1719             break;
1720         case INetd::PERMISSION_NETWORK:
1721             networkPermissionRule = StringPrintf(
1722                     "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1723             break;
1724         case INetd::PERMISSION_SYSTEM:
1725             networkPermissionRule = StringPrintf(
1726                     "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1727             break;
1728     }
1729 
1730     for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1731         EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1732     }
1733 }
1734 
1735 // 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)1736 bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1737                                                  const std::string& expectedInterface,
1738                                                  const std::string& expectedRule,
1739                                                  const char* table) {
1740     std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1741     for (const auto& rule : rules) {
1742         if (rule.find(expectedInterface) != std::string::npos) {
1743             if (rule.find(expectedRule) != std::string::npos) {
1744                 return true;
1745             }
1746         }
1747     }
1748     return false;
1749 }
1750 
expectNetworkPermissionIptablesRuleExists(const char * ifName,int permission)1751 void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1752     static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1753     std::string networkIncomingPacketMarkRule = "";
1754     switch (permission) {
1755         case INetd::PERMISSION_NONE:
1756             networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1757             break;
1758         case INetd::PERMISSION_NETWORK:
1759             networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1760             break;
1761         case INetd::PERMISSION_SYSTEM:
1762             networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1763             break;
1764     }
1765 
1766     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1767         EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1768                 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1769     }
1770 }
1771 
1772 }  // namespace
1773 
TEST_F(NetdBinderTest,NetworkAddRemoveRouteUserPermission)1774 TEST_F(NetdBinderTest, NetworkAddRemoveRouteUserPermission) {
1775     static const struct {
1776         const char* ipVersion;
1777         const char* testDest;
1778         const char* testNextHop;
1779         const bool expectSuccess;
1780     } kTestData[] = {
1781             {IP_RULE_V4, "0.0.0.0/0", "", true},
1782             {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1783             {IP_RULE_V4, "10.251.0.0/16", "", true},
1784             {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1785             {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
1786             {IP_RULE_V6, "::/0", "", true},
1787             {IP_RULE_V6, "::/0", "2001:db8::", true},
1788             {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
1789             {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1790     };
1791 
1792     static const struct {
1793         const char* ipVersion;
1794         const char* testDest;
1795         const char* testNextHop;
1796     } kTestDataWithNextHop[] = {
1797             {IP_RULE_V4, "10.251.10.0/30", ""},
1798             {IP_RULE_V6, "2001:db8::/32", ""},
1799     };
1800 
1801     static const char testTableLegacySystem[] = "legacy_system";
1802     static const char testTableLegacyNetwork[] = "legacy_network";
1803     const int testUid = randomUid();
1804     const std::vector<int32_t> testUids = {testUid};
1805 
1806     // Add test physical network
1807     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1808     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1809 
1810     // Setup route for testing nextHop
1811     for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
1812         const auto& td = kTestDataWithNextHop[i];
1813 
1814         // All route for test tun will disappear once the tun interface is deleted.
1815         binder::Status status =
1816                 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1817         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1818         expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1819                                  sTun.name().c_str());
1820 
1821         // Add system permission for test uid, setup route in legacy system table.
1822         EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1823 
1824         status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1825                                               testUid);
1826         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1827         expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1828                                  testTableLegacySystem);
1829 
1830         // Remove system permission for test uid, setup route in legacy network table.
1831         EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1832 
1833         status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1834                                               testUid);
1835         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1836         expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1837                                  testTableLegacyNetwork);
1838     }
1839 
1840     for (size_t i = 0; i < std::size(kTestData); i++) {
1841         const auto& td = kTestData[i];
1842 
1843         binder::Status status =
1844                 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1845         if (td.expectSuccess) {
1846             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1847             expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1848                                      sTun.name().c_str());
1849         } else {
1850             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1851             EXPECT_NE(0, status.serviceSpecificErrorCode());
1852         }
1853 
1854         status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1855         if (td.expectSuccess) {
1856             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1857             expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1858                                            sTun.name().c_str());
1859         } else {
1860             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1861             EXPECT_NE(0, status.serviceSpecificErrorCode());
1862         }
1863 
1864         // Add system permission for test uid, route will be added into legacy system table.
1865         EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1866 
1867         status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1868                                               testUid);
1869         if (td.expectSuccess) {
1870             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1871             expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1872                                      testTableLegacySystem);
1873         } else {
1874             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1875             EXPECT_NE(0, status.serviceSpecificErrorCode());
1876         }
1877 
1878         status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1879                                                  td.testNextHop, testUid);
1880         if (td.expectSuccess) {
1881             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1882             expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1883                                            testTableLegacySystem);
1884         } else {
1885             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1886             EXPECT_NE(0, status.serviceSpecificErrorCode());
1887         }
1888 
1889         // Remove system permission for test uid, route will be added into legacy network table.
1890         EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1891 
1892         status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1893                                               testUid);
1894         if (td.expectSuccess) {
1895             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1896             expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1897                                      testTableLegacyNetwork);
1898         } else {
1899             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1900             EXPECT_NE(0, status.serviceSpecificErrorCode());
1901         }
1902 
1903         status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1904                                                  td.testNextHop, testUid);
1905         if (td.expectSuccess) {
1906             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1907             expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1908                                            testTableLegacyNetwork);
1909         } else {
1910             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1911             EXPECT_NE(0, status.serviceSpecificErrorCode());
1912         }
1913     }
1914 
1915     for (size_t i = 0; i < std::size(kTestData); i++) {
1916         const auto& td = kTestData[i];
1917         int mtu = (i % 2) ? 1480 : 1280;
1918 
1919         android::net::RouteInfoParcel parcel;
1920         parcel.ifName = sTun.name();
1921         parcel.destination = td.testDest;
1922         parcel.nextHop = td.testNextHop;
1923         parcel.mtu = mtu;
1924         binder::Status status = mNetd->networkAddRouteParcel(TEST_NETID1, parcel);
1925         if (td.expectSuccess) {
1926             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1927             expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1928                                             std::to_string(parcel.mtu), sTun.name().c_str());
1929         } else {
1930             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1931             EXPECT_NE(0, status.serviceSpecificErrorCode());
1932         }
1933 
1934         parcel.mtu = 1337;
1935         status = mNetd->networkUpdateRouteParcel(TEST_NETID1, parcel);
1936         if (td.expectSuccess) {
1937             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1938             expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1939                                             std::to_string(parcel.mtu), sTun.name().c_str());
1940         } else {
1941             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1942             EXPECT_NE(0, status.serviceSpecificErrorCode());
1943         }
1944 
1945         status = mNetd->networkRemoveRouteParcel(TEST_NETID1, parcel);
1946         if (td.expectSuccess) {
1947             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1948             expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1949                                            sTun.name().c_str());
1950         } else {
1951             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1952             EXPECT_NE(0, status.serviceSpecificErrorCode());
1953         }
1954     }
1955     // Remove test physical network
1956     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1957 }
1958 
TEST_F(NetdBinderTest,NetworkPermissionDefault)1959 TEST_F(NetdBinderTest, NetworkPermissionDefault) {
1960     // Add test physical network
1961     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1962     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1963 
1964     // Get current default network NetId
1965     binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1966     ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
1967 
1968     // Test SetDefault
1969     status = mNetd->networkSetDefault(TEST_NETID1);
1970     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1971     expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1972 
1973     status = mNetd->networkClearDefault();
1974     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1975     expectNetworkDefaultIpRuleDoesNotExist();
1976 
1977     // Set default network back
1978     status = mNetd->networkSetDefault(mStoredDefaultNetwork);
1979     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1980 
1981     // Test SetPermission
1982     status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1983     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1984     expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1985     expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1986 
1987     status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1988     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1989     expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1990     expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1991 
1992     // Remove test physical network
1993     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1994 }
1995 
TEST_F(NetdBinderTest,NetworkSetProtectAllowDeny)1996 TEST_F(NetdBinderTest, NetworkSetProtectAllowDeny) {
1997     binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
1998     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1999     bool ret = false;
2000     status = mNetd->networkCanProtect(TEST_UID1, &ret);
2001     EXPECT_TRUE(ret);
2002 
2003     status = mNetd->networkSetProtectDeny(TEST_UID1);
2004     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2005 
2006     // Clear uid permission before calling networkCanProtect to ensure
2007     // the call won't be affected by uid permission.
2008     EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
2009 
2010     status = mNetd->networkCanProtect(TEST_UID1, &ret);
2011     EXPECT_FALSE(ret);
2012 }
2013 
2014 namespace {
2015 
readIntFromPath(const std::string & path)2016 int readIntFromPath(const std::string& path) {
2017     std::string result = "";
2018     EXPECT_TRUE(ReadFileToString(path, &result));
2019     return std::stoi(result);
2020 }
2021 
getTetherAcceptIPv6Ra(const std::string & ifName)2022 int getTetherAcceptIPv6Ra(const std::string& ifName) {
2023     std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
2024     return readIntFromPath(path);
2025 }
2026 
getTetherAcceptIPv6Dad(const std::string & ifName)2027 bool getTetherAcceptIPv6Dad(const std::string& ifName) {
2028     std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
2029     return readIntFromPath(path);
2030 }
2031 
getTetherIPv6DadTransmits(const std::string & ifName)2032 int getTetherIPv6DadTransmits(const std::string& ifName) {
2033     std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
2034     return readIntFromPath(path);
2035 }
2036 
getTetherEnableIPv6(const std::string & ifName)2037 bool getTetherEnableIPv6(const std::string& ifName) {
2038     std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2039     int disableIPv6 = readIntFromPath(path);
2040     return !disableIPv6;
2041 }
2042 
interfaceListContains(const std::vector<std::string> & ifList,const std::string & ifName)2043 bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2044     for (const auto& iface : ifList) {
2045         if (iface == ifName) {
2046             return true;
2047         }
2048     }
2049     return false;
2050 }
2051 
expectTetherInterfaceConfigureForIPv6Router(const std::string & ifName)2052 void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2053     EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2054     EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2055     EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2056     EXPECT_TRUE(getTetherEnableIPv6(ifName));
2057 }
2058 
expectTetherInterfaceConfigureForIPv6Client(const std::string & ifName)2059 void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2060     EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2061     EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2062     EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2063     EXPECT_FALSE(getTetherEnableIPv6(ifName));
2064 }
2065 
expectTetherInterfaceExists(const std::vector<std::string> & ifList,const std::string & ifName)2066 void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2067                                  const std::string& ifName) {
2068     EXPECT_TRUE(interfaceListContains(ifList, ifName));
2069 }
2070 
expectTetherInterfaceNotExists(const std::vector<std::string> & ifList,const std::string & ifName)2071 void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2072                                     const std::string& ifName) {
2073     EXPECT_FALSE(interfaceListContains(ifList, ifName));
2074 }
2075 
expectTetherDnsListEquals(const std::vector<std::string> & dnsList,const std::vector<std::string> & testDnsAddrs)2076 void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2077                                const std::vector<std::string>& testDnsAddrs) {
2078     EXPECT_TRUE(dnsList == testDnsAddrs);
2079 }
2080 
2081 }  // namespace
2082 
TEST_F(NetdBinderTest,TetherStartStopStatus)2083 TEST_F(NetdBinderTest, TetherStartStopStatus) {
2084     std::vector<std::string> noDhcpRange = {};
2085     for (bool usingLegacyDnsProxy : {true, false}) {
2086         android::net::TetherConfigParcel config;
2087         config.usingLegacyDnsProxy = usingLegacyDnsProxy;
2088         config.dhcpRanges = noDhcpRange;
2089         binder::Status status = mNetd->tetherStartWithConfiguration(config);
2090         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2091         SCOPED_TRACE(StringPrintf("usingLegacyDnsProxy: %d", usingLegacyDnsProxy));
2092         if (usingLegacyDnsProxy == true) {
2093             expectProcessExists(DNSMASQ);
2094         } else {
2095             expectProcessDoesNotExist(DNSMASQ);
2096         }
2097 
2098         bool tetherEnabled;
2099         status = mNetd->tetherIsEnabled(&tetherEnabled);
2100         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2101         EXPECT_TRUE(tetherEnabled);
2102 
2103         status = mNetd->tetherStop();
2104         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2105         expectProcessDoesNotExist(DNSMASQ);
2106 
2107         status = mNetd->tetherIsEnabled(&tetherEnabled);
2108         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2109         EXPECT_FALSE(tetherEnabled);
2110     }
2111 }
2112 
TEST_F(NetdBinderTest,TetherInterfaceAddRemoveList)2113 TEST_F(NetdBinderTest, TetherInterfaceAddRemoveList) {
2114     // TODO: verify if dnsmasq update interface successfully
2115 
2116     binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2117     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2118     expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2119 
2120     std::vector<std::string> ifList;
2121     status = mNetd->tetherInterfaceList(&ifList);
2122     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2123     expectTetherInterfaceExists(ifList, sTun.name());
2124 
2125     status = mNetd->tetherInterfaceRemove(sTun.name());
2126     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2127     expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2128 
2129     status = mNetd->tetherInterfaceList(&ifList);
2130     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2131     expectTetherInterfaceNotExists(ifList, sTun.name());
2132 }
2133 
TEST_F(NetdBinderTest,TetherDnsSetList)2134 TEST_F(NetdBinderTest, TetherDnsSetList) {
2135     // TODO: verify if dnsmasq update dns successfully
2136     std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2137                                              "fe80::1%" + sTun.name()};
2138 
2139     binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2140     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2141 
2142     std::vector<std::string> dnsList;
2143     status = mNetd->tetherDnsList(&dnsList);
2144     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2145     expectTetherDnsListEquals(dnsList, testDnsAddrs);
2146 }
2147 
2148 namespace {
2149 
findDnsSockets(SockDiag * sd,unsigned numExpected)2150 std::vector<IPAddress> findDnsSockets(SockDiag* sd, unsigned numExpected) {
2151     std::vector<IPAddress> listenAddrs;
2152 
2153     // Callback lambda that finds all IPv4 sockets with source port 53.
2154     auto findDnsSockets = [&](uint8_t /* proto */, const inet_diag_msg* msg) {
2155         // Always return false, which means do not destroy this socket.
2156         if (msg->id.idiag_sport != htons(53)) return false;
2157         IPAddress addr(*(in_addr*)msg->id.idiag_src);
2158         listenAddrs.push_back(addr);
2159         return false;
2160     };
2161 
2162     // There is no way to know if dnsmasq has finished processing the update_interfaces command and
2163     // opened listening sockets. So, just spin a few times and return the first list of sockets
2164     // that is at least numExpected long.
2165     // Pick a relatively large timeout to avoid flaky tests, particularly when running on shared
2166     // devices.
2167     constexpr int kMaxAttempts = 50;
2168     constexpr int kSleepMs = 100;
2169     for (int i = 0; i < kMaxAttempts; i++) {
2170         listenAddrs.clear();
2171         EXPECT_EQ(0, sd->sendDumpRequest(IPPROTO_TCP, AF_INET, 1 << TCP_LISTEN))
2172                 << "Failed to dump sockets, attempt " << i << " of " << kMaxAttempts;
2173         sd->readDiagMsg(IPPROTO_TCP, findDnsSockets);
2174         if (listenAddrs.size() >= numExpected) {
2175             break;
2176         }
2177         usleep(kSleepMs * 1000);
2178     }
2179 
2180     return listenAddrs;
2181 }
2182 
2183 }  // namespace
2184 
2185 // Checks that when starting dnsmasq on an interface that no longer exists, it doesn't attempt to
2186 // start on other interfaces instead.
TEST_F(NetdBinderTest,TetherDeletedInterface)2187 TEST_F(NetdBinderTest, TetherDeletedInterface) {
2188     // Do this first so we don't need to clean up anything else if it fails.
2189     SockDiag sd;
2190     ASSERT_TRUE(sd.open()) << "Failed to open SOCK_DIAG socket";
2191 
2192     // Create our own TunInterfaces (so we can delete them without affecting other tests), and add
2193     // IP addresses to them. They must be IPv4 because tethering an interface disables and
2194     // re-enables IPv6 on the interface, which clears all addresses.
2195     TunInterface tun1, tun2;
2196     ASSERT_EQ(0, tun1.init());
2197     ASSERT_EQ(0, tun2.init());
2198 
2199     // Clean up. It is safe to call TunInterface::destroy multiple times.
2200     auto guard = android::base::make_scope_guard([&] {
2201         tun1.destroy();
2202         tun2.destroy();
2203         mNetd->tetherStop();
2204         mNetd->tetherInterfaceRemove(tun1.name());
2205         mNetd->tetherInterfaceRemove(tun2.name());
2206     });
2207 
2208     IPAddress addr1, addr2;
2209     ASSERT_TRUE(IPAddress::forString("192.0.2.1", &addr1));
2210     ASSERT_TRUE(IPAddress::forString("192.0.2.2", &addr2));
2211     EXPECT_EQ(0, tun1.addAddress(addr1.toString(), 32));
2212     EXPECT_EQ(0, tun2.addAddress(addr2.toString(), 32));
2213 
2214     // Stop tethering.
2215     binder::Status status = mNetd->tetherStop();
2216     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2217 
2218     // Start dnsmasq on an interface that doesn't exist.
2219     // First, tether our tun interface...
2220     status = mNetd->tetherInterfaceAdd(tun1.name());
2221     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2222     expectTetherInterfaceConfigureForIPv6Router(tun1.name());
2223 
2224     // ... then delete it...
2225     tun1.destroy();
2226 
2227     // ... then start dnsmasq.
2228     android::net::TetherConfigParcel config;
2229     config.usingLegacyDnsProxy = true;
2230     config.dhcpRanges = {};
2231     status = mNetd->tetherStartWithConfiguration(config);
2232     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2233 
2234     // Wait for dnsmasq to start.
2235     expectProcessExists(DNSMASQ);
2236 
2237     // Make sure that netd thinks the interface is tethered (even though it doesn't exist).
2238     std::vector<std::string> ifList;
2239     status = mNetd->tetherInterfaceList(&ifList);
2240     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2241     ASSERT_EQ(1U, ifList.size());
2242     EXPECT_EQ(tun1.name(), ifList[0]);
2243 
2244     // Give dnsmasq some time to start up.
2245     usleep(200 * 1000);
2246 
2247     // Check that dnsmasq is not listening on any IP addresses. It shouldn't, because it was only
2248     // told to run on tun1, and tun1 does not exist. Ensure it stays running and doesn't listen on
2249     // any IP addresses.
2250     std::vector<IPAddress> listenAddrs = findDnsSockets(&sd, 0);
2251     EXPECT_EQ(0U, listenAddrs.size()) << "Unexpectedly found IPv4 socket(s) listening on port 53";
2252 
2253     // Now add an interface to dnsmasq and check that we can see the sockets. This confirms that
2254     // findDnsSockets is actually able to see sockets when they exist.
2255     status = mNetd->tetherInterfaceAdd(tun2.name());
2256     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2257 
2258     in_addr loopback = {htonl(INADDR_LOOPBACK)};
2259     listenAddrs = findDnsSockets(&sd, 2);
2260     EXPECT_EQ(2U, listenAddrs.size()) << "Expected exactly 2 IPv4 sockets listening on port 53";
2261     EXPECT_EQ(1, std::count(listenAddrs.begin(), listenAddrs.end(), addr2));
2262     EXPECT_EQ(1, std::count(listenAddrs.begin(), listenAddrs.end(), IPAddress(loopback)));
2263 
2264     // Clean up.
2265     status = mNetd->tetherStop();
2266     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2267 
2268     expectProcessDoesNotExist(DNSMASQ);
2269 
2270     status = mNetd->tetherInterfaceRemove(tun1.name());
2271     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2272 
2273     status = mNetd->tetherInterfaceRemove(tun2.name());
2274     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2275 }
2276 
2277 namespace {
2278 
2279 constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2280 constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2281 constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2282 constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2283 constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2284 constexpr char FIREWALL_STANDBY[] = "fw_standby";
2285 constexpr char targetReturn[] = "RETURN";
2286 constexpr char targetDrop[] = "DROP";
2287 
expectFirewallAllowlistMode()2288 void expectFirewallAllowlistMode() {
2289     static const char dropRule[] = "DROP       all";
2290     static const char rejectRule[] = "REJECT     all";
2291     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2292         EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2293         EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2294         EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2295     }
2296 }
2297 
expectFirewallDenylistMode()2298 void expectFirewallDenylistMode() {
2299     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2300         EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2301         EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2302         EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2303     }
2304 }
2305 
iptablesFirewallInterfaceFirstRuleExists(const char * binary,const char * chainName,const std::string & expectedInterface,const std::string & expectedRule)2306 bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2307                                               const std::string& expectedInterface,
2308                                               const std::string& expectedRule) {
2309     std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2310     // Expected rule:
2311     // Chain fw_INPUT (1 references)
2312     // pkts bytes target     prot opt in     out     source               destination
2313     // 0     0 RETURN     all  --  expectedInterface *       0.0.0.0/0            0.0.0.0/0
2314     // 0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0
2315     int firstRuleIndex = 2;
2316     if (rules.size() < 4) return false;
2317     if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2318         if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2319             return true;
2320         }
2321     }
2322     return false;
2323 }
2324 
2325 // 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)2326 bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2327                                          const std::string& expectedInterface,
2328                                          const std::string& expectedRule) {
2329     std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2330     for (const auto& rule : rules) {
2331         if (rule.find(expectedInterface) != std::string::npos) {
2332             if (rule.find(expectedRule) != std::string::npos) {
2333                 return true;
2334             }
2335         }
2336     }
2337     return false;
2338 }
2339 
expectFirewallInterfaceRuleAllowExists(const std::string & ifname)2340 void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2341     static const char returnRule[] = "RETURN     all";
2342     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2343         EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2344                                                              returnRule));
2345         EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2346                                                              returnRule));
2347     }
2348 }
2349 
expectFireWallInterfaceRuleAllowDoesNotExist(const std::string & ifname)2350 void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2351     static const char returnRule[] = "RETURN     all";
2352     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2353         EXPECT_FALSE(
2354                 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2355         EXPECT_FALSE(
2356                 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2357     }
2358 }
2359 
iptablesFirewallUidFirstRuleExists(const char * binary,const char * chainName,const std::string & expectedTarget,const std::string & expectedRule)2360 bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2361                                         const std::string& expectedTarget,
2362                                         const std::string& expectedRule) {
2363     std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2364     int firstRuleIndex = 2;
2365     if (rules.size() < 4) return false;
2366     if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2367         if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2368             return true;
2369         }
2370     }
2371     return false;
2372 }
2373 
iptablesFirewallUidLastRuleExists(const char * binary,const char * chainName,const std::string & expectedTarget,const std::string & expectedRule)2374 bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2375                                        const std::string& expectedTarget,
2376                                        const std::string& expectedRule) {
2377     std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2378     int lastRuleIndex = rules.size() - 1;
2379     if (lastRuleIndex < 0) return false;
2380     if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2381         if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2382             return true;
2383         }
2384     }
2385     return false;
2386 }
2387 
expectFirewallUidFirstRuleExists(const char * chainName,int32_t uid)2388 void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2389     std::string uidRule = StringPrintf("owner UID match %u", uid);
2390     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2391         EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2392 }
2393 
expectFirewallUidFirstRuleDoesNotExist(const char * chainName,int32_t uid)2394 void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2395     std::string uidRule = StringPrintf("owner UID match %u", uid);
2396     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2397         EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2398 }
2399 
expectFirewallUidLastRuleExists(const char * chainName,int32_t uid)2400 void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2401     std::string uidRule = StringPrintf("owner UID match %u", uid);
2402     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2403         EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2404 }
2405 
expectFirewallUidLastRuleDoesNotExist(const char * chainName,int32_t uid)2406 void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2407     std::string uidRule = StringPrintf("owner UID match %u", uid);
2408     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2409         EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2410 }
2411 
iptablesFirewallChildChainsLastRuleExists(const char * binary,const char * chainName)2412 bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2413     std::vector<std::string> inputRules =
2414             listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2415     std::vector<std::string> outputRules =
2416             listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2417     int inputLastRuleIndex = inputRules.size() - 1;
2418     int outputLastRuleIndex = outputRules.size() - 1;
2419 
2420     if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2421     if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2422         if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2423             return true;
2424         }
2425     }
2426     return false;
2427 }
2428 
expectFirewallChildChainsLastRuleExists(const char * chainRule)2429 void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2430     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2431         EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2432 }
2433 
expectFirewallChildChainsLastRuleDoesNotExist(const char * chainRule)2434 void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2435     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2436         EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2437         EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2438     }
2439 }
2440 
2441 }  // namespace
2442 
TEST_F(NetdBinderTest,FirewallSetFirewallType)2443 TEST_F(NetdBinderTest, FirewallSetFirewallType) {
2444     binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2445     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2446     expectFirewallAllowlistMode();
2447 
2448     status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2449     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2450     expectFirewallDenylistMode();
2451 
2452     // set firewall type blacklist twice
2453     mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2454     status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2455     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2456     expectFirewallDenylistMode();
2457 
2458     // set firewall type whitelist twice
2459     mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2460     status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2461     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2462     expectFirewallAllowlistMode();
2463 
2464     // reset firewall type to default
2465     status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2466     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2467     expectFirewallDenylistMode();
2468 }
2469 
TEST_F(NetdBinderTest,FirewallSetInterfaceRule)2470 TEST_F(NetdBinderTest, FirewallSetInterfaceRule) {
2471     // setinterfaceRule is not supported in BLACKLIST MODE
2472     binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2473     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2474 
2475     status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2476     EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2477 
2478     // set WHITELIST mode first
2479     status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2480     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2481 
2482     status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2483     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2484     expectFirewallInterfaceRuleAllowExists(sTun.name());
2485 
2486     status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2487     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2488     expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2489 
2490     // reset firewall mode to default
2491     status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2492     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2493     expectFirewallDenylistMode();
2494 }
2495 
TEST_F(NetdBinderTest,FirewallSetUidRule)2496 TEST_F(NetdBinderTest, FirewallSetUidRule) {
2497     SKIP_IF_BPF_SUPPORTED;
2498 
2499     int32_t uid = randomUid();
2500 
2501     // Doze allow
2502     binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2503                                                       INetd::FIREWALL_RULE_ALLOW);
2504     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2505     expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2506 
2507     // Doze deny
2508     status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2509                                        INetd::FIREWALL_RULE_DENY);
2510     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2511     expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2512 
2513     // Powersave allow
2514     status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2515                                        INetd::FIREWALL_RULE_ALLOW);
2516     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2517     expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2518 
2519     // Powersave deny
2520     status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2521                                        INetd::FIREWALL_RULE_DENY);
2522     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2523     expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2524 
2525     // Standby deny
2526     status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2527                                        INetd::FIREWALL_RULE_DENY);
2528     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2529     expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2530 
2531     // Standby allow
2532     status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2533                                        INetd::FIREWALL_RULE_ALLOW);
2534     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2535     expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2536 
2537     // None deny in BLACKLIST
2538     status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2539     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2540     expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2541     expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2542 
2543     // None allow in BLACKLIST
2544     status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2545     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2546     expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2547     expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2548 
2549     // set firewall type whitelist twice
2550     status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2551     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2552     expectFirewallAllowlistMode();
2553 
2554     // None allow in WHITELIST
2555     status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2556     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2557     expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2558     expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2559 
2560     // None deny in WHITELIST
2561     status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2562     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2563     expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2564     expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2565 
2566     // reset firewall mode to default
2567     status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2568     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2569     expectFirewallDenylistMode();
2570 }
2571 
TEST_F(NetdBinderTest,FirewallEnableDisableChildChains)2572 TEST_F(NetdBinderTest, FirewallEnableDisableChildChains) {
2573     SKIP_IF_BPF_SUPPORTED;
2574 
2575     binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2576     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2577     expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2578 
2579     status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2580     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2581     expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2582 
2583     status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2584     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2585     expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2586 
2587     status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2588     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2589     expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2590 
2591     status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2592     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2593     expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2594 
2595     status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2596     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2597     expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2598 }
2599 
2600 namespace {
2601 
hwAddrToStr(unsigned char * hwaddr)2602 std::string hwAddrToStr(unsigned char* hwaddr) {
2603     return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2604                         hwaddr[4], hwaddr[5]);
2605 }
2606 
ipv4NetmaskToPrefixLength(in_addr_t mask)2607 int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2608     int prefixLength = 0;
2609     uint32_t m = ntohl(mask);
2610     while (m & (1 << 31)) {
2611         prefixLength++;
2612         m = m << 1;
2613     }
2614     return prefixLength;
2615 }
2616 
toStdString(const String16 & s)2617 std::string toStdString(const String16& s) {
2618     return std::string(String8(s.string()));
2619 }
2620 
ioctlByIfName(const std::string & ifName,unsigned long flag)2621 android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2622     const auto& sys = sSyscalls.get();
2623     auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2624     EXPECT_TRUE(isOk(fd.status()));
2625 
2626     struct ifreq ifr = {};
2627     strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2628 
2629     return sys.ioctl(fd.value(), flag, &ifr);
2630 }
2631 
getInterfaceHwAddr(const std::string & ifName)2632 std::string getInterfaceHwAddr(const std::string& ifName) {
2633     auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2634 
2635     unsigned char hwaddr[ETH_ALEN] = {};
2636     if (isOk(res.status())) {
2637         memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2638     }
2639 
2640     return hwAddrToStr(hwaddr);
2641 }
2642 
getInterfaceIPv4Prefix(const std::string & ifName)2643 int getInterfaceIPv4Prefix(const std::string& ifName) {
2644     auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2645 
2646     int prefixLength = 0;
2647     if (isOk(res.status())) {
2648         prefixLength = ipv4NetmaskToPrefixLength(
2649                 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2650     }
2651 
2652     return prefixLength;
2653 }
2654 
getInterfaceIPv4Addr(const std::string & ifName)2655 std::string getInterfaceIPv4Addr(const std::string& ifName) {
2656     auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2657 
2658     struct in_addr addr = {};
2659     if (isOk(res.status())) {
2660         addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2661     }
2662 
2663     return std::string(inet_ntoa(addr));
2664 }
2665 
getInterfaceFlags(const std::string & ifName)2666 std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2667     auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2668 
2669     unsigned flags = 0;
2670     if (isOk(res.status())) {
2671         flags = res.value().ifr_flags;
2672     }
2673 
2674     std::vector<std::string> ifFlags;
2675     ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2676                                      : toStdString(INetd::IF_STATE_DOWN()));
2677 
2678     if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2679     if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2680     if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2681     if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2682     if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2683 
2684     return ifFlags;
2685 }
2686 
compareListInterface(const std::vector<std::string> & interfaceList)2687 bool compareListInterface(const std::vector<std::string>& interfaceList) {
2688     const auto& res = InterfaceController::getIfaceNames();
2689     EXPECT_TRUE(isOk(res));
2690 
2691     std::vector<std::string> resIfList;
2692     resIfList.reserve(res.value().size());
2693     resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2694 
2695     return resIfList == interfaceList;
2696 }
2697 
getInterfaceIPv6PrivacyExtensions(const std::string & ifName)2698 int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2699     std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2700     return readIntFromPath(path);
2701 }
2702 
getInterfaceEnableIPv6(const std::string & ifName)2703 bool getInterfaceEnableIPv6(const std::string& ifName) {
2704     std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2705 
2706     int disableIPv6 = readIntFromPath(path);
2707     return !disableIPv6;
2708 }
2709 
getInterfaceMtu(const std::string & ifName)2710 int getInterfaceMtu(const std::string& ifName) {
2711     std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2712     return readIntFromPath(path);
2713 }
2714 
expectInterfaceList(const std::vector<std::string> & interfaceList)2715 void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2716     EXPECT_TRUE(compareListInterface(interfaceList));
2717 }
2718 
expectCurrentInterfaceConfigurationEquals(const std::string & ifName,const InterfaceConfigurationParcel & interfaceCfg)2719 void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2720                                                const InterfaceConfigurationParcel& interfaceCfg) {
2721     EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2722     EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2723     EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2724     EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2725 }
2726 
expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel & setCfg)2727 void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2728     EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2729     EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2730 
2731     const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2732     for (const auto& flag : setCfg.flags) {
2733         EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2734     }
2735 }
2736 
expectInterfaceIPv6PrivacyExtensions(const std::string & ifName,bool enable)2737 void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2738     int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2739     EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2740 }
2741 
expectInterfaceNoAddr(const std::string & ifName)2742 void expectInterfaceNoAddr(const std::string& ifName) {
2743     // noAddr
2744     EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2745     // noPrefix
2746     EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2747 }
2748 
expectInterfaceEnableIPv6(const std::string & ifName,bool enable)2749 void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2750     int enableIPv6 = getInterfaceEnableIPv6(ifName);
2751     EXPECT_EQ(enableIPv6, enable);
2752 }
2753 
expectInterfaceMtu(const std::string & ifName,const int mtu)2754 void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2755     int mtuSize = getInterfaceMtu(ifName);
2756     EXPECT_EQ(mtu, mtuSize);
2757 }
2758 
makeInterfaceCfgParcel(const std::string & ifName,const std::string & addr,int prefixLength,const std::vector<std::string> & flags)2759 InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2760                                                     const std::string& addr, int prefixLength,
2761                                                     const std::vector<std::string>& flags) {
2762     InterfaceConfigurationParcel cfg;
2763     cfg.ifName = ifName;
2764     cfg.hwAddr = "";
2765     cfg.ipv4Addr = addr;
2766     cfg.prefixLength = prefixLength;
2767     cfg.flags = flags;
2768     return cfg;
2769 }
2770 
expectTunFlags(const InterfaceConfigurationParcel & interfaceCfg)2771 void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2772     std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2773     std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2774 
2775     for (const auto& flag : expectedFlags) {
2776         EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2777                     interfaceCfg.flags.end());
2778     }
2779 
2780     for (const auto& flag : unexpectedFlags) {
2781         EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2782                     interfaceCfg.flags.end());
2783     }
2784 }
2785 
2786 }  // namespace
2787 
TEST_F(NetdBinderTest,InterfaceList)2788 TEST_F(NetdBinderTest, InterfaceList) {
2789     std::vector<std::string> interfaceListResult;
2790 
2791     binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2792     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2793     expectInterfaceList(interfaceListResult);
2794 }
2795 
TEST_F(NetdBinderTest,InterfaceGetCfg)2796 TEST_F(NetdBinderTest, InterfaceGetCfg) {
2797     InterfaceConfigurationParcel interfaceCfgResult;
2798 
2799     // Add test physical network
2800     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2801     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2802 
2803     binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2804     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2805     expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2806     expectTunFlags(interfaceCfgResult);
2807 
2808     // Remove test physical network
2809     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2810 }
2811 
TEST_F(NetdBinderTest,InterfaceSetCfg)2812 TEST_F(NetdBinderTest, InterfaceSetCfg) {
2813     const std::string testAddr = "192.0.2.3";
2814     const int testPrefixLength = 24;
2815     std::vector<std::string> upFlags = {"up"};
2816     std::vector<std::string> downFlags = {"down"};
2817 
2818     // Add test physical network
2819     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2820     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2821 
2822     // Set tun interface down.
2823     auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2824     binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2825     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2826     expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2827 
2828     // Set tun interface up again.
2829     interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2830     status = mNetd->interfaceSetCfg(interfaceCfg);
2831     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2832     status = mNetd->interfaceClearAddrs(sTun.name());
2833     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2834 
2835     // Remove test physical network
2836     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2837 }
2838 
TEST_F(NetdBinderTest,InterfaceSetIPv6PrivacyExtensions)2839 TEST_F(NetdBinderTest, InterfaceSetIPv6PrivacyExtensions) {
2840     // enable
2841     binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2842     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2843     expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2844 
2845     // disable
2846     status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2847     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2848     expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2849 }
2850 
TEST_F(NetdBinderTest,InterfaceClearAddr)2851 TEST_F(NetdBinderTest, InterfaceClearAddr) {
2852     const std::string testAddr = "192.0.2.3";
2853     const int testPrefixLength = 24;
2854     std::vector<std::string> noFlags{};
2855 
2856     // Add test physical network
2857     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2858     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2859 
2860     auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2861     binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2862     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2863     expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2864 
2865     status = mNetd->interfaceClearAddrs(sTun.name());
2866     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2867     expectInterfaceNoAddr(sTun.name());
2868 
2869     // Remove test physical network
2870     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2871 }
2872 
TEST_F(NetdBinderTest,InterfaceSetEnableIPv6)2873 TEST_F(NetdBinderTest, InterfaceSetEnableIPv6) {
2874     // Add test physical network
2875     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2876     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2877 
2878     // disable
2879     binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2880     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2881     expectInterfaceEnableIPv6(sTun.name(), false);
2882 
2883     // enable
2884     status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2885     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2886     expectInterfaceEnableIPv6(sTun.name(), true);
2887 
2888     // Remove test physical network
2889     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2890 }
2891 
TEST_F(NetdBinderTest,InterfaceSetMtu)2892 TEST_F(NetdBinderTest, InterfaceSetMtu) {
2893     const int testMtu = 1200;
2894 
2895     // Add test physical network
2896     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2897     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2898 
2899     binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2900     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2901     expectInterfaceMtu(sTun.name(), testMtu);
2902 
2903     // Remove test physical network
2904     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2905 }
2906 
2907 namespace {
2908 
2909 constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2910 constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
2911 constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
2912 constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2913 
iptablesCountRules(const char * binary,const char * table,const char * chainName)2914 int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
2915     return listIptablesRuleByTable(binary, table, chainName).size();
2916 }
2917 
iptablesChainMatch(const char * binary,const char * table,const char * chainName,const std::vector<std::string> & targetVec)2918 bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2919                         const std::vector<std::string>& targetVec) {
2920     std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2921     if (targetVec.size() != rules.size() - 2) {
2922         return false;
2923     }
2924 
2925     /*
2926      * Check that the rules match. Note that this function matches substrings, not entire rules,
2927      * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
2928      * Skip first two lines since rules start from third line.
2929      * Chain chainName (x references)
2930      * pkts bytes target     prot opt in     out     source               destination
2931      * ...
2932      */
2933     int rIndex = 2;
2934     for (const auto& target : targetVec) {
2935         if (rules[rIndex].find(target) == std::string::npos) {
2936             return false;
2937         }
2938         rIndex++;
2939     }
2940     return true;
2941 }
2942 
expectNatEnable(const std::string & intIf,const std::string & extIf)2943 void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2944     std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2945     std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2946     std::vector<std::string> forwardV4Match = {
2947             "bw_global_alert", "state RELATED", "state INVALID",
2948             StringPrintf("tetherctrl_counters  all  --  %s %s", intIf.c_str(), extIf.c_str()),
2949             "DROP"};
2950 
2951     // V4
2952     EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2953                                    postroutingV4Match));
2954     EXPECT_TRUE(
2955             iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
2956     EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2957 
2958     std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
2959     std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2960 
2961     // V6
2962     EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
2963     EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2964                                    preroutingV6Match));
2965 
2966     for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2967         EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2968                                           extIf));
2969     }
2970 }
2971 
expectNatDisable()2972 void expectNatDisable() {
2973     // It is the default DROP rule with tethering disable.
2974     // Chain tetherctrl_FORWARD (1 references)
2975     // pkts bytes target     prot opt in     out     source               destination
2976     //    0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0
2977     std::vector<std::string> forwardV4Match = {"DROP"};
2978     EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2979 
2980     // We expect that these chains should be empty.
2981     EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2982     EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
2983 
2984     EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2985     EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
2986 
2987     // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2988 }
2989 
2990 }  // namespace
2991 
TEST_F(NetdBinderTest,TetherForwardAddRemove)2992 TEST_F(NetdBinderTest, TetherForwardAddRemove) {
2993     binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2994     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2995     expectNatEnable(sTun.name(), sTun2.name());
2996 
2997     status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2998     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2999     expectNatDisable();
3000 }
3001 
3002 namespace {
3003 
3004 using TripleInt = std::array<int, 3>;
3005 
readProcFileToTripleInt(const std::string & path)3006 TripleInt readProcFileToTripleInt(const std::string& path) {
3007     std::string valueString;
3008     int min, def, max;
3009     EXPECT_TRUE(ReadFileToString(path, &valueString));
3010     EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
3011     return {min, def, max};
3012 }
3013 
updateAndCheckTcpBuffer(sp<INetd> & netd,TripleInt & rmemValues,TripleInt & wmemValues)3014 void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
3015     std::string testRmemValues =
3016             StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
3017     std::string testWmemValues =
3018             StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
3019     EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
3020 
3021     TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
3022     TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
3023 
3024     for (int i = 0; i < 3; i++) {
3025         SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
3026         EXPECT_EQ(rmemValues[i], newRmemValues[i]);
3027         EXPECT_EQ(wmemValues[i], newWmemValues[i]);
3028     }
3029 }
3030 
3031 }  // namespace
3032 
TEST_F(NetdBinderTest,TcpBufferSet)3033 TEST_F(NetdBinderTest, TcpBufferSet) {
3034     TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
3035     TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
3036     TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
3037     TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
3038 
3039     updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
3040     updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
3041 }
3042 
3043 namespace {
3044 
checkUidsInPermissionMap(std::vector<int32_t> & uids,bool exist)3045 void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
3046     android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(UID_PERMISSION_MAP_PATH);
3047     for (int32_t uid : uids) {
3048         android::base::Result<uint8_t> permission = uidPermissionMap.readValue(uid);
3049         if (exist) {
3050             ASSERT_RESULT_OK(permission);
3051             EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
3052         } else {
3053             ASSERT_FALSE(permission.ok());
3054             EXPECT_EQ(ENOENT, permission.error().code());
3055         }
3056     }
3057 }
3058 
3059 }  // namespace
3060 
TEST_F(NetdBinderTest,TestInternetPermission)3061 TEST_F(NetdBinderTest, TestInternetPermission) {
3062     SKIP_IF_BPF_NOT_SUPPORTED;
3063 
3064     std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
3065 
3066     mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
3067     checkUidsInPermissionMap(appUids, false);
3068     mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
3069     checkUidsInPermissionMap(appUids, true);
3070     mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
3071     checkUidsInPermissionMap(appUids, false);
3072 }
3073 
TEST_F(NetdBinderTest,UnsolEvents)3074 TEST_F(NetdBinderTest, UnsolEvents) {
3075     auto testUnsolService = android::net::TestUnsolService::start();
3076     std::string oldTunName = sTun.name();
3077     std::string newTunName = "unsolTest";
3078     testUnsolService->tarVec.push_back(oldTunName);
3079     testUnsolService->tarVec.push_back(newTunName);
3080     auto& cv = testUnsolService->getCv();
3081     auto& cvMutex = testUnsolService->getCvMutex();
3082     binder::Status status = mNetd->registerUnsolicitedEventListener(
3083             android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
3084     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3085 
3086     // TODO: Add test for below events
3087     //       StrictCleartextDetected / InterfaceDnsServersAdded
3088     //       InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
3089 
3090     {
3091         std::unique_lock lock(cvMutex);
3092 
3093         // Re-init test Tun, and we expect that we will get some unsol events.
3094         // Use the test Tun device name to verify if we receive its unsol events.
3095         sTun.destroy();
3096         // Use predefined name
3097         sTun.init(newTunName);
3098 
3099         EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3100     }
3101 
3102     // bit mask 1101101000
3103     // Test only covers below events currently
3104     const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
3105                                      InterfaceLinkStatusChanged | RouteChanged;
3106     EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
3107 
3108     // Re-init sTun to clear predefined name
3109     sTun.destroy();
3110     sTun.init();
3111 }
3112 
TEST_F(NetdBinderTest,NDC)3113 TEST_F(NetdBinderTest, NDC) {
3114     struct Command {
3115         const std::string cmdString;
3116         const std::string expectedResult;
3117     };
3118 
3119     // clang-format off
3120     // Do not change the commands order
3121     const Command networkCmds[] = {
3122             {StringPrintf("ndc network create %d", TEST_NETID1),
3123              "200 0 success"},
3124             {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
3125              "200 0 success"},
3126             {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
3127              "200 0 success"},
3128             {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
3129              "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
3130             {StringPrintf("ndc network destroy %d", TEST_NETID1),
3131              "200 0 success"},
3132     };
3133 
3134     const std::vector<Command> ipfwdCmds = {
3135             {"ndc ipfwd enable " + sTun.name(),
3136              "200 0 ipfwd operation succeeded"},
3137             {"ndc ipfwd disable " + sTun.name(),
3138              "200 0 ipfwd operation succeeded"},
3139             {"ndc ipfwd add lo2 lo3",
3140              "400 0 ipfwd operation failed (No such process)"},
3141             {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
3142              "200 0 ipfwd operation succeeded"},
3143             {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
3144              "200 0 ipfwd operation succeeded"},
3145     };
3146 
3147     static const struct {
3148         const char* ipVersion;
3149         const char* testDest;
3150         const char* testNextHop;
3151         const bool expectSuccess;
3152         const std::string expectedResult;
3153     } kTestData[] = {
3154             {IP_RULE_V4, "0.0.0.0/0",          "",            true,
3155              "200 0 success"},
3156             {IP_RULE_V4, "10.251.0.0/16",      "",            true,
3157              "200 0 success"},
3158             {IP_RULE_V4, "10.251.0.0/16",      "fe80::/64",   false,
3159              "400 0 addRoute() failed (Invalid argument)",},
3160             {IP_RULE_V6, "::/0",               "",            true,
3161              "200 0 success"},
3162             {IP_RULE_V6, "2001:db8:cafe::/64", "",            true,
3163              "200 0 success"},
3164             {IP_RULE_V6, "fe80::/64",          "0.0.0.0",     false,
3165              "400 0 addRoute() failed (Invalid argument)"},
3166     };
3167     // clang-format on
3168 
3169     for (const auto& cmd : networkCmds) {
3170         const std::vector<std::string> result = runCommand(cmd.cmdString);
3171         SCOPED_TRACE(cmd.cmdString);
3172         EXPECT_EQ(result.size(), 1U);
3173         EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3174     }
3175 
3176     for (const auto& cmd : ipfwdCmds) {
3177         const std::vector<std::string> result = runCommand(cmd.cmdString);
3178         SCOPED_TRACE(cmd.cmdString);
3179         EXPECT_EQ(result.size(), 1U);
3180         EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3181     }
3182 
3183     // Add test physical network
3184     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3185     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3186 
3187     for (const auto& td : kTestData) {
3188         const std::string routeAddCmd =
3189                 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
3190                              td.testDest, td.testNextHop);
3191         const std::string routeRemoveCmd =
3192                 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
3193                              sTun.name().c_str(), td.testDest, td.testNextHop);
3194         std::vector<std::string> result = runCommand(routeAddCmd);
3195         SCOPED_TRACE(routeAddCmd);
3196         EXPECT_EQ(result.size(), 1U);
3197         EXPECT_EQ(td.expectedResult, Trim(result[0]));
3198         if (td.expectSuccess) {
3199             expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3200                                      sTun.name().c_str());
3201             result = runCommand(routeRemoveCmd);
3202             EXPECT_EQ(result.size(), 1U);
3203             EXPECT_EQ(td.expectedResult, Trim(result[0]));
3204             expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3205                                            sTun.name().c_str());
3206         }
3207     }
3208     // Remove test physical network
3209     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
3210 }
3211 
TEST_F(NetdBinderTest,OemNetdRelated)3212 TEST_F(NetdBinderTest, OemNetdRelated) {
3213     sp<IBinder> binder;
3214     binder::Status status = mNetd->getOemNetd(&binder);
3215     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3216     sp<com::android::internal::net::IOemNetd> oemNetd;
3217     if (binder != nullptr) {
3218         oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3219     }
3220     ASSERT_NE(nullptr, oemNetd.get());
3221 
3222     TimedOperation t("OemNetd isAlive RPC");
3223     bool isAlive = false;
3224     oemNetd->isAlive(&isAlive);
3225     ASSERT_TRUE(isAlive);
3226 
3227     class TestOemUnsolListener
3228         : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3229       public:
3230         android::binder::Status onRegistered() override {
3231             std::lock_guard lock(mCvMutex);
3232             mCv.notify_one();
3233             return android::binder::Status::ok();
3234         }
3235         std::condition_variable& getCv() { return mCv; }
3236         std::mutex& getCvMutex() { return mCvMutex; }
3237 
3238       private:
3239         std::mutex mCvMutex;
3240         std::condition_variable mCv;
3241     };
3242 
3243     // Start the Binder thread pool.
3244     android::ProcessState::self()->startThreadPool();
3245 
3246     android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3247 
3248     auto& cv = testListener->getCv();
3249     auto& cvMutex = testListener->getCvMutex();
3250 
3251     {
3252         std::unique_lock lock(cvMutex);
3253 
3254         status = oemNetd->registerOemUnsolicitedEventListener(
3255                 ::android::interface_cast<
3256                         com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3257                         testListener));
3258         EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3259 
3260         // Wait for receiving expected events.
3261         EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3262     }
3263 }
3264 
createVpnNetworkWithUid(bool secure,uid_t uid,int vpnNetId,int fallthroughNetId)3265 void NetdBinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3266                                              int fallthroughNetId) {
3267     // Re-init sTun* to ensure route rule exists.
3268     sTun.destroy();
3269     sTun.init();
3270     sTun2.destroy();
3271     sTun2.init();
3272 
3273     // Create physical network with fallthroughNetId but not set it as default network
3274     EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3275     EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3276 
3277     // Create VPN with vpnNetId
3278     EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3279 
3280     // Add uid to VPN
3281     EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3282     EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3283 
3284     // Add default route to fallthroughNetwork
3285     EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3286     // Add limited route
3287     EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3288 }
3289 
3290 namespace {
3291 
3292 class ScopedUidChange {
3293   public:
ScopedUidChange(uid_t uid)3294     explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3295         mStoredUid = getuid();
3296         if (mInputUid == mStoredUid) return;
3297         EXPECT_TRUE(seteuid(uid) == 0);
3298     }
~ScopedUidChange()3299     ~ScopedUidChange() {
3300         if (mInputUid == mStoredUid) return;
3301         EXPECT_TRUE(seteuid(mStoredUid) == 0);
3302     }
3303 
3304   private:
3305     uid_t mInputUid;
3306     uid_t mStoredUid;
3307 };
3308 
3309 constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3310 
clearQueue(int tunFd)3311 void clearQueue(int tunFd) {
3312     char buf[4096];
3313     int ret;
3314     do {
3315         ret = read(tunFd, buf, sizeof(buf));
3316     } while (ret > 0);
3317 }
3318 
checkDataReceived(int udpSocket,int tunFd)3319 void checkDataReceived(int udpSocket, int tunFd) {
3320     char buf[4096] = {};
3321     // Clear tunFd's queue before write something because there might be some
3322     // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3323     clearQueue(tunFd);
3324     EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3325     // TODO: extract header and verify data
3326     EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3327 }
3328 
sendIPv6PacketFromUid(uid_t uid,const in6_addr & dstAddr,Fwmark * fwmark,int tunFd)3329 bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3330     ScopedUidChange scopedUidChange(uid);
3331     unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
3332     if (testSocket < 0) return false;
3333 
3334     const sockaddr_in6 dst6 = {
3335             .sin6_family = AF_INET6,
3336             .sin6_port = 42,
3337             .sin6_addr = dstAddr,
3338     };
3339     int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3340     socklen_t fwmarkLen = sizeof(fwmark->intValue);
3341     EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3342     if (res == -1) return false;
3343 
3344     char addr[INET6_ADDRSTRLEN];
3345     inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3346     SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3347     checkDataReceived(testSocket, tunFd);
3348     return true;
3349 }
3350 
expectVpnFallthroughRuleExists(const std::string & ifName,int vpnNetId)3351 void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3352     std::string vpnFallthroughRule =
3353             StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3354                          RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3355     for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3356         EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3357     }
3358 }
3359 
expectVpnFallthroughWorks(android::net::INetd * netdService,bool bypassable,uid_t uid,const TunInterface & fallthroughNetwork,const TunInterface & vpnNetwork,int vpnNetId=TEST_NETID2,int fallthroughNetId=TEST_NETID1)3360 void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3361                                const TunInterface& fallthroughNetwork,
3362                                const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3363                                int fallthroughNetId = TEST_NETID1) {
3364     // Set default network to NETID_UNSET
3365     EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3366 
3367     // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3368     in6_addr insideVpnAddr = {
3369             {// 2001:db8:cafe::1
3370              .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3371     // outsideVpnAddr will hit the route in the fallthrough network route table
3372     // because we added default route in createVpnNetworkWithUid
3373     in6_addr outsideVpnAddr = {
3374             {// 2607:f0d0:1002::4
3375              .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3376 
3377     int fallthroughFd = fallthroughNetwork.getFdForTesting();
3378     int vpnFd = vpnNetwork.getFdForTesting();
3379     // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3380     // default network.
3381     Fwmark fwmark;
3382     EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3383     EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3384 
3385     // Set default network
3386     EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3387 
3388     // Connections go on the default network because UID 0 is not subject to the VPN.
3389     EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3390     EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3391     EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3392     EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3393 
3394     // Check if fallthrough rule exists
3395     expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3396 
3397     // Expect fallthrough to default network
3398     // The fwmark differs depending on whether the VPN is bypassable or not.
3399     EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3400     EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3401 
3402     // Expect connect success, packet will be sent to vpnFd.
3403     EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3404     EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3405 
3406     // Explicitly select vpn network
3407     setNetworkForProcess(vpnNetId);
3408 
3409     // Expect fallthrough to default network
3410     EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3411     // Expect the mark contains all the bit because we've selected network.
3412     EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3413 
3414     // Expect connect success, packet will be sent to vpnFd.
3415     EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3416     // Expect the mark contains all the bit because we've selected network.
3417     EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3418 
3419     // Explicitly select fallthrough network
3420     setNetworkForProcess(fallthroughNetId);
3421 
3422     // The mark is set to fallthrough network because we've selected it.
3423     EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3424     EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3425 
3426     // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3427     if (bypassable) {
3428         EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3429         EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3430     } else {
3431         // If not, no permission to bypass vpn.
3432         EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3433         EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3434     }
3435 }
3436 
3437 }  // namespace
3438 
TEST_F(NetdBinderTest,SecureVPNFallthrough)3439 TEST_F(NetdBinderTest, SecureVPNFallthrough) {
3440     createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3441     // Get current default network NetId
3442     ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3443     expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3444 }
3445 
TEST_F(NetdBinderTest,BypassableVPNFallthrough)3446 TEST_F(NetdBinderTest, BypassableVPNFallthrough) {
3447     createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3448     // Get current default network NetId
3449     ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3450     expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
3451 }
3452 
3453 namespace {
3454 
createIpv6SocketAndCheckMark(int type,const in6_addr & dstAddr)3455 int32_t createIpv6SocketAndCheckMark(int type, const in6_addr& dstAddr) {
3456     const sockaddr_in6 dst6 = {
3457             .sin6_family = AF_INET6,
3458             .sin6_port = 1234,
3459             .sin6_addr = dstAddr,
3460     };
3461     // create non-blocking socket.
3462     int sockFd = socket(AF_INET6, type | SOCK_NONBLOCK, 0);
3463     EXPECT_NE(-1, sockFd);
3464     EXPECT_EQ((type == SOCK_STREAM) ? -1 : 0, connect(sockFd, (sockaddr*)&dst6, sizeof(dst6)));
3465 
3466     // Get socket fwmark.
3467     Fwmark fwmark;
3468     socklen_t fwmarkLen = sizeof(fwmark.intValue);
3469     EXPECT_EQ(0, getsockopt(sockFd, SOL_SOCKET, SO_MARK, &fwmark.intValue, &fwmarkLen));
3470     EXPECT_EQ(0, close(sockFd));
3471     return fwmark.intValue;
3472 }
3473 
3474 }  // namespace
3475 
TEST_F(NetdBinderTest,GetFwmarkForNetwork)3476 TEST_F(NetdBinderTest, GetFwmarkForNetwork) {
3477     // Save current default network.
3478     ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3479 
3480     in6_addr v6Addr = {
3481             {// 2001:db8:cafe::8888
3482              .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0x88}}};
3483     // Add test physical network 1 and set as default network.
3484     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3485     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3486     EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "2001:db8::/32", "").isOk());
3487     EXPECT_TRUE(mNetd->networkSetDefault(TEST_NETID1).isOk());
3488     // Add test physical network 2
3489     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
3490     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
3491 
3492     // Get fwmark for network 1.
3493     MarkMaskParcel maskMarkNet1;
3494     ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID1, &maskMarkNet1).isOk());
3495 
3496     uint32_t fwmarkTcp = createIpv6SocketAndCheckMark(SOCK_STREAM, v6Addr);
3497     uint32_t fwmarkUdp = createIpv6SocketAndCheckMark(SOCK_DGRAM, v6Addr);
3498     EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkTcp & maskMarkNet1.mask));
3499     EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkUdp & maskMarkNet1.mask));
3500 
3501     // Get fwmark for network 2.
3502     MarkMaskParcel maskMarkNet2;
3503     ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID2, &maskMarkNet2).isOk());
3504     EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkTcp & maskMarkNet2.mask));
3505     EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkUdp & maskMarkNet2.mask));
3506 
3507     // Remove test physical network.
3508     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
3509     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
3510 }
3511 
3512 namespace {
3513 
makeTetherOffloadRule(int inputInterfaceIndex,int outputInterfaceIndex,const std::vector<uint8_t> & destination,int prefixLength,const std::vector<uint8_t> & srcL2Address,const std::vector<uint8_t> & dstL2Address,int pmtu)3514 TetherOffloadRuleParcel makeTetherOffloadRule(int inputInterfaceIndex, int outputInterfaceIndex,
3515                                               const std::vector<uint8_t>& destination,
3516                                               int prefixLength,
3517                                               const std::vector<uint8_t>& srcL2Address,
3518                                               const std::vector<uint8_t>& dstL2Address, int pmtu) {
3519     android::net::TetherOffloadRuleParcel parcel;
3520     parcel.inputInterfaceIndex = inputInterfaceIndex;
3521     parcel.outputInterfaceIndex = outputInterfaceIndex;
3522     parcel.destination = destination;
3523     parcel.prefixLength = prefixLength;
3524     parcel.srcL2Address = srcL2Address;
3525     parcel.dstL2Address = dstL2Address;
3526     parcel.pmtu = pmtu;
3527     return parcel;
3528 }
3529 
3530 }  // namespace
3531 
TEST_F(NetdBinderTest,TetherOffloadRule)3532 TEST_F(NetdBinderTest, TetherOffloadRule) {
3533     SKIP_IF_BPF_NOT_SUPPORTED;
3534 
3535     // TODO: Perhaps verify invalid interface index once the netd handle the error in methods.
3536     constexpr uint32_t kIfaceInt = 101;
3537     constexpr uint32_t kIfaceExt = 102;
3538     constexpr uint32_t kIfaceNonExistent = 103;
3539 
3540     const std::vector<uint8_t> kAddr6 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0x00, 0x00,
3541                                          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88};
3542     const std::vector<uint8_t> kSrcMac = {0x00, 0x00, 0x00, 0x00, 0x00, 0x0a};
3543     const std::vector<uint8_t> kDstMac = {0x00, 0x00, 0x00, 0x00, 0x00, 0x0b};
3544 
3545     const std::vector<uint8_t> kInvalidAddr4 = {0xac, 0x0a, 0x0d, 0xb8};  // should be IPv6 address
3546     const std::vector<uint8_t> kInvalidMac = {0xde, 0xad, 0xbe, 0xef};    // should be 6-byte length
3547 
3548     // Invalid IP address, add rule
3549     TetherOffloadRuleParcel rule = makeTetherOffloadRule(
3550             kIfaceExt, kIfaceInt, kInvalidAddr4 /*bad*/, 128, kSrcMac, kDstMac, 1500);
3551     auto status = mNetd->tetherOffloadRuleAdd(rule);
3552     EXPECT_FALSE(status.isOk());
3553     EXPECT_EQ(EAFNOSUPPORT, status.serviceSpecificErrorCode());
3554 
3555     // Invalid source L2 address, add rule
3556     rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kInvalidMac /*bad*/, kDstMac,
3557                                  1500);
3558     status = mNetd->tetherOffloadRuleAdd(rule);
3559     EXPECT_FALSE(status.isOk());
3560     EXPECT_EQ(ENXIO, status.serviceSpecificErrorCode());
3561 
3562     // Invalid destination L2 address, add rule
3563     rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kSrcMac, kInvalidMac /*bad*/,
3564                                  1500);
3565     status = mNetd->tetherOffloadRuleAdd(rule);
3566     EXPECT_FALSE(status.isOk());
3567     EXPECT_EQ(ENXIO, status.serviceSpecificErrorCode());
3568 
3569     // Invalid IP address, remove rule
3570     rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kInvalidAddr4 /*bad*/, 128, kSrcMac, kDstMac,
3571                                  1500);
3572     status = mNetd->tetherOffloadRuleRemove(rule);
3573     EXPECT_FALSE(status.isOk());
3574     EXPECT_EQ(EAFNOSUPPORT, status.serviceSpecificErrorCode());
3575 
3576     // Invalid prefix length
3577     rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 64 /*bad*/, kSrcMac, kDstMac, 1500);
3578     status = mNetd->tetherOffloadRuleAdd(rule);
3579     EXPECT_FALSE(status.isOk());
3580     EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
3581     status = mNetd->tetherOffloadRuleRemove(rule);
3582     EXPECT_FALSE(status.isOk());
3583     EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
3584 
3585     // Invalid interface index
3586     rule = makeTetherOffloadRule(kIfaceExt, 0, kAddr6, 128, kSrcMac, kDstMac, 1500);
3587     status = mNetd->tetherOffloadRuleAdd(rule);
3588     EXPECT_FALSE(status.isOk());
3589     EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
3590     rule = makeTetherOffloadRule(0, kIfaceInt, kAddr6, 64, kSrcMac, kDstMac, 1500);
3591     status = mNetd->tetherOffloadRuleRemove(rule);
3592     EXPECT_FALSE(status.isOk());
3593     EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
3594 
3595     // Invalid pmtu (too low)
3596     rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kSrcMac, kDstMac, 1279);
3597     status = mNetd->tetherOffloadRuleAdd(rule);
3598     EXPECT_FALSE(status.isOk());
3599     EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
3600 
3601     // Invalid pmtu (too high)
3602     rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kSrcMac, kDstMac, 65536);
3603     status = mNetd->tetherOffloadRuleAdd(rule);
3604     EXPECT_FALSE(status.isOk());
3605     EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
3606 
3607     // Remove non existent rule. Expect that silently return success if the rule did not exist.
3608     rule = makeTetherOffloadRule(kIfaceNonExistent, kIfaceInt, kAddr6, 128, kSrcMac, kDstMac, 1500);
3609     EXPECT_TRUE(mNetd->tetherOffloadRuleRemove(rule).isOk());
3610 
3611     // Add and remove rule normally.
3612     rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kSrcMac, kDstMac, 1500);
3613     EXPECT_TRUE(mNetd->tetherOffloadRuleAdd(rule).isOk());
3614     EXPECT_TRUE(mNetd->tetherOffloadRuleRemove(rule).isOk());
3615 }
3616 
expectPacket(int fd,uint8_t * ipPacket,ssize_t ipLen)3617 static bool expectPacket(int fd, uint8_t* ipPacket, ssize_t ipLen) {
3618     constexpr bool kDebug = false;
3619 
3620     uint8_t buf[ETHER_HDR_LEN + 1500];
3621 
3622     // Wait a bit to ensure that the packet we're interested in has arrived.
3623     // TODO: speed this up.
3624     usleep(100 * 1000);
3625 
3626     ssize_t bytesRead;
3627     ssize_t expectedLen = ipLen + ETHER_HDR_LEN;
3628     while ((bytesRead = read(fd, buf, sizeof(buf))) >= 0) {
3629         if (kDebug) {
3630             std::cerr << fmt::format(
3631                     "Expected: {:02x}\n  Actual: {:02x}\n",
3632                     fmt::join(ipPacket, ipPacket + ipLen, " "),
3633                     fmt::join(buf + ETHER_HDR_LEN, buf + ETHER_HDR_LEN + ipLen, " "));
3634         }
3635 
3636         if (bytesRead != expectedLen) {
3637             continue;
3638         }
3639 
3640         if (!memcmp(ipPacket, buf + ETHER_HDR_LEN, ipLen)) {
3641             return true;
3642         }
3643     }
3644 
3645     return false;
3646 }
3647 
TEST_F(NetdBinderTest,TetherOffloadForwarding)3648 TEST_F(NetdBinderTest, TetherOffloadForwarding) {
3649     SKIP_IF_EXTENDED_BPF_NOT_SUPPORTED;
3650 
3651     constexpr const char* kDownstreamPrefix = "2001:db8:2::/64";
3652 
3653     // 1500-byte packet.
3654     constexpr unsigned short kPayloadLen = 1500 - sizeof(ipv6hdr);
3655     struct packet {
3656         ipv6hdr hdr;
3657         char data[kPayloadLen];
3658     } __attribute__((packed)) pkt = {
3659             .hdr =
3660                     {
3661                             .version = 6,
3662                             .payload_len = htons(kPayloadLen),
3663                             .nexthdr = 59,  // No next header.
3664                             .hop_limit = 64,
3665                             .saddr = {{{0x20, 0x01, 0x0d, 0xb8, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
3666                                         0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}},
3667                             .daddr = {{{0x20, 0x01, 0x0d, 0xb8, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
3668                                         0x00, 0x00, 0x0f, 0x00, 0xca, 0xfe}}},
3669                     },
3670     };
3671     ASSERT_EQ(1500U, sizeof(pkt));
3672 
3673     // Use one of the test's tun interfaces as upstream.
3674     // It must be part of a network or it will not have the clsact attached.
3675     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3676     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3677     int fd1 = sTun.getFdForTesting();
3678 
3679     // Create our own tap as a downstream.
3680     TunInterface tap;
3681     ASSERT_EQ(0, tap.init(true /* isTap */));
3682     ASSERT_LE(tap.name().size(), static_cast<size_t>(IFNAMSIZ));
3683     int fd2 = tap.getFdForTesting();
3684 
3685     // Set it to nonblocking so that expectPacket can work.
3686     int flags = fcntl(fd2, F_GETFL, 0);
3687     fcntl(fd2, F_SETFL, flags | O_NONBLOCK);
3688 
3689     // Downstream interface setup. Add to local network, add directly-connected route, etc.
3690     binder::Status status = mNetd->networkAddInterface(INetd::LOCAL_NET_ID, tap.name());
3691     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3692     status = mNetd->tetherInterfaceAdd(tap.name());
3693     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3694     expectTetherInterfaceConfigureForIPv6Router(tap.name());
3695 
3696     // Can't easily use INetd::NEXTHOP_NONE because it is a String16 constant. Use "" instead.
3697     status = mNetd->networkAddRoute(INetd::LOCAL_NET_ID, tap.name(), kDownstreamPrefix, "");
3698     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3699 
3700     // Set up forwarding. All methods take intIface first and extIface second.
3701     status = mNetd->tetherAddForward(tap.name(), sTun.name());
3702     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3703     status = mNetd->ipfwdAddInterfaceForward(tap.name(), sTun.name());
3704     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3705 
3706     std::vector<uint8_t> kDummyMac = {02, 00, 00, 00, 00, 00};
3707     uint8_t* daddr = reinterpret_cast<uint8_t*>(&pkt.hdr.daddr);
3708     std::vector<uint8_t> dstAddr(daddr, daddr + sizeof(pkt.hdr.daddr));
3709 
3710     TetherOffloadRuleParcel rule = makeTetherOffloadRule(sTun.ifindex(), tap.ifindex(), dstAddr,
3711                                                          128, kDummyMac, kDummyMac, sizeof(pkt));
3712     status = mNetd->tetherOffloadRuleAdd(rule);
3713     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3714 
3715     // Set data limit to one byte less than two packets.
3716     // If you get rid of the '- 1' then the second packet will get forwarded
3717     // and the EXPECT_FALSE(expectPacket(...)) a dozen lines down will fail.
3718     status = mNetd->tetherOffloadSetInterfaceQuota(sTun.ifindex(), sizeof(pkt) * 2 - 1);
3719     EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3720 
3721     // Receive a packet on sTun.
3722     EXPECT_EQ((ssize_t)sizeof(pkt), write(fd1, &pkt, sizeof(pkt)));
3723 
3724     // Expect a packet identical to pkt, except with a TTL of 63.
3725     struct packet pkt2 = pkt;
3726     ASSERT_EQ(1500U, sizeof(pkt2));
3727     pkt2.hdr.hop_limit = pkt.hdr.hop_limit - 1;
3728     EXPECT_TRUE(expectPacket(fd2, (uint8_t*)&pkt2, sizeof(pkt2)));
3729 
3730     // Receive a second packet on sTun.
3731     EXPECT_EQ((ssize_t)sizeof(pkt), write(fd1, &pkt, sizeof(pkt)));
3732 
3733     // Should fail to forward due to quota limit.
3734     EXPECT_FALSE(expectPacket(fd2, (uint8_t*)&pkt2, sizeof(pkt2)));
3735 
3736     // Clean up.
3737     EXPECT_TRUE(mNetd->tetherOffloadRuleRemove(rule).isOk());
3738 
3739     TetherStatsParcel tetherStats;
3740     EXPECT_TRUE(mNetd->tetherOffloadGetAndClearStats(sTun.ifindex(), &tetherStats).isOk());
3741     EXPECT_EQ("", tetherStats.iface);
3742     EXPECT_EQ(static_cast<int64_t>(sizeof(pkt)), tetherStats.rxBytes);
3743     EXPECT_EQ(1, tetherStats.rxPackets);
3744     EXPECT_EQ(0, tetherStats.txBytes);
3745     EXPECT_EQ(0, tetherStats.txPackets);
3746     EXPECT_EQ(sTun.ifindex(), tetherStats.ifIndex);
3747 
3748     EXPECT_TRUE(mNetd->ipfwdRemoveInterfaceForward(tap.name(), sTun.name()).isOk());
3749     EXPECT_TRUE(mNetd->tetherRemoveForward(tap.name(), sTun.name()).isOk());
3750     EXPECT_TRUE(mNetd->networkRemoveRoute(INetd::LOCAL_NET_ID, tap.name(), kDownstreamPrefix, "")
3751                         .isOk());
3752     EXPECT_TRUE(mNetd->tetherInterfaceRemove(tap.name()).isOk());
3753     EXPECT_TRUE(mNetd->networkRemoveInterface(INetd::LOCAL_NET_ID, tap.name()).isOk());
3754     EXPECT_TRUE(mNetd->networkRemoveInterface(TEST_NETID1, sTun.name()).isOk());
3755 }
3756