blob: 3f77a76783254265f3eb83062b8994fe025cf399 [file] [log] [blame]
Lorenzo Colitti89faa342016-02-26 11:38:47 +09001/*
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
Robin Leeb8087362016-03-30 18:43:08 +010019#include <cerrno>
20#include <cinttypes>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090021#include <cstdint>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090022#include <cstdio>
23#include <cstdlib>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090024#include <set>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090025#include <vector>
26
Lorenzo Colitti755faa92016-07-27 22:10:49 +090027#include <fcntl.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090028#include <ifaddrs.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090029#include <netdb.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090030#include <sys/socket.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090031#include <sys/types.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090032#include <netinet/in.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090033#include <linux/if.h>
34#include <linux/if_tun.h>
Ben Schwartze7601812017-04-28 16:38:29 -040035#include <openssl/base64.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090036
Luke Huang531f5d32018-08-03 15:19:05 +080037#include <android-base/file.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090038#include <android-base/macros.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090039#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090040#include <android-base/strings.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070041#include <bpf/BpfUtils.h>
Robin Leeb8087362016-03-30 18:43:08 +010042#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090043#include <gtest/gtest.h>
44#include <logwrap/logwrap.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090045#include <netutils/ifc.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090046
Nathan Harold21299f72018-03-16 20:13:03 -070047#include "InterfaceController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090048#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090049#include "Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070050#include "XfrmController.h"
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090051#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090052#include "android/net/INetd.h"
Robin Leeb8087362016-03-30 18:43:08 +010053#include "android/net/UidRange.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090054#include "binder/IServiceManager.h"
Nathan Harold21299f72018-03-16 20:13:03 -070055#include "netdutils/Syscalls.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090056
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090057#define IP_PATH "/system/bin/ip"
58#define IP6TABLES_PATH "/system/bin/ip6tables"
59#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090060#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080061#define RAW_TABLE "raw"
62#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080063#define FILTER_TABLE "filter"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090064
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090065namespace binder = android::binder;
66namespace netdutils = android::netdutils;
67
68using android::IBinder;
69using android::IServiceManager;
70using android::sp;
71using android::String16;
72using android::String8;
73using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080074using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090075using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090076using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080077using android::base::Trim;
Chenbo Feng837ddfc2018-05-08 13:45:08 -070078using android::bpf::hasBpfSupport;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090079using android::net::INetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090080using android::net::TunInterface;
Robin Leeb8087362016-03-30 18:43:08 +010081using android::net::UidRange;
Nathan Harold21299f72018-03-16 20:13:03 -070082using android::net::XfrmController;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090083using android::os::PersistableBundle;
Robin Leeb8087362016-03-30 18:43:08 +010084
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090085#define SKIP_IF_BPF_SUPPORTED \
86 do { \
87 if (hasBpfSupport()) return; \
88 } while (0)
Chenbo Feng837ddfc2018-05-08 13:45:08 -070089
Robin Leeb8087362016-03-30 18:43:08 +010090static const char* IP_RULE_V4 = "-4";
91static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090092static const int TEST_NETID1 = 65501;
93static const int TEST_NETID2 = 65502;
94constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090095
Benedict Wongb2daefb2017-12-06 22:05:46 -080096static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
97static const std::string ESP_ALLOW_RULE("esp");
98
Lorenzo Colitti89faa342016-02-26 11:38:47 +090099class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900100 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900101 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900102 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900103 sp<IBinder> binder = sm->getService(String16("netd"));
104 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900105 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900106 }
107 }
108
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900109 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900110 ASSERT_NE(nullptr, mNetd.get());
111 }
112
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900113 void TearDown() override {
114 mNetd->networkDestroy(TEST_NETID1);
115 mNetd->networkDestroy(TEST_NETID2);
116 }
117
Nathan Harold21299f72018-03-16 20:13:03 -0700118 bool allocateIpSecResources(bool expectOk, int32_t *spi);
119
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900120 // Static because setting up the tun interface takes about 40ms.
121 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900122 ASSERT_EQ(0, sTun.init());
123 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900124 }
125
126 static void TearDownTestCase() {
127 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900128 sTun.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900129 }
130
131 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900132
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900133 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900134 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900135 static TunInterface sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900136};
137
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900138TunInterface BinderTest::sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900139
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900140class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900141 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700142 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900143 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900144 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900145 }
146
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900147 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900148 std::string mName;
149};
150
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900151TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900152 TimedOperation t("isAlive RPC");
153 bool isAlive = false;
154 mNetd->isAlive(&isAlive);
155 ASSERT_TRUE(isAlive);
156}
157
158static int randomUid() {
159 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
160}
161
Robin Leeb8087362016-03-30 18:43:08 +0100162static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900163 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900164 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
165 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900166 perror("popen");
167 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900168 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900169
170 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100171 size_t bufsize = 0;
172 ssize_t linelen = 0;
173 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900174 lines.push_back(std::string(line, linelen));
175 free(line);
176 line = nullptr;
177 }
178
179 pclose(f);
180 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900181}
182
Robin Leeb8087362016-03-30 18:43:08 +0100183static std::vector<std::string> listIpRules(const char *ipVersion) {
184 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
185 return runCommand(command);
186}
187
188static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900189 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100190 return runCommand(command);
191}
192
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900193static int iptablesRuleLineLength(const char *binary, const char *chainName) {
194 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900195}
196
Benedict Wongb2daefb2017-12-06 22:05:46 -0800197static bool iptablesRuleExists(const char *binary,
198 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900199 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800200 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900201 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800202 if(rule.find(expectedRule) != std::string::npos) {
203 return true;
204 }
205 }
206 return false;
207}
208
209static bool iptablesNoSocketAllowRuleExists(const char *chainName){
210 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
211 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
212}
213
214static bool iptablesEspAllowRuleExists(const char *chainName){
215 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
216 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
217}
218
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900219TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700220 SKIP_IF_BPF_SUPPORTED;
221
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900222 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
223 const int kNumUids = 500;
224 std::vector<int32_t> noUids(0);
225 std::vector<int32_t> uids(kNumUids);
226 for (int i = 0; i < kNumUids; i++) {
227 uids[i] = randomUid();
228 }
229
230 bool ret;
231 {
232 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900233 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900234 }
235 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800236 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
237 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
238 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
239 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900240 {
241 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900242 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900243 }
244 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900245 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
246 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900247
248 {
249 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900250 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900251 }
252 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900253 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
254 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800255 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
256 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900257
258 {
259 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900260 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900261 }
262 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900263 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
264 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900265
266 // Check that the call fails if iptables returns an error.
267 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900268 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900269 EXPECT_EQ(false, ret);
270}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900271
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900272TEST_F(BinderTest, VirtualTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700273 const struct TestData {
274 const std::string family;
275 const std::string deviceName;
276 const std::string localAddress;
277 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800278 int32_t iKey;
279 int32_t oKey;
280 } kTestData[] = {
Nathan Harold21299f72018-03-16 20:13:03 -0700281 {"IPV4", "test_vti", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53},
282 {"IPV6", "test_vti6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50},
manojboopathi8707f232018-01-02 14:45:47 -0800283 };
284
285 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700286 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800287
288 binder::Status status;
289
290 // Create Virtual Tunnel Interface.
Nathan Harold21299f72018-03-16 20:13:03 -0700291 status = mNetd->addVirtualTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
292 td.iKey, td.oKey);
manojboopathi8707f232018-01-02 14:45:47 -0800293 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
294
295 // Update Virtual Tunnel Interface.
296 status = mNetd->updateVirtualTunnelInterface(td.deviceName, td.localAddress,
297 td.remoteAddress, td.iKey, td.oKey);
298 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
299
300 // Remove Virtual Tunnel Interface.
301 status = mNetd->removeVirtualTunnelInterface(td.deviceName);
302 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
303 }
304}
305
Nathan Harold2deff322018-05-10 14:03:48 -0700306// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
307// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
308#if INTPTR_MAX != INT32_MAX
Benedict Wonga04ffa72018-05-09 21:42:42 -0700309static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
310 static_cast<int>(android::net::XfrmDirection::OUT)};
311static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
312
Nathan Harold21299f72018-03-16 20:13:03 -0700313#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
314 do { if ((_expect_) != (_ret_)) return false; } while(false)
315bool BinderTest::allocateIpSecResources(bool expectOk, int32_t *spi) {
316 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
317 SCOPED_TRACE(status);
318 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
319
320 // Add a policy
Benedict Wonga04ffa72018-05-09 21:42:42 -0700321 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700322 SCOPED_TRACE(status);
323 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
324
325 // Add an ipsec interface
326 status = netdutils::statusFromErrno(
327 XfrmController::addVirtualTunnelInterface(
328 "ipsec_test", "::", "::1", 0xF00D, 0xD00D, false),
329 "addVirtualTunnelInterface");
330 return (status.ok() == expectOk);
331}
332
Benedict Wonga04ffa72018-05-09 21:42:42 -0700333TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
334 binder::Status status;
335
336 // Repeat to ensure cleanup and recreation works correctly
337 for (int i = 0; i < 2; i++) {
338 for (int direction : XFRM_DIRECTIONS) {
339 for (int addrFamily : ADDRESS_FAMILIES) {
340 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
341 "127.0.0.6", 123, 0, 0);
342 EXPECT_TRUE(status.isOk())
343 << " family: " << addrFamily << " direction: " << direction;
344 }
345 }
346
347 // Cleanup
348 for (int direction : XFRM_DIRECTIONS) {
349 for (int addrFamily : ADDRESS_FAMILIES) {
350 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0);
351 EXPECT_TRUE(status.isOk());
352 }
353 }
354 }
355}
356
357TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
358 binder::Status status;
359
360 // Repeat to ensure cleanup and recreation works correctly
361 for (int i = 0; i < 2; i++) {
362 for (int direction : XFRM_DIRECTIONS) {
363 for (int addrFamily : ADDRESS_FAMILIES) {
364 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
365 "2001:db8::d00d", 123, 0, 0);
366 EXPECT_TRUE(status.isOk())
367 << " family: " << addrFamily << " direction: " << direction;
368 }
369 }
370
371 // Cleanup
372 for (int direction : XFRM_DIRECTIONS) {
373 for (int addrFamily : ADDRESS_FAMILIES) {
374 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0);
375 EXPECT_TRUE(status.isOk());
376 }
377 }
378 }
379}
380
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900381TEST_F(BinderTest, XfrmControllerInit) {
Nathan Harold21299f72018-03-16 20:13:03 -0700382 netdutils::Status status;
383 status = XfrmController::Init();
384 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700385
386 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
387 // feature.
388 if (status.code() == EOPNOTSUPP) return;
389
Nathan Harold21299f72018-03-16 20:13:03 -0700390 ASSERT_TRUE(status.ok());
391
392 int32_t spi = 0;
393
394 ASSERT_TRUE(allocateIpSecResources(true, &spi));
395 ASSERT_TRUE(allocateIpSecResources(false, &spi));
396
397 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700398 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700399 ASSERT_TRUE(allocateIpSecResources(true, &spi));
400
401 // Clean up
402 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0);
403 SCOPED_TRACE(status);
404 ASSERT_TRUE(status.ok());
405
Benedict Wonga04ffa72018-05-09 21:42:42 -0700406 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700407 SCOPED_TRACE(status);
408 ASSERT_TRUE(status.ok());
409
410 // Remove Virtual Tunnel Interface.
411 status = netdutils::statusFromErrno(
412 XfrmController::removeVirtualTunnelInterface("ipsec_test"),
413 "removeVirtualTunnelInterface");
414
415 ASSERT_TRUE(status.ok());
416}
Nathan Harold2deff322018-05-10 14:03:48 -0700417#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700418
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900419static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900420 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900421
422 // Output looks like this:
423 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900424 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900425 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900426 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900427 //
428 // or:
429 //
430 // Chain bw_data_saver (1 references)
431 // target prot opt source destination
432 // ... possibly connectivity critical packet rules here ...
433 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900434
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900435 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900436
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900437 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
438 // Data saver disabled.
439 return 0;
440 }
441
442 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
443
444 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
445 // Data saver enabled.
446 return 1;
447 }
448
449 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900450}
451
452bool enableDataSaver(sp<INetd>& netd, bool enable) {
453 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
454 bool ret;
455 netd->bandwidthEnableDataSaver(enable, &ret);
456 return ret;
457}
458
459int getDataSaverState() {
460 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
461 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
462 EXPECT_EQ(enabled4, enabled6);
463 EXPECT_NE(-1, enabled4);
464 EXPECT_NE(-1, enabled6);
465 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
466 return -1;
467 }
468 return enabled6;
469}
470
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900471TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900472 const int wasEnabled = getDataSaverState();
473 ASSERT_NE(-1, wasEnabled);
474
475 if (wasEnabled) {
476 ASSERT_TRUE(enableDataSaver(mNetd, false));
477 EXPECT_EQ(0, getDataSaverState());
478 }
479
480 ASSERT_TRUE(enableDataSaver(mNetd, false));
481 EXPECT_EQ(0, getDataSaverState());
482
483 ASSERT_TRUE(enableDataSaver(mNetd, true));
484 EXPECT_EQ(1, getDataSaverState());
485
486 ASSERT_TRUE(enableDataSaver(mNetd, true));
487 EXPECT_EQ(1, getDataSaverState());
488
489 if (!wasEnabled) {
490 ASSERT_TRUE(enableDataSaver(mNetd, false));
491 EXPECT_EQ(0, getDataSaverState());
492 }
493}
Robin Leeb8087362016-03-30 18:43:08 +0100494
495static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
496 const std::string& action, const char* ipVersion) {
497 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100498 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100499 std::vector<std::string> rules = listIpRules(ipVersion);
500
501 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
502 std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
503 range.getStart(), range.getStop(), action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900504 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800505 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100506 return true;
507 }
508 }
509 return false;
510}
511
512static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
513 const std::string& action) {
514 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
515 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
516 EXPECT_EQ(existsIp4, existsIp6);
517 return existsIp4;
518}
519
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900520TEST_F(BinderTest, NetworkInterfaces) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900521 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, "").isOk());
522 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, "").serviceSpecificErrorCode());
523 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
524 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
525
526 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
527 EXPECT_EQ(EBUSY,
528 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
529
530 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
531 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
532 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
533}
534
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900535TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900536 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
537
538 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
539 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
540 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
541
542 std::vector<UidRange> uidRanges = {
543 {BASE_UID + 8005, BASE_UID + 8012},
544 {BASE_UID + 8090, BASE_UID + 8099}
545 };
546 UidRange otherRange(BASE_UID + 8190, BASE_UID + 8299);
547 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
548
549 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
550
551 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
552 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
553 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
554 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
555
556 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
557 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
558 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
559 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
560
561 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
562}
563
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900564TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100565 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100566
Robin Leeb8087362016-03-30 18:43:08 +0100567 std::vector<UidRange> uidRanges = {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900568 {BASE_UID + 150, BASE_UID + 224},
569 {BASE_UID + 226, BASE_UID + 300}
Robin Leeb8087362016-03-30 18:43:08 +0100570 };
571
572 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
573 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
574
575 // Create two valid rules.
576 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
577 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
578 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
579 for (auto const& range : uidRanges) {
580 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
581 }
582
583 // Remove the rules.
584 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
585 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
586 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
587 for (auto const& range : uidRanges) {
588 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
589 }
590
591 // Fail to remove the rules a second time after they are already deleted.
592 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
593 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
594 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
595
596 // All rules should be the same as before.
597 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
598 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
599}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900600
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900601// Create a socket pair that isLoopbackSocket won't think is local.
602void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900603 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900604 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900605 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
606
607 socklen_t addrlen = sizeof(server6);
608 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
609 ASSERT_EQ(0, listen(*serverSocket, 10));
610
Bernie Innocentif6918262018-06-11 17:37:35 +0900611 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900612 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900613 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900614 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
615 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
616
Bernie Innocentif6918262018-06-11 17:37:35 +0900617 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900618 ASSERT_NE(-1, *acceptedSocket);
619
620 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
621}
622
623void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
624 char buf[4096];
625 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
626 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
627 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
628}
629
630void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
631 // Check that the client socket was closed with ECONNABORTED.
632 int ret = write(clientSocket, "foo", sizeof("foo"));
633 int err = errno;
634 EXPECT_EQ(-1, ret);
635 EXPECT_EQ(ECONNABORTED, err);
636
637 // Check that it sent a RST to the server.
638 ret = write(acceptedSocket, "foo", sizeof("foo"));
639 err = errno;
640 EXPECT_EQ(-1, ret);
641 EXPECT_EQ(ECONNRESET, err);
642}
643
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900644TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900645 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900646 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900647
648 // Pick a random UID in the system UID range.
649 constexpr int baseUid = AID_APP - 2000;
650 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
651 int uid = baseUid + 500 + arc4random_uniform(1000);
652 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
653
654 // UID ranges that don't contain uid.
655 std::vector<UidRange> uidRanges = {
656 {baseUid + 42, baseUid + 449},
657 {baseUid + 1536, AID_APP - 4},
658 {baseUid + 498, uid - 1},
659 {uid + 1, baseUid + 1520},
660 };
661 // A skip list that doesn't contain UID.
662 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
663
664 // Close sockets. Our test socket should be intact.
665 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
666 checkSocketpairOpen(clientSocket, acceptedSocket);
667
668 // UID ranges that do contain uid.
669 uidRanges = {
670 {baseUid + 42, baseUid + 449},
671 {baseUid + 1536, AID_APP - 4},
672 {baseUid + 498, baseUid + 1520},
673 };
674 // Add uid to the skip list.
675 skipUids.push_back(uid);
676
677 // Close sockets. Our test socket should still be intact because it's in the skip list.
678 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
679 checkSocketpairOpen(clientSocket, acceptedSocket);
680
681 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
682 skipUids.resize(skipUids.size() - 1);
683 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
684 checkSocketpairClosed(clientSocket, acceptedSocket);
685
686 close(clientSocket);
687 close(serverSocket);
688 close(acceptedSocket);
689}
Erik Klinecc4f2732016-08-03 11:24:27 +0900690
691namespace {
692
693int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
694 if (buf == nullptr) return -1;
695
696 int prefixLength = 0;
697 bool endOfContiguousBits = false;
698 for (unsigned int i = 0; i < buflen; i++) {
699 const uint8_t value = buf[i];
700
701 // Bad bit sequence: check for a contiguous set of bits from the high
702 // end by verifying that the inverted value + 1 is a power of 2
703 // (power of 2 iff. (v & (v - 1)) == 0).
704 const uint8_t inverse = ~value + 1;
705 if ((inverse & (inverse - 1)) != 0) return -1;
706
707 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
708
709 // Bogus netmask.
710 if (endOfContiguousBits && value != 0) return -1;
711
712 if (value != 0xff) endOfContiguousBits = true;
713 }
714
715 return prefixLength;
716}
717
718template<typename T>
719int netmaskToPrefixLength(const T *p) {
720 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
721}
722
723
724static bool interfaceHasAddress(
725 const std::string &ifname, const char *addrString, int prefixLength) {
726 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900727
728 const struct addrinfo hints = {
729 .ai_flags = AI_NUMERICHOST,
730 .ai_family = AF_UNSPEC,
731 .ai_socktype = SOCK_DGRAM,
732 };
733 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
734 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
735 return false;
736 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900737 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900738
739 struct ifaddrs *ifaddrsList = nullptr;
740 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
741
742 if (getifaddrs(&ifaddrsList) != 0) {
743 return false;
744 }
745
746 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
747 if (std::string(addr->ifa_name) != ifname ||
748 addr->ifa_addr == nullptr ||
749 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
750 continue;
751 }
752
753 switch (addr->ifa_addr->sa_family) {
754 case AF_INET: {
755 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
756 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
757 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
758 continue;
759 }
760
761 if (prefixLength < 0) return true; // not checking prefix lengths
762
763 if (addr->ifa_netmask == nullptr) return false;
764 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
765 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
766 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
767 }
768 case AF_INET6: {
769 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
770 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
771 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_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_in6*>(addr->ifa_netmask);
779 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
780 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
781 }
782 default:
783 // Cannot happen because we have already screened for matching
784 // address families at the top of each iteration.
785 continue;
786 }
787 }
788
789 return false;
790}
791
792} // namespace
793
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900794TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900795 static const struct TestData {
796 const char *addrString;
797 const int prefixLength;
798 const bool expectSuccess;
799 } kTestData[] = {
800 { "192.0.2.1", 24, true },
801 { "192.0.2.2", 25, true },
802 { "192.0.2.3", 32, true },
803 { "192.0.2.4", 33, false },
804 { "192.not.an.ip", 24, false },
805 { "2001:db8::1", 64, true },
806 { "2001:db8::2", 65, true },
807 { "2001:db8::3", 128, true },
808 { "2001:db8::4", 129, false },
809 { "foo:bar::bad", 64, false },
810 };
811
812 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
813 const auto &td = kTestData[i];
814
815 // [1.a] Add the address.
816 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900817 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900818 if (td.expectSuccess) {
819 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
820 } else {
821 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
822 ASSERT_NE(0, status.serviceSpecificErrorCode());
823 }
824
825 // [1.b] Verify the addition meets the expectation.
826 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900827 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900828 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900829 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900830 }
831
832 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900833 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900834 if (td.expectSuccess) {
835 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
836 } else {
837 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
838 ASSERT_NE(0, status.serviceSpecificErrorCode());
839 }
840
841 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900842 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900843 }
844}
Erik Kline55b06f82016-07-04 09:57:18 +0900845
Erik Kline38e51f12018-09-06 20:14:44 +0900846TEST_F(BinderTest, GetProcSysNet) {
847 const char LOOPBACK[] = "lo";
848 static const struct {
849 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900850 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900851 const char* ifname;
852 const char* parameter;
853 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900854 const int expectedReturnCode;
855 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900856 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
857 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
858 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
859 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
860 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
861 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
862 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900863 };
864
Erik Kline38e51f12018-09-06 20:14:44 +0900865 for (int i = 0; i < arraysize(kTestData); i++) {
866 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900867
Erik Kline38e51f12018-09-06 20:14:44 +0900868 std::string value;
869 const binder::Status status =
870 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
871
872 if (td.expectedReturnCode == 0) {
873 SCOPED_TRACE(String8::format("test case %d should have passed", i));
874 EXPECT_EQ(0, status.exceptionCode());
875 EXPECT_EQ(0, status.serviceSpecificErrorCode());
876 EXPECT_EQ(td.expectedValue, value);
877 } else {
878 SCOPED_TRACE(String8::format("test case %d should have failed", i));
879 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
880 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
881 }
882 }
883}
884
885TEST_F(BinderTest, SetProcSysNet) {
886 static const struct {
887 const int ipversion;
888 const int which;
889 const char* ifname;
890 const char* parameter;
891 const char* value;
892 const int expectedReturnCode;
893 } kTestData[] = {
894 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
895 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
896 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
897 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
898 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
899 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
900 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
901 };
902
903 for (int i = 0; i < arraysize(kTestData); i++) {
904 const auto& td = kTestData[i];
905
906 const binder::Status status =
907 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900908
909 if (td.expectedReturnCode == 0) {
910 SCOPED_TRACE(String8::format("test case %d should have passed", i));
911 EXPECT_EQ(0, status.exceptionCode());
912 EXPECT_EQ(0, status.serviceSpecificErrorCode());
913 } else {
914 SCOPED_TRACE(String8::format("test case %d should have failed", i));
915 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
916 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
917 }
918 }
919}
Ben Schwartze7601812017-04-28 16:38:29 -0400920
Erik Kline38e51f12018-09-06 20:14:44 +0900921TEST_F(BinderTest, GetSetProcSysNet) {
922 const int ipversion = INetd::IPV6;
923 const int category = INetd::NEIGH;
924 const std::string& tun = sTun.name();
925 const std::string parameter("ucast_solicit");
926
927 std::string value{};
928 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
929 EXPECT_FALSE(value.empty());
930 const int ival = std::stoi(value);
931 EXPECT_GT(ival, 0);
932 // Try doubling the parameter value (always best!).
933 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
934 .isOk());
935 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
936 EXPECT_EQ(2 * ival, std::stoi(value));
937 // Try resetting the parameter.
938 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
939 .isOk());
940 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
941 EXPECT_EQ(ival, std::stoi(value));
942}
943
Ben Schwartze7601812017-04-28 16:38:29 -0400944static std::string base64Encode(const std::vector<uint8_t>& input) {
945 size_t out_len;
946 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
947 // out_len includes the trailing NULL.
948 uint8_t output_bytes[out_len];
949 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
950 return std::string(reinterpret_cast<char*>(output_bytes));
951}
952
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900953TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900954 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400955 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400956 std::vector<uint8_t> short_fp(1);
957 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
958 std::vector<std::string> test_domains;
959 std::vector<int> test_params = { 300, 25, 8, 8 };
960 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400961 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400962 const std::vector<std::string> servers;
963 const std::string tlsName;
964 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400965 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900966 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400967 { {"192.0.2.1"}, "", {}, 0 },
968 { {"2001:db8::2"}, "host.name", {}, 0 },
969 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
970 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900971 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400972 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900973 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400974 { {"2001:dg8::6"}, "", {}, EINVAL },
975 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
976 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
977 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
978 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400979 };
980
Erik Klinea1476fb2018-03-04 21:01:56 +0900981 for (unsigned int i = 0; i < arraysize(kTlsTestData); i++) {
982 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -0400983
984 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400985 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400986 fingerprints.push_back(base64Encode(fingerprint));
987 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400988 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900989 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
990 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -0400991
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400992 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -0400993 SCOPED_TRACE(String8::format("test case %d should have passed", i));
994 SCOPED_TRACE(status.toString8());
995 EXPECT_EQ(0, status.exceptionCode());
996 } else {
997 SCOPED_TRACE(String8::format("test case %d should have failed", i));
998 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400999 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -04001000 }
Ben Schwartze7601812017-04-28 16:38:29 -04001001 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001002 // Ensure TLS is disabled before the start of the next test.
1003 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001004 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1005 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001006}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001007
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001008namespace {
1009
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001010void expectNoTestCounterRules() {
1011 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1012 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1013 std::string allRules = Join(runCommand(command), "\n");
1014 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1015 }
1016}
1017
Bernie Innocentif6918262018-06-11 17:37:35 +09001018void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1019 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001020 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1021 path, if1.c_str(), if2.c_str(), pkt, byte));
1022}
1023
Bernie Innocentif6918262018-06-11 17:37:35 +09001024void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001025 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1026 path, if1.c_str(), if2.c_str()));
1027 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1028 path, if2.c_str(), if1.c_str()));
1029}
1030
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001031} // namespace
1032
1033TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001034 expectNoTestCounterRules();
1035
1036 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1037 // disabling tethering. We don't check the return value because these commands will fail if
1038 // tethering is already enabled.
1039 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1040 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1041
1042 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1043 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1044 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1045 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1046 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1047
1048 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1049 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1050 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1051 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1052 // RX is from external to internal, and TX is from internal to external.
1053 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1054 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1055
1056 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1057 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1058
1059 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1060 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1061
1062 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1063 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1064 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1065
1066 PersistableBundle stats;
1067 binder::Status status = mNetd->tetherGetStats(&stats);
1068 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1069
1070 std::vector<int64_t> actual1;
1071 EXPECT_TRUE(stats.getLongVector(String16(extIface1.c_str()), &actual1));
1072 EXPECT_EQ(expected1, actual1);
1073
1074 std::vector<int64_t> actual2;
1075 EXPECT_TRUE(stats.getLongVector(String16(extIface2.c_str()), &actual2));
1076 EXPECT_EQ(expected2, actual2);
1077
1078 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1079 delTetherCounterValues(path, intIface1, extIface1);
1080 delTetherCounterValues(path, intIface2, extIface2);
1081 if (path == IP6TABLES_PATH) {
1082 delTetherCounterValues(path, intIface3, extIface2);
1083 }
1084 }
1085
1086 expectNoTestCounterRules();
1087}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001088
Luke Huang0051a622018-07-23 20:30:16 +08001089namespace {
1090
Luke Huanga5211072018-08-01 23:36:29 +08001091constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1092constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001093
1094static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1095 const char* chainName) {
1096 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1097 return runCommand(command);
1098}
1099
Luke Huanga5211072018-08-01 23:36:29 +08001100bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001101 const std::string& expectedInterface,
1102 const std::string& expectedRule, const char* table) {
1103 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1104 for (const auto& rule : rules) {
1105 if (rule.find(expectedInterface) != std::string::npos) {
1106 if (rule.find(expectedRule) != std::string::npos) {
1107 return true;
1108 }
1109 }
1110 }
1111 return false;
1112}
1113
1114void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001115 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001116 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001117 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001118 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001119 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1120 IdletimerRule, RAW_TABLE));
1121 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001122 ifname, IdletimerRule, MANGLE_TABLE));
1123 }
1124}
1125
1126void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001127 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001128 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001129 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001130 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001131 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1132 IdletimerRule, RAW_TABLE));
1133 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001134 ifname, IdletimerRule, MANGLE_TABLE));
1135 }
1136}
1137
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001138} // namespace
1139
1140TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001141 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1142 // rule in the table. Because we only check the result after calling remove function. We might
1143 // check the actual rule which is removed by our function (maybe compare the results between
1144 // calling function before and after)
1145 binder::Status status;
1146 const struct TestData {
1147 const std::string ifname;
1148 int32_t timeout;
1149 const std::string classLabel;
1150 } idleTestData[] = {
1151 {"wlan0", 1234, "happyday"},
1152 {"rmnet_data0", 4567, "friday"},
1153 };
1154 for (const auto& td : idleTestData) {
1155 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1156 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1157 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1158
1159 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1160 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1161 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1162 }
1163}
1164
Luke Huanga67dd562018-07-17 19:58:25 +08001165namespace {
1166
1167constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1168constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1169
1170void expectStrictSetUidAccept(const int uid) {
1171 std::string uidRule = StringPrintf("owner UID match %u", uid);
1172 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1173 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1174 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1175 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1176 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1177 }
1178}
1179
1180void expectStrictSetUidLog(const int uid) {
1181 static const char logRule[] = "st_penalty_log all";
1182 std::string uidRule = StringPrintf("owner UID match %u", uid);
1183 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1184 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1185 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1186 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1187 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1188 }
1189}
1190
1191void expectStrictSetUidReject(const int uid) {
1192 static const char rejectRule[] = "st_penalty_reject all";
1193 std::string uidRule = StringPrintf("owner UID match %u", uid);
1194 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1195 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1196 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1197 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1198 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1199 }
1200}
1201
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001202} // namespace
1203
1204TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001205 binder::Status status;
1206 int32_t uid = randomUid();
1207
1208 // setUidCleartextPenalty Policy:Log with randomUid
1209 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1210 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1211 expectStrictSetUidLog(uid);
1212
1213 // setUidCleartextPenalty Policy:Accept with randomUid
1214 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1215 expectStrictSetUidAccept(uid);
1216
1217 // setUidCleartextPenalty Policy:Reject with randomUid
1218 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1219 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1220 expectStrictSetUidReject(uid);
1221
1222 // setUidCleartextPenalty Policy:Accept with randomUid
1223 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1224 expectStrictSetUidAccept(uid);
1225
1226 // test wrong policy
1227 int32_t wrongPolicy = -123;
1228 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1229 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1230}
1231
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001232namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001233
Luke Huanga5211072018-08-01 23:36:29 +08001234bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001235 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1236 return (runCommand(cmd.c_str()).size()) ? true : false;
1237}
1238
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001239} // namespace
1240
1241TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001242 binder::Status status;
1243 // use dummy0 for test since it is set ready
1244 static const char testIf[] = "dummy0";
1245 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1246
1247 status = mNetd->clatdStart(testIf);
1248 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1249 EXPECT_TRUE(processExists(clatdName));
1250
1251 mNetd->clatdStop(testIf);
1252 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1253 EXPECT_FALSE(processExists(clatdName));
1254}
Luke Huang457d4702018-08-16 15:39:15 +08001255
1256namespace {
1257
1258bool getIpfwdV4Enable() {
1259 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1260 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1261 EXPECT_TRUE(!result.empty());
1262 int v4Enable = std::stoi(result[0]);
1263 return v4Enable;
1264}
1265
1266bool getIpfwdV6Enable() {
1267 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1268 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1269 EXPECT_TRUE(!result.empty());
1270 int v6Enable = std::stoi(result[0]);
1271 return v6Enable;
1272}
1273
1274void expectIpfwdEnable(bool enable) {
1275 int enableIPv4 = getIpfwdV4Enable();
1276 int enableIPv6 = getIpfwdV6Enable();
1277 EXPECT_EQ(enable, enableIPv4);
1278 EXPECT_EQ(enable, enableIPv6);
1279}
1280
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001281bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001282 std::vector<std::string> rules = listIpRules(ipVersion);
1283 for (const auto& rule : rules) {
1284 if (rule.find(ipfwdRule) != std::string::npos) {
1285 return true;
1286 }
1287 }
1288 return false;
1289}
1290
1291void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1292 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1293
1294 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1295 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1296 }
1297}
1298
1299void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1300 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1301
1302 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1303 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1304 }
1305}
1306
1307} // namespace
1308
1309TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1310 // Netd default enable Ipfwd with requester NetdHwService
1311 const std::string defaultRequester = "NetdHwService";
1312
1313 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1314 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1315 expectIpfwdEnable(false);
1316
1317 bool ipfwdEnabled;
1318 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1319 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1320 EXPECT_FALSE(ipfwdEnabled);
1321
1322 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1323 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1324 expectIpfwdEnable(true);
1325
1326 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1327 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1328 EXPECT_TRUE(ipfwdEnabled);
1329}
1330
1331TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1332 static const char testFromIf[] = "dummy0";
1333 static const char testToIf[] = "dummy0";
1334
1335 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1336 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1337 expectIpfwdRuleExists(testFromIf, testToIf);
1338
1339 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1340 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1341 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001342}
Luke Huang531f5d32018-08-03 15:19:05 +08001343
1344namespace {
1345
1346constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1347constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1348constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1349constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1350constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
1351
1352// TODO: move iptablesTargetsExists and listIptablesRuleByTable to the top.
1353bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1354 const char* chainName, const std::string& expectedTargetA,
1355 const std::string& expectedTargetB) {
1356 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1357 int matchCount = 0;
1358
1359 for (const auto& rule : rules) {
1360 if (rule.find(expectedTargetA) != std::string::npos) {
1361 if (rule.find(expectedTargetB) != std::string::npos) {
1362 matchCount++;
1363 }
1364 }
1365 }
1366 return matchCount == expectedCount;
1367}
1368
1369void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1370 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1371 std::string result = "";
1372
1373 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001374 // Quota value might be decreased while matching packets
1375 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001376}
1377
1378void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1379 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1380 std::string quotaRule = StringPrintf("quota %s", ifname);
1381
1382 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1383 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1384 BANDWIDTH_COSTLY_IF));
1385 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1386 BANDWIDTH_COSTLY_IF));
1387 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1388 BANDWIDTH_COSTLY_IF));
1389 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1390 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1391 }
1392 expectXtQuotaValueEqual(ifname, quotaBytes);
1393}
1394
1395void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1396 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1397 std::string quotaRule = StringPrintf("quota %s", ifname);
1398
1399 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1400 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1401 BANDWIDTH_COSTLY_IF));
1402 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1403 BANDWIDTH_COSTLY_IF));
1404 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1405 BANDWIDTH_COSTLY_IF));
1406 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1407 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1408 }
1409}
1410
1411void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1412 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1413 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1414 std::string alertName = StringPrintf("%sAlert", ifname);
1415
1416 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1417 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1418 }
1419 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1420}
1421
1422void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1423 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1424 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1425
1426 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1427 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1428 }
1429}
1430
1431void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1432 static const char globalAlertRule[] = "quota globalAlert";
1433 static const char globalAlertName[] = "globalAlert";
1434
1435 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1436 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_INPUT, globalAlertRule));
1437 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_OUTPUT, globalAlertRule));
1438 }
1439 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1440}
1441
1442void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1443 std::string uidRule = StringPrintf("owner UID match %u", uid);
1444
1445 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1446 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1447 }
1448}
1449
1450void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1451 std::string uidRule = StringPrintf("owner UID match %u", uid);
1452
1453 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1454 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1455 }
1456}
1457
1458} // namespace
1459
1460TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1461 long testQuotaBytes = 5550;
1462
1463 // Add test physical network
1464 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, "").isOk());
1465 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1466
1467 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1468 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1469 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1470
1471 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1472 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1473 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1474
1475 // Remove test physical network
1476 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1477}
1478
1479TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1480 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001481 // Add test physical network
1482 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, "").isOk());
1483 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001484 // Need to have a prior interface quota set to set an alert
1485 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1486 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1487 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1488 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1489
1490 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1491 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1492 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1493
1494 // Remove interface quota
1495 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1496 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1497 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1498
1499 // Remove test physical network
1500 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1501}
1502
1503TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1504 long testAlertBytes = 2097149;
1505
1506 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1507 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1508 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1509
1510 testAlertBytes = 2097152;
1511 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1512 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1513 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1514}
1515
1516TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1517 SKIP_IF_BPF_SUPPORTED;
1518
1519 int32_t uid = randomUid();
1520 static const char targetReject[] = "REJECT";
1521 static const char targetReturn[] = "RETURN";
1522
1523 // add NaughtyApp
1524 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1525 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1526 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1527
1528 // remove NaughtyApp
1529 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1530 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1531 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1532
1533 // add NiceApp
1534 status = mNetd->bandwidthAddNiceApp(uid);
1535 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1536 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1537
1538 // remove NiceApp
1539 status = mNetd->bandwidthRemoveNiceApp(uid);
1540 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1541 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1542}
Luke Huangb5733d72018-08-21 17:17:19 +08001543
1544namespace {
1545
1546int readIntFromPath(const std::string& path) {
1547 std::string result = "";
1548 EXPECT_TRUE(ReadFileToString(path, &result));
1549 return std::stoi(result);
1550}
1551
1552int getTetherAcceptIPv6Ra(const std::string& ifName) {
1553 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1554 return readIntFromPath(path);
1555}
1556
1557bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1558 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1559 return readIntFromPath(path);
1560}
1561
1562int getTetherIPv6DadTransmits(const std::string& ifName) {
1563 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1564 return readIntFromPath(path);
1565}
1566
1567bool getTetherEnableIPv6(const std::string& ifName) {
1568 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1569 int disableIPv6 = readIntFromPath(path);
1570 return !disableIPv6;
1571}
1572
1573bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1574 for (const auto& iface : ifList) {
1575 if (iface == ifName) {
1576 return true;
1577 }
1578 }
1579 return false;
1580}
1581
1582void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1583 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1584 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1585 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1586 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1587}
1588
1589void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1590 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1591 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1592 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1593 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1594}
1595
1596void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1597 const std::string& ifName) {
1598 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1599}
1600
1601void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1602 const std::string& ifName) {
1603 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1604}
1605
1606void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
1607 const std::vector<std::string>& testDnsAddrs) {
1608 EXPECT_TRUE(dnsList == testDnsAddrs);
1609}
1610
1611} // namespace
1612
1613TEST_F(BinderTest, TetherStartStopStatus) {
1614 std::vector<std::string> noDhcpRange = {};
1615 static const char dnsdName[] = "dnsmasq";
1616
1617 binder::Status status = mNetd->tetherStart(noDhcpRange);
1618 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1619 EXPECT_TRUE(processExists(dnsdName));
1620
1621 bool tetherEnabled;
1622 status = mNetd->tetherIsEnabled(&tetherEnabled);
1623 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1624 EXPECT_TRUE(tetherEnabled);
1625
1626 status = mNetd->tetherStop();
1627 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1628 EXPECT_FALSE(processExists(dnsdName));
1629
1630 status = mNetd->tetherIsEnabled(&tetherEnabled);
1631 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1632 EXPECT_FALSE(tetherEnabled);
1633}
1634
1635TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
1636 // TODO: verify if dnsmasq update interface successfully
1637
1638 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
1639 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1640 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
1641
1642 std::vector<std::string> ifList;
1643 status = mNetd->tetherInterfaceList(&ifList);
1644 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1645 expectTetherInterfaceExists(ifList, sTun.name());
1646
1647 status = mNetd->tetherInterfaceRemove(sTun.name());
1648 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1649 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
1650
1651 status = mNetd->tetherInterfaceList(&ifList);
1652 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1653 expectTetherInterfaceNotExists(ifList, sTun.name());
1654}
1655
1656TEST_F(BinderTest, TetherDnsSetList) {
1657 // TODO: verify if dnsmasq update dns successfully
1658 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
1659
1660 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
1661 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1662
1663 std::vector<std::string> dnsList;
1664 status = mNetd->tetherDnsList(&dnsList);
1665 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1666 expectTetherDnsListEquals(dnsList, testDnsAddrs);
1667}