blob: 5aafec872a863245c8f4aab998b3860714758b26 [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>
Luke Huang528af602018-08-29 19:06:05 +080020#include <chrono>
Robin Leeb8087362016-03-30 18:43:08 +010021#include <cinttypes>
Luke Huang528af602018-08-29 19:06:05 +080022#include <condition_variable>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090023#include <cstdint>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090024#include <cstdio>
25#include <cstdlib>
Luke Huang528af602018-08-29 19:06:05 +080026#include <mutex>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090027#include <set>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090028#include <vector>
29
Luke Huangf7782042018-08-08 13:13:04 +080030#include <dirent.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090031#include <fcntl.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090032#include <ifaddrs.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090033#include <linux/if.h>
34#include <linux/if_tun.h>
Benedict Wonga450e722018-05-07 10:29:02 -070035#include <net/if.h>
Luke Huangf7782042018-08-08 13:13:04 +080036#include <netdb.h>
37#include <netinet/in.h>
Ben Schwartze7601812017-04-28 16:38:29 -040038#include <openssl/base64.h>
Luke Huangf7782042018-08-08 13:13:04 +080039#include <sys/socket.h>
40#include <sys/types.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090041
Luke Huang531f5d32018-08-03 15:19:05 +080042#include <android-base/file.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090043#include <android-base/macros.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090044#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090045#include <android-base/strings.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070046#include <bpf/BpfUtils.h>
Robin Leeb8087362016-03-30 18:43:08 +010047#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090048#include <gtest/gtest.h>
49#include <logwrap/logwrap.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090050#include <netutils/ifc.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090051
Nathan Harold21299f72018-03-16 20:13:03 -070052#include "InterfaceController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090053#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090054#include "Stopwatch.h"
Luke Huang528af602018-08-29 19:06:05 +080055#include "TestUnsolService.h"
Nathan Harold21299f72018-03-16 20:13:03 -070056#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090057#include "android/net/INetd.h"
58#include "binder/IServiceManager.h"
Nathan Harold21299f72018-03-16 20:13:03 -070059#include "netdutils/Syscalls.h"
Mike Yu5ae61542018-10-19 22:11:43 +080060#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090061
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090062#define IP_PATH "/system/bin/ip"
63#define IP6TABLES_PATH "/system/bin/ip6tables"
64#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090065#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080066#define RAW_TABLE "raw"
67#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080068#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090069#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090070
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090071namespace binder = android::binder;
72namespace netdutils = android::netdutils;
73
74using android::IBinder;
75using android::IServiceManager;
76using android::sp;
77using android::String16;
78using android::String8;
79using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080080using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090081using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090082using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080083using android::base::Trim;
Chenbo Fengf5663d82018-11-08 16:10:48 -080084using android::base::WriteStringToFile;
Chenbo Feng837ddfc2018-05-08 13:45:08 -070085using android::bpf::hasBpfSupport;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090086using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080087using android::net::InterfaceConfigurationParcel;
88using android::net::InterfaceController;
Luke Huangcaebcbb2018-09-27 20:37:14 +080089using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090090using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090091using android::net::UidRangeParcel;
Nathan Harold21299f72018-03-16 20:13:03 -070092using android::net::XfrmController;
Luke Huangf7782042018-08-08 13:13:04 +080093using android::netdutils::sSyscalls;
Robin Leeb8087362016-03-30 18:43:08 +010094
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090095#define SKIP_IF_BPF_SUPPORTED \
96 do { \
97 if (hasBpfSupport()) return; \
98 } while (0)
Chenbo Feng837ddfc2018-05-08 13:45:08 -070099
Robin Leeb8087362016-03-30 18:43:08 +0100100static const char* IP_RULE_V4 = "-4";
101static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900102static const int TEST_NETID1 = 65501;
103static const int TEST_NETID2 = 65502;
104constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900105
Benedict Wongb2daefb2017-12-06 22:05:46 -0800106static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
107static const std::string ESP_ALLOW_RULE("esp");
108
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900109class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900110 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900111 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900112 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900113 sp<IBinder> binder = sm->getService(String16("netd"));
114 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900115 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900116 }
117 }
118
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900119 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900120 ASSERT_NE(nullptr, mNetd.get());
121 }
122
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900123 void TearDown() override {
124 mNetd->networkDestroy(TEST_NETID1);
125 mNetd->networkDestroy(TEST_NETID2);
126 }
127
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900128 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700129
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900130 // Static because setting up the tun interface takes about 40ms.
131 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900132 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900133 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900134 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900135 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900136 }
137
138 static void TearDownTestCase() {
139 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900140 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900141 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900142 }
143
144 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900145
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900146 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900147 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900148 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900149 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900150};
151
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900152TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900153TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900154
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900155class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900156 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700157 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900158 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900159 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900160 }
161
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900162 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900163 std::string mName;
164};
165
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900166TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900167 TimedOperation t("isAlive RPC");
168 bool isAlive = false;
169 mNetd->isAlive(&isAlive);
170 ASSERT_TRUE(isAlive);
171}
172
173static int randomUid() {
174 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
175}
176
Robin Leeb8087362016-03-30 18:43:08 +0100177static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900178 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900179 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
180 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900181 perror("popen");
182 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900183 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900184
185 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100186 size_t bufsize = 0;
187 ssize_t linelen = 0;
188 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900189 lines.push_back(std::string(line, linelen));
190 free(line);
191 line = nullptr;
192 }
193
194 pclose(f);
195 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900196}
197
Robin Leeb8087362016-03-30 18:43:08 +0100198static std::vector<std::string> listIpRules(const char *ipVersion) {
199 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
200 return runCommand(command);
201}
202
203static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900204 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100205 return runCommand(command);
206}
207
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900208static int iptablesRuleLineLength(const char *binary, const char *chainName) {
209 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900210}
211
Benedict Wongb2daefb2017-12-06 22:05:46 -0800212static bool iptablesRuleExists(const char *binary,
213 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900214 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800215 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900216 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800217 if(rule.find(expectedRule) != std::string::npos) {
218 return true;
219 }
220 }
221 return false;
222}
223
224static bool iptablesNoSocketAllowRuleExists(const char *chainName){
225 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
226 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
227}
228
229static bool iptablesEspAllowRuleExists(const char *chainName){
230 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
231 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
232}
233
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900234TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700235 SKIP_IF_BPF_SUPPORTED;
236
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900237 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
238 const int kNumUids = 500;
239 std::vector<int32_t> noUids(0);
240 std::vector<int32_t> uids(kNumUids);
241 for (int i = 0; i < kNumUids; i++) {
242 uids[i] = randomUid();
243 }
244
245 bool ret;
246 {
247 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900248 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900249 }
250 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800251 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
252 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
253 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
254 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900255 {
256 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900257 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900258 }
259 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900260 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
261 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900262
263 {
264 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900265 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900266 }
267 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900268 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
269 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800270 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
271 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900272
273 {
274 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900275 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900276 }
277 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900278 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
279 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900280
281 // Check that the call fails if iptables returns an error.
282 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900283 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900284 EXPECT_EQ(false, ret);
285}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900286
Benedict Wong319f17e2018-05-15 17:06:44 -0700287TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700288 const struct TestData {
289 const std::string family;
290 const std::string deviceName;
291 const std::string localAddress;
292 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800293 int32_t iKey;
294 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700295 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800296 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700297 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
298 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
299 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800300 };
301
Sehee Park8659b8d2018-11-16 10:53:16 +0900302 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700303 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800304
305 binder::Status status;
306
Benedict Wong319f17e2018-05-15 17:06:44 -0700307 // Create Tunnel Interface.
308 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700309 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800310 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
311
Benedict Wonga450e722018-05-07 10:29:02 -0700312 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900313 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700314
Benedict Wong319f17e2018-05-15 17:06:44 -0700315 // Update Tunnel Interface.
316 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700317 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800318 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
319
Benedict Wong319f17e2018-05-15 17:06:44 -0700320 // Remove Tunnel Interface.
321 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800322 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700323
324 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900325 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800326 }
327}
328
Benedict Wong1cb73df2018-12-03 00:54:14 -0800329TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
330 android::base::unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
331 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
332
333 int sockOptVal = UDP_ENCAP_ESPINUDP;
334 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
335
336 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
337 EXPECT_TRUE(res.isOk());
338
339 struct stat info;
340 EXPECT_EQ(0, fstat(sockFd.get(), &info));
341 EXPECT_EQ(1001, (int) info.st_uid);
342}
343
Nathan Harold2deff322018-05-10 14:03:48 -0700344// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
345// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
346#if INTPTR_MAX != INT32_MAX
Benedict Wonga04ffa72018-05-09 21:42:42 -0700347static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
348 static_cast<int>(android::net::XfrmDirection::OUT)};
349static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
350
Nathan Harold21299f72018-03-16 20:13:03 -0700351#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
352 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900353bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Nathan Harold21299f72018-03-16 20:13:03 -0700354 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
355 SCOPED_TRACE(status);
356 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
357
358 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700359 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700360 SCOPED_TRACE(status);
361 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
362
363 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700364 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
365 0xD00D, 0xE00D, false)
366 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700367}
368
Benedict Wonga04ffa72018-05-09 21:42:42 -0700369TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
370 binder::Status status;
371
372 // Repeat to ensure cleanup and recreation works correctly
373 for (int i = 0; i < 2; i++) {
374 for (int direction : XFRM_DIRECTIONS) {
375 for (int addrFamily : ADDRESS_FAMILIES) {
376 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700377 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700378 EXPECT_TRUE(status.isOk())
379 << " family: " << addrFamily << " direction: " << direction;
380 }
381 }
382
383 // Cleanup
384 for (int direction : XFRM_DIRECTIONS) {
385 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700386 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700387 EXPECT_TRUE(status.isOk());
388 }
389 }
390 }
391}
392
393TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
394 binder::Status status;
395
396 // Repeat to ensure cleanup and recreation works correctly
397 for (int i = 0; i < 2; i++) {
398 for (int direction : XFRM_DIRECTIONS) {
399 for (int addrFamily : ADDRESS_FAMILIES) {
400 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700401 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700402 EXPECT_TRUE(status.isOk())
403 << " family: " << addrFamily << " direction: " << direction;
404 }
405 }
406
407 // Cleanup
408 for (int direction : XFRM_DIRECTIONS) {
409 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700410 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700411 EXPECT_TRUE(status.isOk());
412 }
413 }
414 }
415}
416
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900417TEST_F(BinderTest, XfrmControllerInit) {
Nathan Harold21299f72018-03-16 20:13:03 -0700418 netdutils::Status status;
419 status = XfrmController::Init();
420 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700421
422 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
423 // feature.
424 if (status.code() == EOPNOTSUPP) return;
425
Nathan Harold21299f72018-03-16 20:13:03 -0700426 ASSERT_TRUE(status.ok());
427
428 int32_t spi = 0;
429
430 ASSERT_TRUE(allocateIpSecResources(true, &spi));
431 ASSERT_TRUE(allocateIpSecResources(false, &spi));
432
433 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700434 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700435 ASSERT_TRUE(allocateIpSecResources(true, &spi));
436
437 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700438 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700439 SCOPED_TRACE(status);
440 ASSERT_TRUE(status.ok());
441
Benedict Wonga450e722018-05-07 10:29:02 -0700442 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700443 SCOPED_TRACE(status);
444 ASSERT_TRUE(status.ok());
445
446 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700447 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700448}
Nathan Harold2deff322018-05-10 14:03:48 -0700449#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700450
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900451static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900452 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900453
454 // Output looks like this:
455 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900456 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900457 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900458 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900459 //
460 // or:
461 //
462 // Chain bw_data_saver (1 references)
463 // target prot opt source destination
464 // ... possibly connectivity critical packet rules here ...
465 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900466
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900467 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900468
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900469 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
470 // Data saver disabled.
471 return 0;
472 }
473
474 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
475
476 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
477 // Data saver enabled.
478 return 1;
479 }
480
481 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900482}
483
484bool enableDataSaver(sp<INetd>& netd, bool enable) {
485 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
486 bool ret;
487 netd->bandwidthEnableDataSaver(enable, &ret);
488 return ret;
489}
490
491int getDataSaverState() {
492 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
493 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
494 EXPECT_EQ(enabled4, enabled6);
495 EXPECT_NE(-1, enabled4);
496 EXPECT_NE(-1, enabled6);
497 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
498 return -1;
499 }
500 return enabled6;
501}
502
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900503TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900504 const int wasEnabled = getDataSaverState();
505 ASSERT_NE(-1, wasEnabled);
506
507 if (wasEnabled) {
508 ASSERT_TRUE(enableDataSaver(mNetd, false));
509 EXPECT_EQ(0, getDataSaverState());
510 }
511
512 ASSERT_TRUE(enableDataSaver(mNetd, false));
513 EXPECT_EQ(0, getDataSaverState());
514
515 ASSERT_TRUE(enableDataSaver(mNetd, true));
516 EXPECT_EQ(1, getDataSaverState());
517
518 ASSERT_TRUE(enableDataSaver(mNetd, true));
519 EXPECT_EQ(1, getDataSaverState());
520
521 if (!wasEnabled) {
522 ASSERT_TRUE(enableDataSaver(mNetd, false));
523 EXPECT_EQ(0, getDataSaverState());
524 }
525}
Robin Leeb8087362016-03-30 18:43:08 +0100526
Luke Huang94658ac2018-10-18 19:35:12 +0900527static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
528 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100529 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100530 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100531 std::vector<std::string> rules = listIpRules(ipVersion);
532
533 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900534 std::string suffix =
535 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900536 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800537 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100538 return true;
539 }
540 }
541 return false;
542}
543
Luke Huang94658ac2018-10-18 19:35:12 +0900544static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
545 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100546 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
547 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
548 EXPECT_EQ(existsIp4, existsIp6);
549 return existsIp4;
550}
551
Luke Huang94658ac2018-10-18 19:35:12 +0900552namespace {
553
554UidRangeParcel makeUidRangeParcel(int start, int stop) {
555 UidRangeParcel res;
556 res.start = start;
557 res.stop = stop;
558
559 return res;
560}
561
562} // namespace
563
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900564TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800565 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
566 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
567 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900568 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
569 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900570
571 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
572 EXPECT_EQ(EBUSY,
573 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
574
575 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
576 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
577 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800578 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900579}
580
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900581TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900582 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
583
cken67cd14c2018-12-05 17:26:59 +0900584 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
585 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900586 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
587
Luke Huang94658ac2018-10-18 19:35:12 +0900588 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
589 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
590 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900591 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
592
593 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
594
595 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
596 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
597 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
598 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
599
600 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
601 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
602 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
603 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
604
605 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
606}
607
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900608TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100609 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100610
Luke Huang94658ac2018-10-18 19:35:12 +0900611 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
612 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100613
614 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
615 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
616
617 // Create two valid rules.
618 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
619 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
620 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
621 for (auto const& range : uidRanges) {
622 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
623 }
624
625 // Remove the rules.
626 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
627 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
628 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
629 for (auto const& range : uidRanges) {
630 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
631 }
632
633 // Fail to remove the rules a second time after they are already deleted.
634 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
635 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
636 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
637
638 // All rules should be the same as before.
639 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
640 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
641}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900642
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900643// Create a socket pair that isLoopbackSocket won't think is local.
644void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900645 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900646 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900647 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
648
649 socklen_t addrlen = sizeof(server6);
650 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
651 ASSERT_EQ(0, listen(*serverSocket, 10));
652
Bernie Innocentif6918262018-06-11 17:37:35 +0900653 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900654 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900655 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900656 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
657 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
658
Bernie Innocentif6918262018-06-11 17:37:35 +0900659 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900660 ASSERT_NE(-1, *acceptedSocket);
661
662 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
663}
664
665void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
666 char buf[4096];
667 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
668 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
669 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
670}
671
672void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
673 // Check that the client socket was closed with ECONNABORTED.
674 int ret = write(clientSocket, "foo", sizeof("foo"));
675 int err = errno;
676 EXPECT_EQ(-1, ret);
677 EXPECT_EQ(ECONNABORTED, err);
678
679 // Check that it sent a RST to the server.
680 ret = write(acceptedSocket, "foo", sizeof("foo"));
681 err = errno;
682 EXPECT_EQ(-1, ret);
683 EXPECT_EQ(ECONNRESET, err);
684}
685
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900686TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900687 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900688 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900689
690 // Pick a random UID in the system UID range.
691 constexpr int baseUid = AID_APP - 2000;
692 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
693 int uid = baseUid + 500 + arc4random_uniform(1000);
694 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
695
696 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900697 std::vector<UidRangeParcel> uidRanges = {
698 makeUidRangeParcel(baseUid + 42, baseUid + 449),
699 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
700 makeUidRangeParcel(baseUid + 498, uid - 1),
701 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900702 };
703 // A skip list that doesn't contain UID.
704 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
705
706 // Close sockets. Our test socket should be intact.
707 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
708 checkSocketpairOpen(clientSocket, acceptedSocket);
709
710 // UID ranges that do contain uid.
711 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900712 makeUidRangeParcel(baseUid + 42, baseUid + 449),
713 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
714 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900715 };
716 // Add uid to the skip list.
717 skipUids.push_back(uid);
718
719 // Close sockets. Our test socket should still be intact because it's in the skip list.
720 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
721 checkSocketpairOpen(clientSocket, acceptedSocket);
722
723 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
724 skipUids.resize(skipUids.size() - 1);
725 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
726 checkSocketpairClosed(clientSocket, acceptedSocket);
727
728 close(clientSocket);
729 close(serverSocket);
730 close(acceptedSocket);
731}
Erik Klinecc4f2732016-08-03 11:24:27 +0900732
733namespace {
734
735int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
736 if (buf == nullptr) return -1;
737
738 int prefixLength = 0;
739 bool endOfContiguousBits = false;
740 for (unsigned int i = 0; i < buflen; i++) {
741 const uint8_t value = buf[i];
742
743 // Bad bit sequence: check for a contiguous set of bits from the high
744 // end by verifying that the inverted value + 1 is a power of 2
745 // (power of 2 iff. (v & (v - 1)) == 0).
746 const uint8_t inverse = ~value + 1;
747 if ((inverse & (inverse - 1)) != 0) return -1;
748
749 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
750
751 // Bogus netmask.
752 if (endOfContiguousBits && value != 0) return -1;
753
754 if (value != 0xff) endOfContiguousBits = true;
755 }
756
757 return prefixLength;
758}
759
760template<typename T>
761int netmaskToPrefixLength(const T *p) {
762 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
763}
764
765
766static bool interfaceHasAddress(
767 const std::string &ifname, const char *addrString, int prefixLength) {
768 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900769
770 const struct addrinfo hints = {
771 .ai_flags = AI_NUMERICHOST,
772 .ai_family = AF_UNSPEC,
773 .ai_socktype = SOCK_DGRAM,
774 };
775 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
776 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
777 return false;
778 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900779 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900780
781 struct ifaddrs *ifaddrsList = nullptr;
782 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
783
784 if (getifaddrs(&ifaddrsList) != 0) {
785 return false;
786 }
787
788 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
789 if (std::string(addr->ifa_name) != ifname ||
790 addr->ifa_addr == nullptr ||
791 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
792 continue;
793 }
794
795 switch (addr->ifa_addr->sa_family) {
796 case AF_INET: {
797 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
798 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
799 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
800 continue;
801 }
802
803 if (prefixLength < 0) return true; // not checking prefix lengths
804
805 if (addr->ifa_netmask == nullptr) return false;
806 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
807 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
808 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
809 }
810 case AF_INET6: {
811 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
812 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
813 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
814 continue;
815 }
816
817 if (prefixLength < 0) return true; // not checking prefix lengths
818
819 if (addr->ifa_netmask == nullptr) return false;
820 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
821 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
822 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
823 }
824 default:
825 // Cannot happen because we have already screened for matching
826 // address families at the top of each iteration.
827 continue;
828 }
829 }
830
831 return false;
832}
833
834} // namespace
835
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900836TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900837 static const struct TestData {
838 const char *addrString;
839 const int prefixLength;
840 const bool expectSuccess;
841 } kTestData[] = {
842 { "192.0.2.1", 24, true },
843 { "192.0.2.2", 25, true },
844 { "192.0.2.3", 32, true },
845 { "192.0.2.4", 33, false },
846 { "192.not.an.ip", 24, false },
847 { "2001:db8::1", 64, true },
848 { "2001:db8::2", 65, true },
849 { "2001:db8::3", 128, true },
850 { "2001:db8::4", 129, false },
851 { "foo:bar::bad", 64, false },
852 };
853
Sehee Park8659b8d2018-11-16 10:53:16 +0900854 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900855 const auto &td = kTestData[i];
856
857 // [1.a] Add the address.
858 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900859 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900860 if (td.expectSuccess) {
861 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
862 } else {
863 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
864 ASSERT_NE(0, status.serviceSpecificErrorCode());
865 }
866
867 // [1.b] Verify the addition meets the expectation.
868 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900869 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900870 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900871 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900872 }
873
874 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900875 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900876 if (td.expectSuccess) {
877 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
878 } else {
879 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
880 ASSERT_NE(0, status.serviceSpecificErrorCode());
881 }
882
883 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900884 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900885 }
886}
Erik Kline55b06f82016-07-04 09:57:18 +0900887
Erik Kline38e51f12018-09-06 20:14:44 +0900888TEST_F(BinderTest, GetProcSysNet) {
889 const char LOOPBACK[] = "lo";
890 static const struct {
891 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900892 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900893 const char* ifname;
894 const char* parameter;
895 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900896 const int expectedReturnCode;
897 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900898 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
899 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
900 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
901 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
902 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
903 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
904 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900905 };
906
Sehee Park8659b8d2018-11-16 10:53:16 +0900907 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900908 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900909
Erik Kline38e51f12018-09-06 20:14:44 +0900910 std::string value;
911 const binder::Status status =
912 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
913
914 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900915 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900916 EXPECT_EQ(0, status.exceptionCode());
917 EXPECT_EQ(0, status.serviceSpecificErrorCode());
918 EXPECT_EQ(td.expectedValue, value);
919 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900920 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900921 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
922 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
923 }
924 }
925}
926
927TEST_F(BinderTest, SetProcSysNet) {
928 static const struct {
929 const int ipversion;
930 const int which;
931 const char* ifname;
932 const char* parameter;
933 const char* value;
934 const int expectedReturnCode;
935 } kTestData[] = {
936 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
937 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
938 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
939 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
940 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
941 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
942 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
943 };
944
Sehee Park8659b8d2018-11-16 10:53:16 +0900945 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900946 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900947 const binder::Status status =
948 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900949
950 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900951 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900952 EXPECT_EQ(0, status.exceptionCode());
953 EXPECT_EQ(0, status.serviceSpecificErrorCode());
954 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900955 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900956 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
957 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
958 }
959 }
960}
Ben Schwartze7601812017-04-28 16:38:29 -0400961
Erik Kline38e51f12018-09-06 20:14:44 +0900962TEST_F(BinderTest, GetSetProcSysNet) {
963 const int ipversion = INetd::IPV6;
964 const int category = INetd::NEIGH;
965 const std::string& tun = sTun.name();
966 const std::string parameter("ucast_solicit");
967
968 std::string value{};
969 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
970 EXPECT_FALSE(value.empty());
971 const int ival = std::stoi(value);
972 EXPECT_GT(ival, 0);
973 // Try doubling the parameter value (always best!).
974 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
975 .isOk());
976 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
977 EXPECT_EQ(2 * ival, std::stoi(value));
978 // Try resetting the parameter.
979 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
980 .isOk());
981 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
982 EXPECT_EQ(ival, std::stoi(value));
983}
984
Ben Schwartze7601812017-04-28 16:38:29 -0400985static std::string base64Encode(const std::vector<uint8_t>& input) {
986 size_t out_len;
987 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
988 // out_len includes the trailing NULL.
989 uint8_t output_bytes[out_len];
990 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
991 return std::string(reinterpret_cast<char*>(output_bytes));
992}
993
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900994TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900995 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400996 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400997 std::vector<uint8_t> short_fp(1);
998 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
999 std::vector<std::string> test_domains;
1000 std::vector<int> test_params = { 300, 25, 8, 8 };
1001 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -04001002 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001003 const std::vector<std::string> servers;
1004 const std::string tlsName;
1005 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -04001006 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +09001007 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001008 { {"192.0.2.1"}, "", {}, 0 },
1009 { {"2001:db8::2"}, "host.name", {}, 0 },
1010 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
1011 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +09001012 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001013 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +09001014 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001015 { {"2001:dg8::6"}, "", {}, EINVAL },
1016 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
1017 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
1018 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
1019 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -04001020 };
1021
Sehee Park8659b8d2018-11-16 10:53:16 +09001022 for (size_t i = 0; i < std::size(kTlsTestData); i++) {
Erik Klinea1476fb2018-03-04 21:01:56 +09001023 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -04001024
1025 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001026 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -04001027 fingerprints.push_back(base64Encode(fingerprint));
1028 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001029 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001030 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
1031 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -04001032
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001033 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +09001034 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Ben Schwartze7601812017-04-28 16:38:29 -04001035 SCOPED_TRACE(status.toString8());
1036 EXPECT_EQ(0, status.exceptionCode());
1037 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +09001038 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Ben Schwartze7601812017-04-28 16:38:29 -04001039 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001040 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -04001041 }
Ben Schwartze7601812017-04-28 16:38:29 -04001042 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001043 // Ensure TLS is disabled before the start of the next test.
1044 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001045 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1046 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001047}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001048
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001049namespace {
1050
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001051void expectNoTestCounterRules() {
1052 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1053 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1054 std::string allRules = Join(runCommand(command), "\n");
1055 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1056 }
1057}
1058
Bernie Innocentif6918262018-06-11 17:37:35 +09001059void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1060 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001061 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1062 path, if1.c_str(), if2.c_str(), pkt, byte));
1063}
1064
Bernie Innocentif6918262018-06-11 17:37:35 +09001065void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001066 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1067 path, if1.c_str(), if2.c_str()));
1068 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1069 path, if2.c_str(), if1.c_str()));
1070}
1071
Luke Huangcaebcbb2018-09-27 20:37:14 +08001072std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1073 const std::string& iface) {
1074 for (auto& stats : statsVec) {
1075 if (stats.iface == iface) {
1076 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1077 }
1078 }
1079 return {};
1080}
1081
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001082} // namespace
1083
1084TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001085 expectNoTestCounterRules();
1086
1087 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1088 // disabling tethering. We don't check the return value because these commands will fail if
1089 // tethering is already enabled.
1090 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1091 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1092
1093 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1094 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1095 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1096 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1097 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1098
1099 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1100 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1101 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1102 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1103 // RX is from external to internal, and TX is from internal to external.
1104 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1105 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1106
1107 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1108 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1109
1110 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1111 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1112
1113 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1114 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1115 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1116
Luke Huangcaebcbb2018-09-27 20:37:14 +08001117 std::vector<TetherStatsParcel> statsVec;
1118 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001119 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1120
Luke Huangcaebcbb2018-09-27 20:37:14 +08001121 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001122
Luke Huangcaebcbb2018-09-27 20:37:14 +08001123 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001124
1125 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1126 delTetherCounterValues(path, intIface1, extIface1);
1127 delTetherCounterValues(path, intIface2, extIface2);
1128 if (path == IP6TABLES_PATH) {
1129 delTetherCounterValues(path, intIface3, extIface2);
1130 }
1131 }
1132
1133 expectNoTestCounterRules();
1134}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001135
Luke Huang0051a622018-07-23 20:30:16 +08001136namespace {
1137
Luke Huanga5211072018-08-01 23:36:29 +08001138constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1139constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001140
1141static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1142 const char* chainName) {
1143 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1144 return runCommand(command);
1145}
1146
Luke Huang19b49c52018-10-22 12:12:05 +09001147// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001148bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001149 const std::string& expectedInterface,
1150 const std::string& expectedRule, const char* table) {
1151 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1152 for (const auto& rule : rules) {
1153 if (rule.find(expectedInterface) != std::string::npos) {
1154 if (rule.find(expectedRule) != std::string::npos) {
1155 return true;
1156 }
1157 }
1158 }
1159 return false;
1160}
1161
1162void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001163 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001164 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001165 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001166 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001167 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1168 IdletimerRule, RAW_TABLE));
1169 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001170 ifname, IdletimerRule, MANGLE_TABLE));
1171 }
1172}
1173
1174void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001175 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001176 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001177 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001178 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001179 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1180 IdletimerRule, RAW_TABLE));
1181 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001182 ifname, IdletimerRule, MANGLE_TABLE));
1183 }
1184}
1185
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001186} // namespace
1187
1188TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001189 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1190 // rule in the table. Because we only check the result after calling remove function. We might
1191 // check the actual rule which is removed by our function (maybe compare the results between
1192 // calling function before and after)
1193 binder::Status status;
1194 const struct TestData {
1195 const std::string ifname;
1196 int32_t timeout;
1197 const std::string classLabel;
1198 } idleTestData[] = {
1199 {"wlan0", 1234, "happyday"},
1200 {"rmnet_data0", 4567, "friday"},
1201 };
1202 for (const auto& td : idleTestData) {
1203 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1204 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1205 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1206
1207 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1208 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1209 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1210 }
1211}
1212
Luke Huanga67dd562018-07-17 19:58:25 +08001213namespace {
1214
1215constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1216constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1217
1218void expectStrictSetUidAccept(const int uid) {
1219 std::string uidRule = StringPrintf("owner UID match %u", uid);
1220 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1221 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1222 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1223 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1224 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1225 }
1226}
1227
1228void expectStrictSetUidLog(const int uid) {
1229 static const char logRule[] = "st_penalty_log all";
1230 std::string uidRule = StringPrintf("owner UID match %u", uid);
1231 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1232 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1233 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1234 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1235 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1236 }
1237}
1238
1239void expectStrictSetUidReject(const int uid) {
1240 static const char rejectRule[] = "st_penalty_reject all";
1241 std::string uidRule = StringPrintf("owner UID match %u", uid);
1242 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1243 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1244 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1245 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1246 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1247 }
1248}
1249
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001250} // namespace
1251
1252TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001253 binder::Status status;
1254 int32_t uid = randomUid();
1255
1256 // setUidCleartextPenalty Policy:Log with randomUid
1257 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1258 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1259 expectStrictSetUidLog(uid);
1260
1261 // setUidCleartextPenalty Policy:Accept with randomUid
1262 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1263 expectStrictSetUidAccept(uid);
1264
1265 // setUidCleartextPenalty Policy:Reject with randomUid
1266 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1267 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1268 expectStrictSetUidReject(uid);
1269
1270 // setUidCleartextPenalty Policy:Accept with randomUid
1271 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1272 expectStrictSetUidAccept(uid);
1273
1274 // test wrong policy
1275 int32_t wrongPolicy = -123;
1276 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1277 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1278}
1279
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001280namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001281
Luke Huanga5211072018-08-01 23:36:29 +08001282bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001283 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1284 return (runCommand(cmd.c_str()).size()) ? true : false;
1285}
1286
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001287} // namespace
1288
1289TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001290 binder::Status status;
1291 // use dummy0 for test since it is set ready
1292 static const char testIf[] = "dummy0";
1293 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1294
1295 status = mNetd->clatdStart(testIf);
1296 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1297 EXPECT_TRUE(processExists(clatdName));
1298
1299 mNetd->clatdStop(testIf);
1300 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1301 EXPECT_FALSE(processExists(clatdName));
1302}
Luke Huang457d4702018-08-16 15:39:15 +08001303
1304namespace {
1305
1306bool getIpfwdV4Enable() {
1307 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1308 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1309 EXPECT_TRUE(!result.empty());
1310 int v4Enable = std::stoi(result[0]);
1311 return v4Enable;
1312}
1313
1314bool getIpfwdV6Enable() {
1315 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1316 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1317 EXPECT_TRUE(!result.empty());
1318 int v6Enable = std::stoi(result[0]);
1319 return v6Enable;
1320}
1321
1322void expectIpfwdEnable(bool enable) {
1323 int enableIPv4 = getIpfwdV4Enable();
1324 int enableIPv6 = getIpfwdV6Enable();
1325 EXPECT_EQ(enable, enableIPv4);
1326 EXPECT_EQ(enable, enableIPv6);
1327}
1328
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001329bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001330 std::vector<std::string> rules = listIpRules(ipVersion);
1331 for (const auto& rule : rules) {
1332 if (rule.find(ipfwdRule) != std::string::npos) {
1333 return true;
1334 }
1335 }
1336 return false;
1337}
1338
1339void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1340 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1341
1342 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1343 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1344 }
1345}
1346
1347void expectIpfwdRuleNotExists(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_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1352 }
1353}
1354
1355} // namespace
1356
1357TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1358 // Netd default enable Ipfwd with requester NetdHwService
1359 const std::string defaultRequester = "NetdHwService";
1360
1361 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1362 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1363 expectIpfwdEnable(false);
1364
1365 bool ipfwdEnabled;
1366 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1367 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1368 EXPECT_FALSE(ipfwdEnabled);
1369
1370 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1371 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1372 expectIpfwdEnable(true);
1373
1374 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1375 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1376 EXPECT_TRUE(ipfwdEnabled);
1377}
1378
1379TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1380 static const char testFromIf[] = "dummy0";
1381 static const char testToIf[] = "dummy0";
1382
1383 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1384 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1385 expectIpfwdRuleExists(testFromIf, testToIf);
1386
1387 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1388 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1389 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001390}
Luke Huang531f5d32018-08-03 15:19:05 +08001391
1392namespace {
1393
1394constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1395constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1396constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1397constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1398constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001399constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001400
Luke Huang19b49c52018-10-22 12:12:05 +09001401// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1402// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001403bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1404 const char* chainName, const std::string& expectedTargetA,
1405 const std::string& expectedTargetB) {
1406 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1407 int matchCount = 0;
1408
1409 for (const auto& rule : rules) {
1410 if (rule.find(expectedTargetA) != std::string::npos) {
1411 if (rule.find(expectedTargetB) != std::string::npos) {
1412 matchCount++;
1413 }
1414 }
1415 }
1416 return matchCount == expectedCount;
1417}
1418
1419void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1420 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1421 std::string result = "";
1422
1423 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001424 // Quota value might be decreased while matching packets
1425 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001426}
1427
1428void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1429 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1430 std::string quotaRule = StringPrintf("quota %s", ifname);
1431
1432 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1433 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1434 BANDWIDTH_COSTLY_IF));
1435 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1436 BANDWIDTH_COSTLY_IF));
1437 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1438 BANDWIDTH_COSTLY_IF));
1439 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1440 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1441 }
1442 expectXtQuotaValueEqual(ifname, quotaBytes);
1443}
1444
1445void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1446 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1447 std::string quotaRule = StringPrintf("quota %s", ifname);
1448
1449 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1450 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1451 BANDWIDTH_COSTLY_IF));
1452 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1453 BANDWIDTH_COSTLY_IF));
1454 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1455 BANDWIDTH_COSTLY_IF));
1456 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1457 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1458 }
1459}
1460
1461void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1462 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1463 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1464 std::string alertName = StringPrintf("%sAlert", ifname);
1465
1466 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1467 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1468 }
1469 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1470}
1471
1472void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1473 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1474 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1475
1476 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1477 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1478 }
1479}
1480
1481void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1482 static const char globalAlertRule[] = "quota globalAlert";
1483 static const char globalAlertName[] = "globalAlert";
1484
1485 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001486 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001487 }
1488 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1489}
1490
1491void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1492 std::string uidRule = StringPrintf("owner UID match %u", uid);
1493
1494 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1495 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1496 }
1497}
1498
1499void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1500 std::string uidRule = StringPrintf("owner UID match %u", uid);
1501
1502 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1503 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1504 }
1505}
1506
1507} // namespace
1508
1509TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1510 long testQuotaBytes = 5550;
1511
1512 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001513 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001514 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1515
1516 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1517 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1518 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1519
1520 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1521 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1522 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1523
1524 // Remove test physical network
1525 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1526}
1527
1528TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1529 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001530 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001531 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001532 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001533 // Need to have a prior interface quota set to set an alert
1534 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1535 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1536 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1537 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1538
1539 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1540 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1541 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1542
1543 // Remove interface quota
1544 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1545 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1546 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1547
1548 // Remove test physical network
1549 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1550}
1551
1552TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1553 long testAlertBytes = 2097149;
1554
1555 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1556 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1557 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1558
1559 testAlertBytes = 2097152;
1560 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1561 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1562 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1563}
1564
1565TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1566 SKIP_IF_BPF_SUPPORTED;
1567
1568 int32_t uid = randomUid();
1569 static const char targetReject[] = "REJECT";
1570 static const char targetReturn[] = "RETURN";
1571
1572 // add NaughtyApp
1573 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1574 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1575 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1576
1577 // remove NaughtyApp
1578 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1579 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1580 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1581
1582 // add NiceApp
1583 status = mNetd->bandwidthAddNiceApp(uid);
1584 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1585 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1586
1587 // remove NiceApp
1588 status = mNetd->bandwidthRemoveNiceApp(uid);
1589 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1590 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1591}
Luke Huangb5733d72018-08-21 17:17:19 +08001592
1593namespace {
1594
Luke Huangb670d162018-08-23 20:01:13 +08001595std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1596 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1597 return runCommand(command);
1598}
1599
Luke Huangc3252cc2018-10-16 15:43:23 +08001600bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001601 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1602 for (const auto& route : routes) {
1603 if (route.find(ipRoute) != std::string::npos) {
1604 return true;
1605 }
1606 }
1607 return false;
1608}
1609
Luke Huangc3252cc2018-10-16 15:43:23 +08001610std::string ipRouteString(const std::string& ifName, const std::string& dst,
1611 const std::string& nextHop) {
1612 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1613
1614 if (!nextHop.empty()) {
1615 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001616 }
1617
Luke Huangc3252cc2018-10-16 15:43:23 +08001618 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001619}
1620
Luke Huangc3252cc2018-10-16 15:43:23 +08001621void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1622 const std::string& dst, const std::string& nextHop,
1623 const char* table) {
1624 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1625}
1626
1627void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001628 const std::string& dst, const std::string& nextHop,
1629 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001630 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001631}
1632
1633bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1634 std::vector<std::string> rules = listIpRules(ipVersion);
1635 for (const auto& rule : rules) {
1636 if (rule.find(ipRule) != std::string::npos) {
1637 return true;
1638 }
1639 }
1640 return false;
1641}
1642
1643void expectNetworkDefaultIpRuleExists(const char* ifName) {
1644 std::string networkDefaultRule =
1645 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1646
1647 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1648 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1649 }
1650}
1651
1652void expectNetworkDefaultIpRuleDoesNotExist() {
1653 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1654
1655 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1656 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1657 }
1658}
1659
1660void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1661 std::string networkPermissionRule = "";
1662 switch (permission) {
1663 case INetd::PERMISSION_NONE:
1664 networkPermissionRule = StringPrintf(
1665 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1666 break;
1667 case INetd::PERMISSION_NETWORK:
1668 networkPermissionRule = StringPrintf(
1669 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1670 break;
1671 case INetd::PERMISSION_SYSTEM:
1672 networkPermissionRule = StringPrintf(
1673 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1674 break;
1675 }
1676
1677 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1678 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1679 }
1680}
1681
1682// TODO: It is a duplicate function, need to remove it
1683bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1684 const std::string& expectedInterface,
1685 const std::string& expectedRule,
1686 const char* table) {
1687 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1688 for (const auto& rule : rules) {
1689 if (rule.find(expectedInterface) != std::string::npos) {
1690 if (rule.find(expectedRule) != std::string::npos) {
1691 return true;
1692 }
1693 }
1694 }
1695 return false;
1696}
1697
1698void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1699 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1700 std::string networkIncomingPacketMarkRule = "";
1701 switch (permission) {
1702 case INetd::PERMISSION_NONE:
1703 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1704 break;
1705 case INetd::PERMISSION_NETWORK:
1706 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1707 break;
1708 case INetd::PERMISSION_SYSTEM:
1709 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1710 break;
1711 }
1712
1713 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1714 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1715 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1716 }
1717}
1718
1719} // namespace
1720
1721TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001722 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001723 const char* ipVersion;
1724 const char* testDest;
1725 const char* testNextHop;
1726 const bool expectSuccess;
1727 } kTestData[] = {
1728 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001729 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1730 {IP_RULE_V4, "10.251.0.0/16", "", true},
1731 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1732 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001733 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001734 {IP_RULE_V6, "::/0", "2001:db8::", true},
1735 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001736 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1737 };
1738
Luke Huangc3252cc2018-10-16 15:43:23 +08001739 static const struct {
1740 const char* ipVersion;
1741 const char* testDest;
1742 const char* testNextHop;
1743 } kTestDataWithNextHop[] = {
1744 {IP_RULE_V4, "10.251.10.0/30", ""},
1745 {IP_RULE_V6, "2001:db8::/32", ""},
1746 };
1747
Luke Huangb670d162018-08-23 20:01:13 +08001748 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001749 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001750 const int testUid = randomUid();
1751 const std::vector<int32_t> testUids = {testUid};
1752
1753 // Add test physical network
1754 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1755 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1756
Luke Huangc3252cc2018-10-16 15:43:23 +08001757 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001758 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001759 const auto& td = kTestDataWithNextHop[i];
1760
1761 // All route for test tun will disappear once the tun interface is deleted.
1762 binder::Status status =
1763 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1764 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1765 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1766 sTun.name().c_str());
1767
1768 // Add system permission for test uid, setup route in legacy system table.
1769 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1770
1771 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1772 testUid);
1773 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1774 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1775 testTableLegacySystem);
1776
1777 // Remove system permission for test uid, setup route in legacy network table.
1778 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1779
1780 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1781 testUid);
1782 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1783 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1784 testTableLegacyNetwork);
1785 }
1786
Sehee Park8659b8d2018-11-16 10:53:16 +09001787 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001788 const auto& td = kTestData[i];
1789
1790 binder::Status status =
1791 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1792 if (td.expectSuccess) {
1793 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001794 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001795 sTun.name().c_str());
1796 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001797 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1798 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001799 }
1800
1801 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1802 if (td.expectSuccess) {
1803 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001804 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1805 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001806 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001807 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1808 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001809 }
1810
Luke Huangc3252cc2018-10-16 15:43:23 +08001811 // Add system permission for test uid, route will be added into legacy system table.
1812 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001813
1814 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1815 testUid);
1816 if (td.expectSuccess) {
1817 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001818 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001819 testTableLegacySystem);
1820 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001821 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1822 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001823 }
1824
1825 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1826 td.testNextHop, testUid);
1827 if (td.expectSuccess) {
1828 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001829 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1830 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001831 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001832 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1833 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001834 }
1835
Luke Huangc3252cc2018-10-16 15:43:23 +08001836 // Remove system permission for test uid, route will be added into legacy network table.
1837 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1838
1839 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1840 testUid);
1841 if (td.expectSuccess) {
1842 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1843 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1844 testTableLegacyNetwork);
1845 } else {
1846 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1847 EXPECT_NE(0, status.serviceSpecificErrorCode());
1848 }
1849
1850 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1851 td.testNextHop, testUid);
1852 if (td.expectSuccess) {
1853 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1854 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1855 testTableLegacyNetwork);
1856 } else {
1857 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1858 EXPECT_NE(0, status.serviceSpecificErrorCode());
1859 }
Luke Huangb670d162018-08-23 20:01:13 +08001860 }
1861
1862 // Remove test physical network
1863 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1864}
1865
1866TEST_F(BinderTest, NetworkPermissionDefault) {
1867 // Add test physical network
1868 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1869 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1870
Luke Huangc3252cc2018-10-16 15:43:23 +08001871 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001872 int currentNetid;
1873 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1874 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1875
1876 // Test SetDefault
1877 status = mNetd->networkSetDefault(TEST_NETID1);
1878 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1879 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1880
1881 status = mNetd->networkClearDefault();
1882 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1883 expectNetworkDefaultIpRuleDoesNotExist();
1884
1885 // Add default network back
1886 status = mNetd->networkSetDefault(currentNetid);
1887 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1888
1889 // Test SetPermission
1890 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1891 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1892 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1893 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1894
1895 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1896 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1897 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1898 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1899
1900 // Remove test physical network
1901 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1902}
1903
1904TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1905 const int testUid = randomUid();
1906 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1907 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1908 bool ret = false;
1909 status = mNetd->networkCanProtect(testUid, &ret);
1910 EXPECT_TRUE(ret);
1911
1912 status = mNetd->networkSetProtectDeny(testUid);
1913 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1914 status = mNetd->networkCanProtect(testUid, &ret);
1915 EXPECT_FALSE(ret);
1916}
1917
1918namespace {
1919
Luke Huangb5733d72018-08-21 17:17:19 +08001920int readIntFromPath(const std::string& path) {
1921 std::string result = "";
1922 EXPECT_TRUE(ReadFileToString(path, &result));
1923 return std::stoi(result);
1924}
1925
1926int getTetherAcceptIPv6Ra(const std::string& ifName) {
1927 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1928 return readIntFromPath(path);
1929}
1930
1931bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1932 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1933 return readIntFromPath(path);
1934}
1935
1936int getTetherIPv6DadTransmits(const std::string& ifName) {
1937 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1938 return readIntFromPath(path);
1939}
1940
1941bool getTetherEnableIPv6(const std::string& ifName) {
1942 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1943 int disableIPv6 = readIntFromPath(path);
1944 return !disableIPv6;
1945}
1946
1947bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1948 for (const auto& iface : ifList) {
1949 if (iface == ifName) {
1950 return true;
1951 }
1952 }
1953 return false;
1954}
1955
1956void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1957 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1958 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1959 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1960 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1961}
1962
1963void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1964 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1965 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1966 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1967 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1968}
1969
1970void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1971 const std::string& ifName) {
1972 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1973}
1974
1975void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1976 const std::string& ifName) {
1977 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1978}
1979
1980void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
1981 const std::vector<std::string>& testDnsAddrs) {
1982 EXPECT_TRUE(dnsList == testDnsAddrs);
1983}
1984
1985} // namespace
1986
1987TEST_F(BinderTest, TetherStartStopStatus) {
1988 std::vector<std::string> noDhcpRange = {};
1989 static const char dnsdName[] = "dnsmasq";
1990
1991 binder::Status status = mNetd->tetherStart(noDhcpRange);
1992 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1993 EXPECT_TRUE(processExists(dnsdName));
1994
1995 bool tetherEnabled;
1996 status = mNetd->tetherIsEnabled(&tetherEnabled);
1997 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1998 EXPECT_TRUE(tetherEnabled);
1999
2000 status = mNetd->tetherStop();
2001 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2002 EXPECT_FALSE(processExists(dnsdName));
2003
2004 status = mNetd->tetherIsEnabled(&tetherEnabled);
2005 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2006 EXPECT_FALSE(tetherEnabled);
2007}
2008
2009TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2010 // TODO: verify if dnsmasq update interface successfully
2011
2012 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2013 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2014 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2015
2016 std::vector<std::string> ifList;
2017 status = mNetd->tetherInterfaceList(&ifList);
2018 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2019 expectTetherInterfaceExists(ifList, sTun.name());
2020
2021 status = mNetd->tetherInterfaceRemove(sTun.name());
2022 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2023 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2024
2025 status = mNetd->tetherInterfaceList(&ifList);
2026 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2027 expectTetherInterfaceNotExists(ifList, sTun.name());
2028}
2029
2030TEST_F(BinderTest, TetherDnsSetList) {
2031 // TODO: verify if dnsmasq update dns successfully
2032 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
2033
2034 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2035 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2036
2037 std::vector<std::string> dnsList;
2038 status = mNetd->tetherDnsList(&dnsList);
2039 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2040 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002041}
2042
2043namespace {
2044
2045constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2046constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2047constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2048constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2049constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2050constexpr char FIREWALL_STANDBY[] = "fw_standby";
2051constexpr char targetReturn[] = "RETURN";
2052constexpr char targetDrop[] = "DROP";
2053
2054void expectFirewallWhitelistMode() {
2055 static const char dropRule[] = "DROP all";
2056 static const char rejectRule[] = "REJECT all";
2057 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2058 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2059 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2060 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2061 }
2062}
2063
2064void expectFirewallBlacklistMode() {
2065 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2066 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2067 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2068 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2069 }
2070}
2071
2072bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2073 const std::string& expectedInterface,
2074 const std::string& expectedRule) {
2075 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2076 // Expected rule:
2077 // Chain fw_INPUT (1 references)
2078 // pkts bytes target prot opt in out source destination
2079 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2080 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2081 int firstRuleIndex = 2;
2082 if (rules.size() < 4) return false;
2083 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2084 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2085 return true;
2086 }
2087 }
2088 return false;
2089}
2090
2091// TODO: It is a duplicate function, need to remove it
2092bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2093 const std::string& expectedInterface,
2094 const std::string& expectedRule) {
2095 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2096 for (const auto& rule : rules) {
2097 if (rule.find(expectedInterface) != std::string::npos) {
2098 if (rule.find(expectedRule) != std::string::npos) {
2099 return true;
2100 }
2101 }
2102 }
2103 return false;
2104}
2105
2106void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2107 static const char returnRule[] = "RETURN all";
2108 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2109 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2110 returnRule));
2111 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2112 returnRule));
2113 }
2114}
2115
2116void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2117 static const char returnRule[] = "RETURN all";
2118 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2119 EXPECT_FALSE(
2120 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2121 EXPECT_FALSE(
2122 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2123 }
2124}
2125
2126bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2127 const std::string& expectedTarget,
2128 const std::string& expectedRule) {
2129 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2130 int firstRuleIndex = 2;
2131 if (rules.size() < 4) return false;
2132 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2133 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2134 return true;
2135 }
2136 }
2137 return false;
2138}
2139
2140bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2141 const std::string& expectedTarget,
2142 const std::string& expectedRule) {
2143 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2144 int lastRuleIndex = rules.size() - 1;
2145 if (lastRuleIndex < 0) return false;
2146 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2147 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2148 return true;
2149 }
2150 }
2151 return false;
2152}
2153
2154void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2155 std::string uidRule = StringPrintf("owner UID match %u", uid);
2156 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2157 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2158}
2159
2160void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2161 std::string uidRule = StringPrintf("owner UID match %u", uid);
2162 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2163 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2164}
2165
2166void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2167 std::string uidRule = StringPrintf("owner UID match %u", uid);
2168 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2169 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2170}
2171
2172void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2173 std::string uidRule = StringPrintf("owner UID match %u", uid);
2174 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2175 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2176}
2177
2178bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2179 std::vector<std::string> inputRules =
2180 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2181 std::vector<std::string> outputRules =
2182 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2183 int inputLastRuleIndex = inputRules.size() - 1;
2184 int outputLastRuleIndex = outputRules.size() - 1;
2185
2186 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2187 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2188 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2189 return true;
2190 }
2191 }
2192 return false;
2193}
2194
2195void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2196 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2197 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2198}
2199
2200void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2201 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2202 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2203 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2204 }
2205}
2206
2207} // namespace
2208
2209TEST_F(BinderTest, FirewallSetFirewallType) {
2210 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2211 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2212 expectFirewallWhitelistMode();
2213
2214 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2215 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2216 expectFirewallBlacklistMode();
2217
2218 // set firewall type blacklist twice
2219 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2220 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2221 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2222 expectFirewallBlacklistMode();
2223
2224 // set firewall type whitelist twice
2225 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2226 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2227 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2228 expectFirewallWhitelistMode();
2229
2230 // reset firewall type to default
2231 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2232 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2233 expectFirewallBlacklistMode();
2234}
2235
2236TEST_F(BinderTest, FirewallSetInterfaceRule) {
2237 // setinterfaceRule is not supported in BLACKLIST MODE
2238 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2239 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2240
2241 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2242 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2243
2244 // set WHITELIST mode first
2245 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2246 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2247
2248 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2249 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2250 expectFirewallInterfaceRuleAllowExists(sTun.name());
2251
2252 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2253 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2254 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2255
2256 // reset firewall mode to default
2257 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2258 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2259 expectFirewallBlacklistMode();
2260}
2261
2262TEST_F(BinderTest, FirewallSetUidRule) {
2263 SKIP_IF_BPF_SUPPORTED;
2264
2265 int32_t uid = randomUid();
2266
2267 // Doze allow
2268 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2269 INetd::FIREWALL_RULE_ALLOW);
2270 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2271 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2272
2273 // Doze deny
2274 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2275 INetd::FIREWALL_RULE_DENY);
2276 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2277 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2278
2279 // Powersave allow
2280 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2281 INetd::FIREWALL_RULE_ALLOW);
2282 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2283 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2284
2285 // Powersave deny
2286 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2287 INetd::FIREWALL_RULE_DENY);
2288 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2289 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2290
2291 // Standby deny
2292 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2293 INetd::FIREWALL_RULE_DENY);
2294 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2295 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2296
2297 // Standby allow
2298 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2299 INetd::FIREWALL_RULE_ALLOW);
2300 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2301 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2302
2303 // None deny in BLACKLIST
2304 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2305 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2306 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2307 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2308
2309 // None allow in BLACKLIST
2310 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2311 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2312 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2313 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2314
2315 // set firewall type whitelist twice
2316 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2317 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2318 expectFirewallWhitelistMode();
2319
2320 // None allow in WHITELIST
2321 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2322 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2323 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2324 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2325
2326 // None deny in WHITELIST
2327 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2328 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2329 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2330 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2331
2332 // reset firewall mode to default
2333 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2334 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2335 expectFirewallBlacklistMode();
2336}
2337
2338TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2339 SKIP_IF_BPF_SUPPORTED;
2340
2341 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2342 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2343 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2344
2345 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2346 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2347 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2348
2349 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2350 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2351 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2352
2353 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2354 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2355 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2356
2357 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2358 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2359 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2360
2361 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2362 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2363 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2364}
Luke Huangf7782042018-08-08 13:13:04 +08002365
2366namespace {
2367
2368std::string hwAddrToStr(unsigned char* hwaddr) {
2369 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2370 hwaddr[4], hwaddr[5]);
2371}
2372
2373int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2374 int prefixLength = 0;
2375 uint32_t m = ntohl(mask);
2376 while (m & (1 << 31)) {
2377 prefixLength++;
2378 m = m << 1;
2379 }
2380 return prefixLength;
2381}
2382
2383std::string toStdString(const String16& s) {
2384 return std::string(String8(s.string()));
2385}
2386
2387android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2388 const auto& sys = sSyscalls.get();
2389 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2390 EXPECT_TRUE(isOk(fd.status()));
2391
2392 struct ifreq ifr = {};
2393 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2394
2395 return sys.ioctl(fd.value(), flag, &ifr);
2396}
2397
2398std::string getInterfaceHwAddr(const std::string& ifName) {
2399 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2400
2401 unsigned char hwaddr[ETH_ALEN] = {};
2402 if (isOk(res.status())) {
2403 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2404 }
2405
2406 return hwAddrToStr(hwaddr);
2407}
2408
2409int getInterfaceIPv4Prefix(const std::string& ifName) {
2410 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2411
2412 int prefixLength = 0;
2413 if (isOk(res.status())) {
2414 prefixLength = ipv4NetmaskToPrefixLength(
2415 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2416 }
2417
2418 return prefixLength;
2419}
2420
2421std::string getInterfaceIPv4Addr(const std::string& ifName) {
2422 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2423
2424 struct in_addr addr = {};
2425 if (isOk(res.status())) {
2426 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2427 }
2428
2429 return std::string(inet_ntoa(addr));
2430}
2431
2432std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2433 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2434
2435 unsigned flags = 0;
2436 if (isOk(res.status())) {
2437 flags = res.value().ifr_flags;
2438 }
2439
2440 std::vector<std::string> ifFlags;
2441 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2442 : toStdString(INetd::IF_STATE_DOWN()));
2443
2444 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2445 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2446 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2447 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2448 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2449
2450 return ifFlags;
2451}
2452
2453bool compareListInterface(const std::vector<std::string>& interfaceList) {
2454 const auto& res = InterfaceController::getIfaceNames();
2455 EXPECT_TRUE(isOk(res));
2456
2457 std::vector<std::string> resIfList;
2458 resIfList.reserve(res.value().size());
2459 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2460
2461 return resIfList == interfaceList;
2462}
2463
2464int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2465 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2466 return readIntFromPath(path);
2467}
2468
2469bool getInterfaceEnableIPv6(const std::string& ifName) {
2470 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2471
2472 int disableIPv6 = readIntFromPath(path);
2473 return !disableIPv6;
2474}
2475
2476int getInterfaceMtu(const std::string& ifName) {
2477 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2478 return readIntFromPath(path);
2479}
2480
2481void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2482 EXPECT_TRUE(compareListInterface(interfaceList));
2483}
2484
2485void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2486 const InterfaceConfigurationParcel& interfaceCfg) {
2487 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2488 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2489 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2490 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2491}
2492
2493void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2494 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2495 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2496
2497 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2498 for (const auto& flag : setCfg.flags) {
2499 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2500 }
2501}
2502
2503void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2504 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2505 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2506}
2507
2508void expectInterfaceNoAddr(const std::string& ifName) {
2509 // noAddr
2510 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2511 // noPrefix
2512 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2513}
2514
2515void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2516 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2517 EXPECT_EQ(enableIPv6, enable);
2518}
2519
2520void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2521 int mtuSize = getInterfaceMtu(ifName);
2522 EXPECT_EQ(mtu, mtuSize);
2523}
2524
2525InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2526 const std::string& addr, int prefixLength,
2527 const std::vector<std::string>& flags) {
2528 InterfaceConfigurationParcel cfg;
2529 cfg.ifName = ifName;
2530 cfg.hwAddr = "";
2531 cfg.ipv4Addr = addr;
2532 cfg.prefixLength = prefixLength;
2533 cfg.flags = flags;
2534 return cfg;
2535}
2536
2537void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2538 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2539 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2540
2541 for (const auto& flag : expectedFlags) {
2542 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2543 interfaceCfg.flags.end());
2544 }
2545
2546 for (const auto& flag : unexpectedFlags) {
2547 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2548 interfaceCfg.flags.end());
2549 }
2550}
2551
2552} // namespace
2553
2554TEST_F(BinderTest, InterfaceList) {
2555 std::vector<std::string> interfaceListResult;
2556
2557 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2558 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2559 expectInterfaceList(interfaceListResult);
2560}
2561
2562TEST_F(BinderTest, InterfaceGetCfg) {
2563 InterfaceConfigurationParcel interfaceCfgResult;
2564
2565 // Add test physical network
2566 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2567 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2568
2569 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2570 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2571 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2572 expectTunFlags(interfaceCfgResult);
2573
2574 // Remove test physical network
2575 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2576}
2577
2578TEST_F(BinderTest, InterfaceSetCfg) {
2579 const std::string testAddr = "192.0.2.3";
2580 const int testPrefixLength = 24;
2581 std::vector<std::string> upFlags = {"up"};
2582 std::vector<std::string> downFlags = {"down"};
2583
2584 // Add test physical network
2585 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2586 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2587
2588 // Set tun interface down.
2589 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2590 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2591 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2592 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2593
2594 // Set tun interface up again.
2595 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2596 status = mNetd->interfaceSetCfg(interfaceCfg);
2597 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2598 status = mNetd->interfaceClearAddrs(sTun.name());
2599 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2600
2601 // Remove test physical network
2602 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2603}
2604
2605TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2606 // enable
2607 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2608 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2609 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2610
2611 // disable
2612 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2613 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2614 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2615}
2616
2617TEST_F(BinderTest, InterfaceClearAddr) {
2618 const std::string testAddr = "192.0.2.3";
2619 const int testPrefixLength = 24;
2620 std::vector<std::string> noFlags{};
2621
2622 // Add test physical network
2623 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2624 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2625
2626 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2627 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2628 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2629 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2630
2631 status = mNetd->interfaceClearAddrs(sTun.name());
2632 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2633 expectInterfaceNoAddr(sTun.name());
2634
2635 // Remove test physical network
2636 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2637}
2638
2639TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2640 // Add test physical network
2641 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2642 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2643
2644 // disable
2645 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2646 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2647 expectInterfaceEnableIPv6(sTun.name(), false);
2648
2649 // enable
2650 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2651 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2652 expectInterfaceEnableIPv6(sTun.name(), true);
2653
2654 // Remove test physical network
2655 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2656}
2657
2658TEST_F(BinderTest, InterfaceSetMtu) {
2659 const int testMtu = 1200;
2660
2661 // Add test physical network
2662 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2663 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2664
2665 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2666 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2667 expectInterfaceMtu(sTun.name(), testMtu);
2668
2669 // Remove test physical network
2670 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2671}
Luke Huang19b49c52018-10-22 12:12:05 +09002672
2673namespace {
2674
2675constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2676constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002677constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002678constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2679
Luke Huangae038f82018-11-05 11:17:31 +09002680int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002681 return listIptablesRuleByTable(binary, table, chainName).size();
2682}
2683
2684bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2685 const std::vector<std::string>& targetVec) {
2686 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2687 if (targetVec.size() != rules.size() - 2) {
2688 return false;
2689 }
2690
2691 /*
Luke Huangae038f82018-11-05 11:17:31 +09002692 * Check that the rules match. Note that this function matches substrings, not entire rules,
2693 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002694 * Skip first two lines since rules start from third line.
2695 * Chain chainName (x references)
2696 * pkts bytes target prot opt in out source destination
2697 * ...
2698 */
2699 int rIndex = 2;
2700 for (const auto& target : targetVec) {
2701 if (rules[rIndex].find(target) == std::string::npos) {
2702 return false;
2703 }
2704 rIndex++;
2705 }
2706 return true;
2707}
2708
2709void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2710 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2711 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2712 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002713 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002714 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2715 "DROP"};
2716
2717 // V4
2718 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2719 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002720 EXPECT_TRUE(
2721 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002722 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2723
Luke Huangae038f82018-11-05 11:17:31 +09002724 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002725 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2726
2727 // V6
2728 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002729 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2730 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002731
2732 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2733 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2734 extIf));
2735 }
2736}
2737
2738void expectNatDisable() {
2739 // It is the default DROP rule with tethering disable.
2740 // Chain tetherctrl_FORWARD (1 references)
2741 // pkts bytes target prot opt in out source destination
2742 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2743 std::vector<std::string> forwardV4Match = {"DROP"};
2744 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2745
2746 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002747 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2748 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002749
Luke Huangae038f82018-11-05 11:17:31 +09002750 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2751 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002752
2753 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2754}
2755
2756} // namespace
2757
2758TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002759 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2760 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2761 expectNatEnable(sTun.name(), sTun2.name());
2762
2763 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2764 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2765 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002766}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002767
2768namespace {
2769
2770using TripleInt = std::array<int, 3>;
2771
2772TripleInt readProcFileToTripleInt(const std::string& path) {
2773 std::string valueString;
2774 int min, def, max;
2775 EXPECT_TRUE(ReadFileToString(path, &valueString));
2776 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2777 return {min, def, max};
2778}
2779
2780void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2781 std::string testRmemValues =
2782 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2783 std::string testWmemValues =
2784 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2785 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2786
2787 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2788 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2789
2790 for (int i = 0; i < 3; i++) {
2791 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2792 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2793 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2794 }
2795}
2796
2797} // namespace
2798
2799TEST_F(BinderTest, TcpBufferSet) {
2800 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2801 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2802 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2803 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2804
2805 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2806 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2807}
Luke Huang528af602018-08-29 19:06:05 +08002808
2809TEST_F(BinderTest, UnsolEvents) {
2810 auto testUnsolService = android::net::TestUnsolService::start();
2811 std::string oldTunName = sTun.name();
2812 std::string newTunName = "unsolTest";
2813 testUnsolService->tarVec.push_back(oldTunName);
2814 testUnsolService->tarVec.push_back(newTunName);
2815 auto& cv = testUnsolService->getCv();
2816 auto& cvMutex = testUnsolService->getCvMutex();
2817 binder::Status status = mNetd->registerUnsolicitedEventListener(
2818 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2819 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2820
2821 // TODO: Add test for below events
2822 // StrictCleartextDetected / InterfaceDnsServersAdded
2823 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2824
2825 {
2826 std::unique_lock lock(cvMutex);
2827
2828 // Re-init test Tun, and we expect that we will get some unsol events.
2829 // Use the test Tun device name to verify if we receive its unsol events.
2830 sTun.destroy();
2831 // Use predefined name
2832 sTun.init(newTunName);
2833
2834 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2835 }
2836
2837 // bit mask 1101101000
2838 // Test only covers below events currently
2839 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2840 InterfaceLinkStatusChanged | RouteChanged;
2841 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
2842}