blob: dac3d71a24bd1b0e4261a42052baea10eae852eb [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 Feng48eaed32018-12-26 17:40:21 -080046#include <bpf/BpfMap.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070047#include <bpf/BpfUtils.h>
Robin Leeb8087362016-03-30 18:43:08 +010048#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090049#include <gtest/gtest.h>
50#include <logwrap/logwrap.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080051#include <netdbpf/bpf_shared.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090052#include <netutils/ifc.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090053
Nathan Harold21299f72018-03-16 20:13:03 -070054#include "InterfaceController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090055#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090056#include "Stopwatch.h"
Luke Huang528af602018-08-29 19:06:05 +080057#include "TestUnsolService.h"
Nathan Harold21299f72018-03-16 20:13:03 -070058#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090059#include "android/net/INetd.h"
60#include "binder/IServiceManager.h"
Nathan Harold21299f72018-03-16 20:13:03 -070061#include "netdutils/Syscalls.h"
Mike Yu5ae61542018-10-19 22:11:43 +080062#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090063
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090064#define IP_PATH "/system/bin/ip"
65#define IP6TABLES_PATH "/system/bin/ip6tables"
66#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090067#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080068#define RAW_TABLE "raw"
69#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080070#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090071#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090072
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090073namespace binder = android::binder;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090074
75using android::IBinder;
76using android::IServiceManager;
77using android::sp;
78using android::String16;
79using android::String8;
80using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080081using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090082using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090083using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080084using android::base::Trim;
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;
Luke Huangf7782042018-08-08 13:13:04 +080092using android::netdutils::sSyscalls;
Robin Leeb8087362016-03-30 18:43:08 +010093
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090094#define SKIP_IF_BPF_SUPPORTED \
95 do { \
96 if (hasBpfSupport()) return; \
97 } while (0)
Chenbo Feng837ddfc2018-05-08 13:45:08 -070098
Robin Leeb8087362016-03-30 18:43:08 +010099static const char* IP_RULE_V4 = "-4";
100static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900101static const int TEST_NETID1 = 65501;
102static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -0800103
104// Use maximum reserved appId for applications to avoid conflict with existing
105// uids.
106static const int TEST_UID1 = 99999;
107static const int TEST_UID2 = 99998;
108
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900109constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900110
Benedict Wongb2daefb2017-12-06 22:05:46 -0800111static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
112static const std::string ESP_ALLOW_RULE("esp");
113
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900114class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900115 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900116 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900117 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900118 sp<IBinder> binder = sm->getService(String16("netd"));
119 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900120 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900121 }
122 }
123
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900124 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900125 ASSERT_NE(nullptr, mNetd.get());
126 }
127
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900128 void TearDown() override {
129 mNetd->networkDestroy(TEST_NETID1);
130 mNetd->networkDestroy(TEST_NETID2);
131 }
132
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900133 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700134
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900135 // Static because setting up the tun interface takes about 40ms.
136 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900137 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900138 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900139 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900140 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900141 }
142
143 static void TearDownTestCase() {
144 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900145 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900146 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900147 }
148
149 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900150
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900151 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900152 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900153 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900154 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900155};
156
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900157TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900158TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900159
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900160class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900161 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700162 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900163 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900164 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900165 }
166
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900167 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900168 std::string mName;
169};
170
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900171TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900172 TimedOperation t("isAlive RPC");
173 bool isAlive = false;
174 mNetd->isAlive(&isAlive);
175 ASSERT_TRUE(isAlive);
176}
177
178static int randomUid() {
179 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
180}
181
Robin Leeb8087362016-03-30 18:43:08 +0100182static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900183 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900184 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
185 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900186 perror("popen");
187 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900188 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900189
190 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100191 size_t bufsize = 0;
192 ssize_t linelen = 0;
193 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900194 lines.push_back(std::string(line, linelen));
195 free(line);
196 line = nullptr;
197 }
198
199 pclose(f);
200 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900201}
202
Robin Leeb8087362016-03-30 18:43:08 +0100203static std::vector<std::string> listIpRules(const char *ipVersion) {
204 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
205 return runCommand(command);
206}
207
208static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900209 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100210 return runCommand(command);
211}
212
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900213static int iptablesRuleLineLength(const char *binary, const char *chainName) {
214 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900215}
216
Benedict Wongb2daefb2017-12-06 22:05:46 -0800217static bool iptablesRuleExists(const char *binary,
218 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900219 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800220 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900221 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800222 if(rule.find(expectedRule) != std::string::npos) {
223 return true;
224 }
225 }
226 return false;
227}
228
229static bool iptablesNoSocketAllowRuleExists(const char *chainName){
230 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
231 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
232}
233
234static bool iptablesEspAllowRuleExists(const char *chainName){
235 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
236 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
237}
238
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900239TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700240 SKIP_IF_BPF_SUPPORTED;
241
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900242 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
243 const int kNumUids = 500;
244 std::vector<int32_t> noUids(0);
245 std::vector<int32_t> uids(kNumUids);
246 for (int i = 0; i < kNumUids; i++) {
247 uids[i] = randomUid();
248 }
249
250 bool ret;
251 {
252 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900253 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900254 }
255 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800256 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
257 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
258 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
259 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900260 {
261 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900262 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900263 }
264 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900265 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
266 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900267
268 {
269 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900270 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900271 }
272 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900273 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
274 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800275 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
276 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900277
278 {
279 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900280 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900281 }
282 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900283 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
284 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900285
286 // Check that the call fails if iptables returns an error.
287 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900288 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900289 EXPECT_EQ(false, ret);
290}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900291
Benedict Wong319f17e2018-05-15 17:06:44 -0700292TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700293 const struct TestData {
294 const std::string family;
295 const std::string deviceName;
296 const std::string localAddress;
297 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800298 int32_t iKey;
299 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700300 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800301 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700302 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
303 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
304 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800305 };
306
Sehee Park8659b8d2018-11-16 10:53:16 +0900307 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700308 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800309
310 binder::Status status;
311
Benedict Wong319f17e2018-05-15 17:06:44 -0700312 // Create Tunnel Interface.
313 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700314 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800315 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
316
Benedict Wonga450e722018-05-07 10:29:02 -0700317 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900318 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700319
Benedict Wong319f17e2018-05-15 17:06:44 -0700320 // Update Tunnel Interface.
321 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700322 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800323 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
324
Benedict Wong319f17e2018-05-15 17:06:44 -0700325 // Remove Tunnel Interface.
326 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800327 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700328
329 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900330 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800331 }
332}
333
Benedict Wong1cb73df2018-12-03 00:54:14 -0800334TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
335 android::base::unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
336 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
337
338 int sockOptVal = UDP_ENCAP_ESPINUDP;
339 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
340
341 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
342 EXPECT_TRUE(res.isOk());
343
344 struct stat info;
345 EXPECT_EQ(0, fstat(sockFd.get(), &info));
346 EXPECT_EQ(1001, (int) info.st_uid);
347}
348
Nathan Harold2deff322018-05-10 14:03:48 -0700349// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
350// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
351#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900352
353using android::net::XfrmController;
354
Benedict Wonga04ffa72018-05-09 21:42:42 -0700355static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
356 static_cast<int>(android::net::XfrmDirection::OUT)};
357static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
358
Nathan Harold21299f72018-03-16 20:13:03 -0700359#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
360 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900361bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900362 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700363 SCOPED_TRACE(status);
364 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
365
366 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700367 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700368 SCOPED_TRACE(status);
369 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
370
371 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700372 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
373 0xD00D, 0xE00D, false)
374 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700375}
376
Benedict Wonga04ffa72018-05-09 21:42:42 -0700377TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900378 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700379
380 // Repeat to ensure cleanup and recreation works correctly
381 for (int i = 0; i < 2; i++) {
382 for (int direction : XFRM_DIRECTIONS) {
383 for (int addrFamily : ADDRESS_FAMILIES) {
384 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700385 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700386 EXPECT_TRUE(status.isOk())
387 << " family: " << addrFamily << " direction: " << direction;
388 }
389 }
390
391 // Cleanup
392 for (int direction : XFRM_DIRECTIONS) {
393 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700394 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700395 EXPECT_TRUE(status.isOk());
396 }
397 }
398 }
399}
400
401TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
402 binder::Status status;
403
404 // Repeat to ensure cleanup and recreation works correctly
405 for (int i = 0; i < 2; i++) {
406 for (int direction : XFRM_DIRECTIONS) {
407 for (int addrFamily : ADDRESS_FAMILIES) {
408 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700409 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700410 EXPECT_TRUE(status.isOk())
411 << " family: " << addrFamily << " direction: " << direction;
412 }
413 }
414
415 // Cleanup
416 for (int direction : XFRM_DIRECTIONS) {
417 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700418 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700419 EXPECT_TRUE(status.isOk());
420 }
421 }
422 }
423}
424
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900425TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900426 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700427 status = XfrmController::Init();
428 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700429
430 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
431 // feature.
432 if (status.code() == EOPNOTSUPP) return;
433
Nathan Harold21299f72018-03-16 20:13:03 -0700434 ASSERT_TRUE(status.ok());
435
436 int32_t spi = 0;
437
438 ASSERT_TRUE(allocateIpSecResources(true, &spi));
439 ASSERT_TRUE(allocateIpSecResources(false, &spi));
440
441 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700442 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700443 ASSERT_TRUE(allocateIpSecResources(true, &spi));
444
445 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700446 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700447 SCOPED_TRACE(status);
448 ASSERT_TRUE(status.ok());
449
Benedict Wonga450e722018-05-07 10:29:02 -0700450 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700451 SCOPED_TRACE(status);
452 ASSERT_TRUE(status.ok());
453
454 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700455 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700456}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900457
458#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700459
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900460static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900461 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900462
463 // Output looks like this:
464 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900465 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900466 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900467 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900468 //
469 // or:
470 //
471 // Chain bw_data_saver (1 references)
472 // target prot opt source destination
473 // ... possibly connectivity critical packet rules here ...
474 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900475
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900476 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900477
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900478 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
479 // Data saver disabled.
480 return 0;
481 }
482
483 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
484
485 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
486 // Data saver enabled.
487 return 1;
488 }
489
490 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900491}
492
493bool enableDataSaver(sp<INetd>& netd, bool enable) {
494 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
495 bool ret;
496 netd->bandwidthEnableDataSaver(enable, &ret);
497 return ret;
498}
499
500int getDataSaverState() {
501 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
502 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
503 EXPECT_EQ(enabled4, enabled6);
504 EXPECT_NE(-1, enabled4);
505 EXPECT_NE(-1, enabled6);
506 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
507 return -1;
508 }
509 return enabled6;
510}
511
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900512TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900513 const int wasEnabled = getDataSaverState();
514 ASSERT_NE(-1, wasEnabled);
515
516 if (wasEnabled) {
517 ASSERT_TRUE(enableDataSaver(mNetd, false));
518 EXPECT_EQ(0, getDataSaverState());
519 }
520
521 ASSERT_TRUE(enableDataSaver(mNetd, false));
522 EXPECT_EQ(0, getDataSaverState());
523
524 ASSERT_TRUE(enableDataSaver(mNetd, true));
525 EXPECT_EQ(1, getDataSaverState());
526
527 ASSERT_TRUE(enableDataSaver(mNetd, true));
528 EXPECT_EQ(1, getDataSaverState());
529
530 if (!wasEnabled) {
531 ASSERT_TRUE(enableDataSaver(mNetd, false));
532 EXPECT_EQ(0, getDataSaverState());
533 }
534}
Robin Leeb8087362016-03-30 18:43:08 +0100535
Luke Huang94658ac2018-10-18 19:35:12 +0900536static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
537 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100538 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100539 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100540 std::vector<std::string> rules = listIpRules(ipVersion);
541
542 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900543 std::string suffix =
544 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900545 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800546 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100547 return true;
548 }
549 }
550 return false;
551}
552
Luke Huang94658ac2018-10-18 19:35:12 +0900553static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
554 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100555 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
556 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
557 EXPECT_EQ(existsIp4, existsIp6);
558 return existsIp4;
559}
560
Luke Huang94658ac2018-10-18 19:35:12 +0900561namespace {
562
563UidRangeParcel makeUidRangeParcel(int start, int stop) {
564 UidRangeParcel res;
565 res.start = start;
566 res.stop = stop;
567
568 return res;
569}
570
571} // namespace
572
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900573TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800574 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
575 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
576 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900577 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
578 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900579
580 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
581 EXPECT_EQ(EBUSY,
582 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
583
584 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
585 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
586 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800587 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900588}
589
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900590TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900591 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
592
cken67cd14c2018-12-05 17:26:59 +0900593 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
594 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900595 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
596
Luke Huang94658ac2018-10-18 19:35:12 +0900597 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
598 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
599 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900600 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
601
602 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
603
604 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
605 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
606 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
607 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
608
609 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
610 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
611 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
612 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
613
614 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
615}
616
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900617TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100618 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100619
Luke Huang94658ac2018-10-18 19:35:12 +0900620 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
621 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100622
623 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
624 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
625
626 // Create two valid rules.
627 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
628 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
629 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
630 for (auto const& range : uidRanges) {
631 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
632 }
633
634 // Remove the rules.
635 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
636 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
637 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
638 for (auto const& range : uidRanges) {
639 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
640 }
641
642 // Fail to remove the rules a second time after they are already deleted.
643 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
644 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
645 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
646
647 // All rules should be the same as before.
648 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
649 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
650}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900651
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900652// Create a socket pair that isLoopbackSocket won't think is local.
653void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900654 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900655 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900656 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
657
658 socklen_t addrlen = sizeof(server6);
659 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
660 ASSERT_EQ(0, listen(*serverSocket, 10));
661
Bernie Innocentif6918262018-06-11 17:37:35 +0900662 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900663 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900664 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900665 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
666 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
667
Bernie Innocentif6918262018-06-11 17:37:35 +0900668 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900669 ASSERT_NE(-1, *acceptedSocket);
670
671 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
672}
673
674void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
675 char buf[4096];
676 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
677 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
678 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
679}
680
681void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
682 // Check that the client socket was closed with ECONNABORTED.
683 int ret = write(clientSocket, "foo", sizeof("foo"));
684 int err = errno;
685 EXPECT_EQ(-1, ret);
686 EXPECT_EQ(ECONNABORTED, err);
687
688 // Check that it sent a RST to the server.
689 ret = write(acceptedSocket, "foo", sizeof("foo"));
690 err = errno;
691 EXPECT_EQ(-1, ret);
692 EXPECT_EQ(ECONNRESET, err);
693}
694
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900695TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900696 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900697 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900698
699 // Pick a random UID in the system UID range.
700 constexpr int baseUid = AID_APP - 2000;
701 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
702 int uid = baseUid + 500 + arc4random_uniform(1000);
703 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
704
705 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900706 std::vector<UidRangeParcel> uidRanges = {
707 makeUidRangeParcel(baseUid + 42, baseUid + 449),
708 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
709 makeUidRangeParcel(baseUid + 498, uid - 1),
710 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900711 };
712 // A skip list that doesn't contain UID.
713 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
714
715 // Close sockets. Our test socket should be intact.
716 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
717 checkSocketpairOpen(clientSocket, acceptedSocket);
718
719 // UID ranges that do contain uid.
720 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900721 makeUidRangeParcel(baseUid + 42, baseUid + 449),
722 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
723 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900724 };
725 // Add uid to the skip list.
726 skipUids.push_back(uid);
727
728 // Close sockets. Our test socket should still be intact because it's in the skip list.
729 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
730 checkSocketpairOpen(clientSocket, acceptedSocket);
731
732 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
733 skipUids.resize(skipUids.size() - 1);
734 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
735 checkSocketpairClosed(clientSocket, acceptedSocket);
736
737 close(clientSocket);
738 close(serverSocket);
739 close(acceptedSocket);
740}
Erik Klinecc4f2732016-08-03 11:24:27 +0900741
742namespace {
743
744int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
745 if (buf == nullptr) return -1;
746
747 int prefixLength = 0;
748 bool endOfContiguousBits = false;
749 for (unsigned int i = 0; i < buflen; i++) {
750 const uint8_t value = buf[i];
751
752 // Bad bit sequence: check for a contiguous set of bits from the high
753 // end by verifying that the inverted value + 1 is a power of 2
754 // (power of 2 iff. (v & (v - 1)) == 0).
755 const uint8_t inverse = ~value + 1;
756 if ((inverse & (inverse - 1)) != 0) return -1;
757
758 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
759
760 // Bogus netmask.
761 if (endOfContiguousBits && value != 0) return -1;
762
763 if (value != 0xff) endOfContiguousBits = true;
764 }
765
766 return prefixLength;
767}
768
769template<typename T>
770int netmaskToPrefixLength(const T *p) {
771 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
772}
773
774
775static bool interfaceHasAddress(
776 const std::string &ifname, const char *addrString, int prefixLength) {
777 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900778
779 const struct addrinfo hints = {
780 .ai_flags = AI_NUMERICHOST,
781 .ai_family = AF_UNSPEC,
782 .ai_socktype = SOCK_DGRAM,
783 };
784 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
785 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
786 return false;
787 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900788 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900789
790 struct ifaddrs *ifaddrsList = nullptr;
791 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
792
793 if (getifaddrs(&ifaddrsList) != 0) {
794 return false;
795 }
796
797 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
798 if (std::string(addr->ifa_name) != ifname ||
799 addr->ifa_addr == nullptr ||
800 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
801 continue;
802 }
803
804 switch (addr->ifa_addr->sa_family) {
805 case AF_INET: {
806 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
807 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
808 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
809 continue;
810 }
811
812 if (prefixLength < 0) return true; // not checking prefix lengths
813
814 if (addr->ifa_netmask == nullptr) return false;
815 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
816 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
817 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
818 }
819 case AF_INET6: {
820 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
821 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
822 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
823 continue;
824 }
825
826 if (prefixLength < 0) return true; // not checking prefix lengths
827
828 if (addr->ifa_netmask == nullptr) return false;
829 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
830 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
831 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
832 }
833 default:
834 // Cannot happen because we have already screened for matching
835 // address families at the top of each iteration.
836 continue;
837 }
838 }
839
840 return false;
841}
842
843} // namespace
844
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900845TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900846 static const struct TestData {
847 const char *addrString;
848 const int prefixLength;
849 const bool expectSuccess;
850 } kTestData[] = {
851 { "192.0.2.1", 24, true },
852 { "192.0.2.2", 25, true },
853 { "192.0.2.3", 32, true },
854 { "192.0.2.4", 33, false },
855 { "192.not.an.ip", 24, false },
856 { "2001:db8::1", 64, true },
857 { "2001:db8::2", 65, true },
858 { "2001:db8::3", 128, true },
859 { "2001:db8::4", 129, false },
860 { "foo:bar::bad", 64, false },
861 };
862
Sehee Park8659b8d2018-11-16 10:53:16 +0900863 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900864 const auto &td = kTestData[i];
865
866 // [1.a] Add the address.
867 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900868 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900869 if (td.expectSuccess) {
870 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
871 } else {
872 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
873 ASSERT_NE(0, status.serviceSpecificErrorCode());
874 }
875
876 // [1.b] Verify the addition meets the expectation.
877 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900878 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900879 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900880 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900881 }
882
883 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900884 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900885 if (td.expectSuccess) {
886 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
887 } else {
888 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
889 ASSERT_NE(0, status.serviceSpecificErrorCode());
890 }
891
892 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900893 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900894 }
895}
Erik Kline55b06f82016-07-04 09:57:18 +0900896
Erik Kline38e51f12018-09-06 20:14:44 +0900897TEST_F(BinderTest, GetProcSysNet) {
898 const char LOOPBACK[] = "lo";
899 static const struct {
900 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900901 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900902 const char* ifname;
903 const char* parameter;
904 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900905 const int expectedReturnCode;
906 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900907 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
908 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
909 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
910 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
911 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
912 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
913 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900914 };
915
Sehee Park8659b8d2018-11-16 10:53:16 +0900916 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900917 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900918
Erik Kline38e51f12018-09-06 20:14:44 +0900919 std::string value;
920 const binder::Status status =
921 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
922
923 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900924 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900925 EXPECT_EQ(0, status.exceptionCode());
926 EXPECT_EQ(0, status.serviceSpecificErrorCode());
927 EXPECT_EQ(td.expectedValue, value);
928 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900929 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900930 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
931 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
932 }
933 }
934}
935
936TEST_F(BinderTest, SetProcSysNet) {
937 static const struct {
938 const int ipversion;
939 const int which;
940 const char* ifname;
941 const char* parameter;
942 const char* value;
943 const int expectedReturnCode;
944 } kTestData[] = {
945 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
946 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
947 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
948 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
949 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
950 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
951 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
952 };
953
Sehee Park8659b8d2018-11-16 10:53:16 +0900954 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900955 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900956 const binder::Status status =
957 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900958
959 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900960 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900961 EXPECT_EQ(0, status.exceptionCode());
962 EXPECT_EQ(0, status.serviceSpecificErrorCode());
963 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900964 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900965 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
966 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
967 }
968 }
969}
Ben Schwartze7601812017-04-28 16:38:29 -0400970
Erik Kline38e51f12018-09-06 20:14:44 +0900971TEST_F(BinderTest, GetSetProcSysNet) {
972 const int ipversion = INetd::IPV6;
973 const int category = INetd::NEIGH;
974 const std::string& tun = sTun.name();
975 const std::string parameter("ucast_solicit");
976
977 std::string value{};
978 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
979 EXPECT_FALSE(value.empty());
980 const int ival = std::stoi(value);
981 EXPECT_GT(ival, 0);
982 // Try doubling the parameter value (always best!).
983 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
984 .isOk());
985 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
986 EXPECT_EQ(2 * ival, std::stoi(value));
987 // Try resetting the parameter.
988 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
989 .isOk());
990 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
991 EXPECT_EQ(ival, std::stoi(value));
992}
993
Ben Schwartze7601812017-04-28 16:38:29 -0400994static std::string base64Encode(const std::vector<uint8_t>& input) {
995 size_t out_len;
996 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
997 // out_len includes the trailing NULL.
998 uint8_t output_bytes[out_len];
999 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
1000 return std::string(reinterpret_cast<char*>(output_bytes));
1001}
1002
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001003TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +09001004 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -04001005 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001006 std::vector<uint8_t> short_fp(1);
1007 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
1008 std::vector<std::string> test_domains;
1009 std::vector<int> test_params = { 300, 25, 8, 8 };
1010 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -04001011 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001012 const std::vector<std::string> servers;
1013 const std::string tlsName;
1014 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -04001015 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +09001016 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001017 { {"192.0.2.1"}, "", {}, 0 },
1018 { {"2001:db8::2"}, "host.name", {}, 0 },
1019 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
1020 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +09001021 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001022 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +09001023 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001024 { {"2001:dg8::6"}, "", {}, EINVAL },
1025 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
1026 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
1027 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
1028 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -04001029 };
1030
Sehee Park8659b8d2018-11-16 10:53:16 +09001031 for (size_t i = 0; i < std::size(kTlsTestData); i++) {
Erik Klinea1476fb2018-03-04 21:01:56 +09001032 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -04001033
1034 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001035 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -04001036 fingerprints.push_back(base64Encode(fingerprint));
1037 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001038 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001039 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
1040 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -04001041
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001042 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +09001043 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Ben Schwartze7601812017-04-28 16:38:29 -04001044 SCOPED_TRACE(status.toString8());
1045 EXPECT_EQ(0, status.exceptionCode());
1046 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +09001047 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Ben Schwartze7601812017-04-28 16:38:29 -04001048 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001049 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -04001050 }
Ben Schwartze7601812017-04-28 16:38:29 -04001051 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001052 // Ensure TLS is disabled before the start of the next test.
1053 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001054 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1055 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001056}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001057
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001058namespace {
1059
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001060void expectNoTestCounterRules() {
1061 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1062 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1063 std::string allRules = Join(runCommand(command), "\n");
1064 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1065 }
1066}
1067
Bernie Innocentif6918262018-06-11 17:37:35 +09001068void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1069 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001070 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1071 path, if1.c_str(), if2.c_str(), pkt, byte));
1072}
1073
Bernie Innocentif6918262018-06-11 17:37:35 +09001074void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001075 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1076 path, if1.c_str(), if2.c_str()));
1077 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1078 path, if2.c_str(), if1.c_str()));
1079}
1080
Luke Huangcaebcbb2018-09-27 20:37:14 +08001081std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1082 const std::string& iface) {
1083 for (auto& stats : statsVec) {
1084 if (stats.iface == iface) {
1085 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1086 }
1087 }
1088 return {};
1089}
1090
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001091} // namespace
1092
1093TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001094 expectNoTestCounterRules();
1095
1096 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1097 // disabling tethering. We don't check the return value because these commands will fail if
1098 // tethering is already enabled.
1099 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1100 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1101
1102 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1103 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1104 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1105 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1106 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1107
1108 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1109 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1110 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1111 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1112 // RX is from external to internal, and TX is from internal to external.
1113 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1114 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1115
1116 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1117 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1118
1119 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1120 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1121
1122 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1123 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1124 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1125
Luke Huangcaebcbb2018-09-27 20:37:14 +08001126 std::vector<TetherStatsParcel> statsVec;
1127 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001128 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1129
Luke Huangcaebcbb2018-09-27 20:37:14 +08001130 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001131
Luke Huangcaebcbb2018-09-27 20:37:14 +08001132 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001133
1134 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1135 delTetherCounterValues(path, intIface1, extIface1);
1136 delTetherCounterValues(path, intIface2, extIface2);
1137 if (path == IP6TABLES_PATH) {
1138 delTetherCounterValues(path, intIface3, extIface2);
1139 }
1140 }
1141
1142 expectNoTestCounterRules();
1143}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001144
Luke Huang0051a622018-07-23 20:30:16 +08001145namespace {
1146
Luke Huanga5211072018-08-01 23:36:29 +08001147constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1148constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001149
1150static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1151 const char* chainName) {
1152 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1153 return runCommand(command);
1154}
1155
Luke Huang19b49c52018-10-22 12:12:05 +09001156// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001157bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001158 const std::string& expectedInterface,
1159 const std::string& expectedRule, const char* table) {
1160 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1161 for (const auto& rule : rules) {
1162 if (rule.find(expectedInterface) != std::string::npos) {
1163 if (rule.find(expectedRule) != std::string::npos) {
1164 return true;
1165 }
1166 }
1167 }
1168 return false;
1169}
1170
1171void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001172 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001173 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001174 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001175 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001176 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1177 IdletimerRule, RAW_TABLE));
1178 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001179 ifname, IdletimerRule, MANGLE_TABLE));
1180 }
1181}
1182
1183void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001184 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001185 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001186 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001187 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001188 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1189 IdletimerRule, RAW_TABLE));
1190 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001191 ifname, IdletimerRule, MANGLE_TABLE));
1192 }
1193}
1194
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001195} // namespace
1196
1197TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001198 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1199 // rule in the table. Because we only check the result after calling remove function. We might
1200 // check the actual rule which is removed by our function (maybe compare the results between
1201 // calling function before and after)
1202 binder::Status status;
1203 const struct TestData {
1204 const std::string ifname;
1205 int32_t timeout;
1206 const std::string classLabel;
1207 } idleTestData[] = {
1208 {"wlan0", 1234, "happyday"},
1209 {"rmnet_data0", 4567, "friday"},
1210 };
1211 for (const auto& td : idleTestData) {
1212 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1213 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1214 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1215
1216 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1217 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1218 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1219 }
1220}
1221
Luke Huanga67dd562018-07-17 19:58:25 +08001222namespace {
1223
1224constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1225constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1226
1227void expectStrictSetUidAccept(const int uid) {
1228 std::string uidRule = StringPrintf("owner UID match %u", uid);
1229 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1230 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1231 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1232 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1233 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1234 }
1235}
1236
1237void expectStrictSetUidLog(const int uid) {
1238 static const char logRule[] = "st_penalty_log all";
1239 std::string uidRule = StringPrintf("owner UID match %u", uid);
1240 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1241 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1242 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1243 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1244 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1245 }
1246}
1247
1248void expectStrictSetUidReject(const int uid) {
1249 static const char rejectRule[] = "st_penalty_reject all";
1250 std::string uidRule = StringPrintf("owner UID match %u", uid);
1251 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1252 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1253 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1254 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1255 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1256 }
1257}
1258
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001259} // namespace
1260
1261TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001262 binder::Status status;
1263 int32_t uid = randomUid();
1264
1265 // setUidCleartextPenalty Policy:Log with randomUid
1266 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1267 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1268 expectStrictSetUidLog(uid);
1269
1270 // setUidCleartextPenalty Policy:Accept with randomUid
1271 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1272 expectStrictSetUidAccept(uid);
1273
1274 // setUidCleartextPenalty Policy:Reject with randomUid
1275 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1276 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1277 expectStrictSetUidReject(uid);
1278
1279 // setUidCleartextPenalty Policy:Accept with randomUid
1280 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1281 expectStrictSetUidAccept(uid);
1282
1283 // test wrong policy
1284 int32_t wrongPolicy = -123;
1285 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1286 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1287}
1288
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001289namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001290
Luke Huanga5211072018-08-01 23:36:29 +08001291bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001292 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1293 return (runCommand(cmd.c_str()).size()) ? true : false;
1294}
1295
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001296} // namespace
1297
1298TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001299 binder::Status status;
1300 // use dummy0 for test since it is set ready
1301 static const char testIf[] = "dummy0";
1302 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1303
1304 status = mNetd->clatdStart(testIf);
1305 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1306 EXPECT_TRUE(processExists(clatdName));
1307
1308 mNetd->clatdStop(testIf);
1309 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1310 EXPECT_FALSE(processExists(clatdName));
1311}
Luke Huang457d4702018-08-16 15:39:15 +08001312
1313namespace {
1314
1315bool getIpfwdV4Enable() {
1316 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1317 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1318 EXPECT_TRUE(!result.empty());
1319 int v4Enable = std::stoi(result[0]);
1320 return v4Enable;
1321}
1322
1323bool getIpfwdV6Enable() {
1324 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1325 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1326 EXPECT_TRUE(!result.empty());
1327 int v6Enable = std::stoi(result[0]);
1328 return v6Enable;
1329}
1330
1331void expectIpfwdEnable(bool enable) {
1332 int enableIPv4 = getIpfwdV4Enable();
1333 int enableIPv6 = getIpfwdV6Enable();
1334 EXPECT_EQ(enable, enableIPv4);
1335 EXPECT_EQ(enable, enableIPv6);
1336}
1337
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001338bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001339 std::vector<std::string> rules = listIpRules(ipVersion);
1340 for (const auto& rule : rules) {
1341 if (rule.find(ipfwdRule) != std::string::npos) {
1342 return true;
1343 }
1344 }
1345 return false;
1346}
1347
1348void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1349 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1350
1351 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1352 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1353 }
1354}
1355
1356void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1357 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1358
1359 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1360 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1361 }
1362}
1363
1364} // namespace
1365
1366TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1367 // Netd default enable Ipfwd with requester NetdHwService
1368 const std::string defaultRequester = "NetdHwService";
1369
1370 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1371 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1372 expectIpfwdEnable(false);
1373
1374 bool ipfwdEnabled;
1375 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1376 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1377 EXPECT_FALSE(ipfwdEnabled);
1378
1379 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1380 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1381 expectIpfwdEnable(true);
1382
1383 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1384 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1385 EXPECT_TRUE(ipfwdEnabled);
1386}
1387
1388TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1389 static const char testFromIf[] = "dummy0";
1390 static const char testToIf[] = "dummy0";
1391
1392 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1393 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1394 expectIpfwdRuleExists(testFromIf, testToIf);
1395
1396 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1397 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1398 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001399}
Luke Huang531f5d32018-08-03 15:19:05 +08001400
1401namespace {
1402
1403constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1404constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1405constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1406constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1407constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001408constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001409
Luke Huang19b49c52018-10-22 12:12:05 +09001410// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1411// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001412bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1413 const char* chainName, const std::string& expectedTargetA,
1414 const std::string& expectedTargetB) {
1415 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1416 int matchCount = 0;
1417
1418 for (const auto& rule : rules) {
1419 if (rule.find(expectedTargetA) != std::string::npos) {
1420 if (rule.find(expectedTargetB) != std::string::npos) {
1421 matchCount++;
1422 }
1423 }
1424 }
1425 return matchCount == expectedCount;
1426}
1427
1428void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1429 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1430 std::string result = "";
1431
1432 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001433 // Quota value might be decreased while matching packets
1434 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001435}
1436
1437void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1438 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1439 std::string quotaRule = StringPrintf("quota %s", ifname);
1440
1441 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1442 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1443 BANDWIDTH_COSTLY_IF));
1444 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1445 BANDWIDTH_COSTLY_IF));
1446 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1447 BANDWIDTH_COSTLY_IF));
1448 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1449 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1450 }
1451 expectXtQuotaValueEqual(ifname, quotaBytes);
1452}
1453
1454void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1455 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1456 std::string quotaRule = StringPrintf("quota %s", ifname);
1457
1458 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1459 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1460 BANDWIDTH_COSTLY_IF));
1461 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1462 BANDWIDTH_COSTLY_IF));
1463 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1464 BANDWIDTH_COSTLY_IF));
1465 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1466 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1467 }
1468}
1469
1470void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1471 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1472 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1473 std::string alertName = StringPrintf("%sAlert", ifname);
1474
1475 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1476 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1477 }
1478 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1479}
1480
1481void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1482 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1483 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1484
1485 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1486 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1487 }
1488}
1489
1490void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1491 static const char globalAlertRule[] = "quota globalAlert";
1492 static const char globalAlertName[] = "globalAlert";
1493
1494 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001495 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001496 }
1497 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1498}
1499
1500void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1501 std::string uidRule = StringPrintf("owner UID match %u", uid);
1502
1503 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1504 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1505 }
1506}
1507
1508void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1509 std::string uidRule = StringPrintf("owner UID match %u", uid);
1510
1511 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1512 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1513 }
1514}
1515
1516} // namespace
1517
1518TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1519 long testQuotaBytes = 5550;
1520
1521 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001522 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001523 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1524
1525 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1526 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1527 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1528
1529 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1530 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1531 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1532
1533 // Remove test physical network
1534 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1535}
1536
1537TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1538 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001539 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001540 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001541 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001542 // Need to have a prior interface quota set to set an alert
1543 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1544 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1545 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1546 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1547
1548 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1549 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1550 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1551
1552 // Remove interface quota
1553 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1554 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1555 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1556
1557 // Remove test physical network
1558 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1559}
1560
1561TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1562 long testAlertBytes = 2097149;
1563
1564 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1565 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1566 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1567
1568 testAlertBytes = 2097152;
1569 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1570 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1571 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1572}
1573
1574TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1575 SKIP_IF_BPF_SUPPORTED;
1576
1577 int32_t uid = randomUid();
1578 static const char targetReject[] = "REJECT";
1579 static const char targetReturn[] = "RETURN";
1580
1581 // add NaughtyApp
1582 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1583 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1584 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1585
1586 // remove NaughtyApp
1587 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1588 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1589 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1590
1591 // add NiceApp
1592 status = mNetd->bandwidthAddNiceApp(uid);
1593 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1594 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1595
1596 // remove NiceApp
1597 status = mNetd->bandwidthRemoveNiceApp(uid);
1598 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1599 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1600}
Luke Huangb5733d72018-08-21 17:17:19 +08001601
1602namespace {
1603
Luke Huangb670d162018-08-23 20:01:13 +08001604std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1605 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1606 return runCommand(command);
1607}
1608
Luke Huangc3252cc2018-10-16 15:43:23 +08001609bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001610 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1611 for (const auto& route : routes) {
1612 if (route.find(ipRoute) != std::string::npos) {
1613 return true;
1614 }
1615 }
1616 return false;
1617}
1618
Luke Huangc3252cc2018-10-16 15:43:23 +08001619std::string ipRouteString(const std::string& ifName, const std::string& dst,
1620 const std::string& nextHop) {
1621 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1622
1623 if (!nextHop.empty()) {
1624 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001625 }
1626
Luke Huangc3252cc2018-10-16 15:43:23 +08001627 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001628}
1629
Luke Huangc3252cc2018-10-16 15:43:23 +08001630void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1631 const std::string& dst, const std::string& nextHop,
1632 const char* table) {
1633 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1634}
1635
1636void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001637 const std::string& dst, const std::string& nextHop,
1638 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001639 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001640}
1641
1642bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1643 std::vector<std::string> rules = listIpRules(ipVersion);
1644 for (const auto& rule : rules) {
1645 if (rule.find(ipRule) != std::string::npos) {
1646 return true;
1647 }
1648 }
1649 return false;
1650}
1651
1652void expectNetworkDefaultIpRuleExists(const char* ifName) {
1653 std::string networkDefaultRule =
1654 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1655
1656 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1657 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1658 }
1659}
1660
1661void expectNetworkDefaultIpRuleDoesNotExist() {
1662 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1663
1664 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1665 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1666 }
1667}
1668
1669void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1670 std::string networkPermissionRule = "";
1671 switch (permission) {
1672 case INetd::PERMISSION_NONE:
1673 networkPermissionRule = StringPrintf(
1674 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1675 break;
1676 case INetd::PERMISSION_NETWORK:
1677 networkPermissionRule = StringPrintf(
1678 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1679 break;
1680 case INetd::PERMISSION_SYSTEM:
1681 networkPermissionRule = StringPrintf(
1682 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1683 break;
1684 }
1685
1686 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1687 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1688 }
1689}
1690
1691// TODO: It is a duplicate function, need to remove it
1692bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1693 const std::string& expectedInterface,
1694 const std::string& expectedRule,
1695 const char* table) {
1696 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1697 for (const auto& rule : rules) {
1698 if (rule.find(expectedInterface) != std::string::npos) {
1699 if (rule.find(expectedRule) != std::string::npos) {
1700 return true;
1701 }
1702 }
1703 }
1704 return false;
1705}
1706
1707void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1708 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1709 std::string networkIncomingPacketMarkRule = "";
1710 switch (permission) {
1711 case INetd::PERMISSION_NONE:
1712 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1713 break;
1714 case INetd::PERMISSION_NETWORK:
1715 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1716 break;
1717 case INetd::PERMISSION_SYSTEM:
1718 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1719 break;
1720 }
1721
1722 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1723 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1724 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1725 }
1726}
1727
1728} // namespace
1729
1730TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001731 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001732 const char* ipVersion;
1733 const char* testDest;
1734 const char* testNextHop;
1735 const bool expectSuccess;
1736 } kTestData[] = {
1737 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001738 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1739 {IP_RULE_V4, "10.251.0.0/16", "", true},
1740 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1741 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001742 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001743 {IP_RULE_V6, "::/0", "2001:db8::", true},
1744 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001745 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1746 };
1747
Luke Huangc3252cc2018-10-16 15:43:23 +08001748 static const struct {
1749 const char* ipVersion;
1750 const char* testDest;
1751 const char* testNextHop;
1752 } kTestDataWithNextHop[] = {
1753 {IP_RULE_V4, "10.251.10.0/30", ""},
1754 {IP_RULE_V6, "2001:db8::/32", ""},
1755 };
1756
Luke Huangb670d162018-08-23 20:01:13 +08001757 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001758 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001759 const int testUid = randomUid();
1760 const std::vector<int32_t> testUids = {testUid};
1761
1762 // Add test physical network
1763 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1764 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1765
Luke Huangc3252cc2018-10-16 15:43:23 +08001766 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001767 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001768 const auto& td = kTestDataWithNextHop[i];
1769
1770 // All route for test tun will disappear once the tun interface is deleted.
1771 binder::Status status =
1772 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1773 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1774 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1775 sTun.name().c_str());
1776
1777 // Add system permission for test uid, setup route in legacy system table.
1778 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, 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 testTableLegacySystem);
1785
1786 // Remove system permission for test uid, setup route in legacy network table.
1787 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1788
1789 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1790 testUid);
1791 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1792 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1793 testTableLegacyNetwork);
1794 }
1795
Sehee Park8659b8d2018-11-16 10:53:16 +09001796 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001797 const auto& td = kTestData[i];
1798
1799 binder::Status status =
1800 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1801 if (td.expectSuccess) {
1802 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001803 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001804 sTun.name().c_str());
1805 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001806 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1807 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001808 }
1809
1810 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1811 if (td.expectSuccess) {
1812 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001813 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1814 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001815 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001816 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1817 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001818 }
1819
Luke Huangc3252cc2018-10-16 15:43:23 +08001820 // Add system permission for test uid, route will be added into legacy system table.
1821 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001822
1823 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1824 testUid);
1825 if (td.expectSuccess) {
1826 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001827 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001828 testTableLegacySystem);
1829 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001830 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1831 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001832 }
1833
1834 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1835 td.testNextHop, testUid);
1836 if (td.expectSuccess) {
1837 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001838 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1839 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001840 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001841 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1842 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001843 }
1844
Luke Huangc3252cc2018-10-16 15:43:23 +08001845 // Remove system permission for test uid, route will be added into legacy network table.
1846 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1847
1848 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1849 testUid);
1850 if (td.expectSuccess) {
1851 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1852 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1853 testTableLegacyNetwork);
1854 } else {
1855 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1856 EXPECT_NE(0, status.serviceSpecificErrorCode());
1857 }
1858
1859 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1860 td.testNextHop, testUid);
1861 if (td.expectSuccess) {
1862 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1863 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1864 testTableLegacyNetwork);
1865 } else {
1866 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1867 EXPECT_NE(0, status.serviceSpecificErrorCode());
1868 }
Luke Huangb670d162018-08-23 20:01:13 +08001869 }
1870
1871 // Remove test physical network
1872 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1873}
1874
1875TEST_F(BinderTest, NetworkPermissionDefault) {
1876 // Add test physical network
1877 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1878 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1879
Luke Huangc3252cc2018-10-16 15:43:23 +08001880 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001881 int currentNetid;
1882 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1883 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1884
1885 // Test SetDefault
1886 status = mNetd->networkSetDefault(TEST_NETID1);
1887 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1888 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1889
1890 status = mNetd->networkClearDefault();
1891 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1892 expectNetworkDefaultIpRuleDoesNotExist();
1893
1894 // Add default network back
1895 status = mNetd->networkSetDefault(currentNetid);
1896 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1897
1898 // Test SetPermission
1899 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1900 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1901 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1902 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1903
1904 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1905 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1906 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1907 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1908
1909 // Remove test physical network
1910 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1911}
1912
1913TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1914 const int testUid = randomUid();
1915 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1916 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1917 bool ret = false;
1918 status = mNetd->networkCanProtect(testUid, &ret);
1919 EXPECT_TRUE(ret);
1920
1921 status = mNetd->networkSetProtectDeny(testUid);
1922 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1923 status = mNetd->networkCanProtect(testUid, &ret);
1924 EXPECT_FALSE(ret);
1925}
1926
1927namespace {
1928
Luke Huangb5733d72018-08-21 17:17:19 +08001929int readIntFromPath(const std::string& path) {
1930 std::string result = "";
1931 EXPECT_TRUE(ReadFileToString(path, &result));
1932 return std::stoi(result);
1933}
1934
1935int getTetherAcceptIPv6Ra(const std::string& ifName) {
1936 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1937 return readIntFromPath(path);
1938}
1939
1940bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1941 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1942 return readIntFromPath(path);
1943}
1944
1945int getTetherIPv6DadTransmits(const std::string& ifName) {
1946 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1947 return readIntFromPath(path);
1948}
1949
1950bool getTetherEnableIPv6(const std::string& ifName) {
1951 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1952 int disableIPv6 = readIntFromPath(path);
1953 return !disableIPv6;
1954}
1955
1956bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1957 for (const auto& iface : ifList) {
1958 if (iface == ifName) {
1959 return true;
1960 }
1961 }
1962 return false;
1963}
1964
1965void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1966 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1967 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1968 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1969 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1970}
1971
1972void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1973 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1974 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1975 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1976 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1977}
1978
1979void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1980 const std::string& ifName) {
1981 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1982}
1983
1984void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1985 const std::string& ifName) {
1986 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1987}
1988
1989void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
1990 const std::vector<std::string>& testDnsAddrs) {
1991 EXPECT_TRUE(dnsList == testDnsAddrs);
1992}
1993
1994} // namespace
1995
1996TEST_F(BinderTest, TetherStartStopStatus) {
1997 std::vector<std::string> noDhcpRange = {};
1998 static const char dnsdName[] = "dnsmasq";
1999
2000 binder::Status status = mNetd->tetherStart(noDhcpRange);
2001 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2002 EXPECT_TRUE(processExists(dnsdName));
2003
2004 bool tetherEnabled;
2005 status = mNetd->tetherIsEnabled(&tetherEnabled);
2006 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2007 EXPECT_TRUE(tetherEnabled);
2008
2009 status = mNetd->tetherStop();
2010 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2011 EXPECT_FALSE(processExists(dnsdName));
2012
2013 status = mNetd->tetherIsEnabled(&tetherEnabled);
2014 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2015 EXPECT_FALSE(tetherEnabled);
2016}
2017
2018TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2019 // TODO: verify if dnsmasq update interface successfully
2020
2021 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2022 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2023 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2024
2025 std::vector<std::string> ifList;
2026 status = mNetd->tetherInterfaceList(&ifList);
2027 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2028 expectTetherInterfaceExists(ifList, sTun.name());
2029
2030 status = mNetd->tetherInterfaceRemove(sTun.name());
2031 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2032 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2033
2034 status = mNetd->tetherInterfaceList(&ifList);
2035 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2036 expectTetherInterfaceNotExists(ifList, sTun.name());
2037}
2038
2039TEST_F(BinderTest, TetherDnsSetList) {
2040 // TODO: verify if dnsmasq update dns successfully
2041 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
2042
2043 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2044 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2045
2046 std::vector<std::string> dnsList;
2047 status = mNetd->tetherDnsList(&dnsList);
2048 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2049 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002050}
2051
2052namespace {
2053
2054constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2055constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2056constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2057constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2058constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2059constexpr char FIREWALL_STANDBY[] = "fw_standby";
2060constexpr char targetReturn[] = "RETURN";
2061constexpr char targetDrop[] = "DROP";
2062
2063void expectFirewallWhitelistMode() {
2064 static const char dropRule[] = "DROP all";
2065 static const char rejectRule[] = "REJECT all";
2066 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2067 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2068 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2069 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2070 }
2071}
2072
2073void expectFirewallBlacklistMode() {
2074 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2075 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2076 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2077 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2078 }
2079}
2080
2081bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2082 const std::string& expectedInterface,
2083 const std::string& expectedRule) {
2084 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2085 // Expected rule:
2086 // Chain fw_INPUT (1 references)
2087 // pkts bytes target prot opt in out source destination
2088 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2089 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2090 int firstRuleIndex = 2;
2091 if (rules.size() < 4) return false;
2092 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2093 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2094 return true;
2095 }
2096 }
2097 return false;
2098}
2099
2100// TODO: It is a duplicate function, need to remove it
2101bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2102 const std::string& expectedInterface,
2103 const std::string& expectedRule) {
2104 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2105 for (const auto& rule : rules) {
2106 if (rule.find(expectedInterface) != std::string::npos) {
2107 if (rule.find(expectedRule) != std::string::npos) {
2108 return true;
2109 }
2110 }
2111 }
2112 return false;
2113}
2114
2115void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2116 static const char returnRule[] = "RETURN all";
2117 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2118 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2119 returnRule));
2120 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2121 returnRule));
2122 }
2123}
2124
2125void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2126 static const char returnRule[] = "RETURN all";
2127 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2128 EXPECT_FALSE(
2129 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2130 EXPECT_FALSE(
2131 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2132 }
2133}
2134
2135bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2136 const std::string& expectedTarget,
2137 const std::string& expectedRule) {
2138 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2139 int firstRuleIndex = 2;
2140 if (rules.size() < 4) return false;
2141 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2142 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2143 return true;
2144 }
2145 }
2146 return false;
2147}
2148
2149bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2150 const std::string& expectedTarget,
2151 const std::string& expectedRule) {
2152 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2153 int lastRuleIndex = rules.size() - 1;
2154 if (lastRuleIndex < 0) return false;
2155 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2156 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2157 return true;
2158 }
2159 }
2160 return false;
2161}
2162
2163void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2164 std::string uidRule = StringPrintf("owner UID match %u", uid);
2165 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2166 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2167}
2168
2169void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2170 std::string uidRule = StringPrintf("owner UID match %u", uid);
2171 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2172 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2173}
2174
2175void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2176 std::string uidRule = StringPrintf("owner UID match %u", uid);
2177 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2178 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2179}
2180
2181void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2182 std::string uidRule = StringPrintf("owner UID match %u", uid);
2183 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2184 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2185}
2186
2187bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2188 std::vector<std::string> inputRules =
2189 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2190 std::vector<std::string> outputRules =
2191 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2192 int inputLastRuleIndex = inputRules.size() - 1;
2193 int outputLastRuleIndex = outputRules.size() - 1;
2194
2195 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2196 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2197 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2198 return true;
2199 }
2200 }
2201 return false;
2202}
2203
2204void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2205 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2206 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2207}
2208
2209void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2210 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2211 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2212 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2213 }
2214}
2215
2216} // namespace
2217
2218TEST_F(BinderTest, FirewallSetFirewallType) {
2219 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2220 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2221 expectFirewallWhitelistMode();
2222
2223 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2224 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2225 expectFirewallBlacklistMode();
2226
2227 // set firewall type blacklist twice
2228 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2229 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2230 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2231 expectFirewallBlacklistMode();
2232
2233 // set firewall type whitelist twice
2234 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2235 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2236 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2237 expectFirewallWhitelistMode();
2238
2239 // reset firewall type to default
2240 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2241 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2242 expectFirewallBlacklistMode();
2243}
2244
2245TEST_F(BinderTest, FirewallSetInterfaceRule) {
2246 // setinterfaceRule is not supported in BLACKLIST MODE
2247 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2248 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2249
2250 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2251 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2252
2253 // set WHITELIST mode first
2254 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2255 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2256
2257 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2258 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2259 expectFirewallInterfaceRuleAllowExists(sTun.name());
2260
2261 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2262 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2263 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2264
2265 // reset firewall mode to default
2266 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2267 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2268 expectFirewallBlacklistMode();
2269}
2270
2271TEST_F(BinderTest, FirewallSetUidRule) {
2272 SKIP_IF_BPF_SUPPORTED;
2273
2274 int32_t uid = randomUid();
2275
2276 // Doze allow
2277 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2278 INetd::FIREWALL_RULE_ALLOW);
2279 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2280 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2281
2282 // Doze deny
2283 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2284 INetd::FIREWALL_RULE_DENY);
2285 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2286 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2287
2288 // Powersave allow
2289 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2290 INetd::FIREWALL_RULE_ALLOW);
2291 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2292 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2293
2294 // Powersave deny
2295 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2296 INetd::FIREWALL_RULE_DENY);
2297 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2298 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2299
2300 // Standby deny
2301 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2302 INetd::FIREWALL_RULE_DENY);
2303 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2304 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2305
2306 // Standby allow
2307 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2308 INetd::FIREWALL_RULE_ALLOW);
2309 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2310 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2311
2312 // None deny in BLACKLIST
2313 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2314 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2315 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2316 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2317
2318 // None allow in BLACKLIST
2319 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2320 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2321 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2322 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2323
2324 // set firewall type whitelist twice
2325 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2326 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2327 expectFirewallWhitelistMode();
2328
2329 // None allow in WHITELIST
2330 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2331 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2332 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2333 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2334
2335 // None deny in WHITELIST
2336 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2337 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2338 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2339 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2340
2341 // reset firewall mode to default
2342 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2343 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2344 expectFirewallBlacklistMode();
2345}
2346
2347TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2348 SKIP_IF_BPF_SUPPORTED;
2349
2350 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2351 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2352 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2353
2354 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2355 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2356 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2357
2358 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2359 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2360 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2361
2362 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2363 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2364 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2365
2366 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2367 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2368 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2369
2370 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2371 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2372 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2373}
Luke Huangf7782042018-08-08 13:13:04 +08002374
2375namespace {
2376
2377std::string hwAddrToStr(unsigned char* hwaddr) {
2378 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2379 hwaddr[4], hwaddr[5]);
2380}
2381
2382int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2383 int prefixLength = 0;
2384 uint32_t m = ntohl(mask);
2385 while (m & (1 << 31)) {
2386 prefixLength++;
2387 m = m << 1;
2388 }
2389 return prefixLength;
2390}
2391
2392std::string toStdString(const String16& s) {
2393 return std::string(String8(s.string()));
2394}
2395
2396android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2397 const auto& sys = sSyscalls.get();
2398 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2399 EXPECT_TRUE(isOk(fd.status()));
2400
2401 struct ifreq ifr = {};
2402 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2403
2404 return sys.ioctl(fd.value(), flag, &ifr);
2405}
2406
2407std::string getInterfaceHwAddr(const std::string& ifName) {
2408 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2409
2410 unsigned char hwaddr[ETH_ALEN] = {};
2411 if (isOk(res.status())) {
2412 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2413 }
2414
2415 return hwAddrToStr(hwaddr);
2416}
2417
2418int getInterfaceIPv4Prefix(const std::string& ifName) {
2419 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2420
2421 int prefixLength = 0;
2422 if (isOk(res.status())) {
2423 prefixLength = ipv4NetmaskToPrefixLength(
2424 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2425 }
2426
2427 return prefixLength;
2428}
2429
2430std::string getInterfaceIPv4Addr(const std::string& ifName) {
2431 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2432
2433 struct in_addr addr = {};
2434 if (isOk(res.status())) {
2435 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2436 }
2437
2438 return std::string(inet_ntoa(addr));
2439}
2440
2441std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2442 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2443
2444 unsigned flags = 0;
2445 if (isOk(res.status())) {
2446 flags = res.value().ifr_flags;
2447 }
2448
2449 std::vector<std::string> ifFlags;
2450 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2451 : toStdString(INetd::IF_STATE_DOWN()));
2452
2453 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2454 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2455 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2456 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2457 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2458
2459 return ifFlags;
2460}
2461
2462bool compareListInterface(const std::vector<std::string>& interfaceList) {
2463 const auto& res = InterfaceController::getIfaceNames();
2464 EXPECT_TRUE(isOk(res));
2465
2466 std::vector<std::string> resIfList;
2467 resIfList.reserve(res.value().size());
2468 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2469
2470 return resIfList == interfaceList;
2471}
2472
2473int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2474 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2475 return readIntFromPath(path);
2476}
2477
2478bool getInterfaceEnableIPv6(const std::string& ifName) {
2479 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2480
2481 int disableIPv6 = readIntFromPath(path);
2482 return !disableIPv6;
2483}
2484
2485int getInterfaceMtu(const std::string& ifName) {
2486 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2487 return readIntFromPath(path);
2488}
2489
2490void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2491 EXPECT_TRUE(compareListInterface(interfaceList));
2492}
2493
2494void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2495 const InterfaceConfigurationParcel& interfaceCfg) {
2496 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2497 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2498 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2499 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2500}
2501
2502void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2503 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2504 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2505
2506 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2507 for (const auto& flag : setCfg.flags) {
2508 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2509 }
2510}
2511
2512void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2513 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2514 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2515}
2516
2517void expectInterfaceNoAddr(const std::string& ifName) {
2518 // noAddr
2519 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2520 // noPrefix
2521 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2522}
2523
2524void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2525 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2526 EXPECT_EQ(enableIPv6, enable);
2527}
2528
2529void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2530 int mtuSize = getInterfaceMtu(ifName);
2531 EXPECT_EQ(mtu, mtuSize);
2532}
2533
2534InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2535 const std::string& addr, int prefixLength,
2536 const std::vector<std::string>& flags) {
2537 InterfaceConfigurationParcel cfg;
2538 cfg.ifName = ifName;
2539 cfg.hwAddr = "";
2540 cfg.ipv4Addr = addr;
2541 cfg.prefixLength = prefixLength;
2542 cfg.flags = flags;
2543 return cfg;
2544}
2545
2546void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2547 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2548 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2549
2550 for (const auto& flag : expectedFlags) {
2551 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2552 interfaceCfg.flags.end());
2553 }
2554
2555 for (const auto& flag : unexpectedFlags) {
2556 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2557 interfaceCfg.flags.end());
2558 }
2559}
2560
2561} // namespace
2562
2563TEST_F(BinderTest, InterfaceList) {
2564 std::vector<std::string> interfaceListResult;
2565
2566 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2567 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2568 expectInterfaceList(interfaceListResult);
2569}
2570
2571TEST_F(BinderTest, InterfaceGetCfg) {
2572 InterfaceConfigurationParcel interfaceCfgResult;
2573
2574 // Add test physical network
2575 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2576 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2577
2578 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2579 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2580 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2581 expectTunFlags(interfaceCfgResult);
2582
2583 // Remove test physical network
2584 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2585}
2586
2587TEST_F(BinderTest, InterfaceSetCfg) {
2588 const std::string testAddr = "192.0.2.3";
2589 const int testPrefixLength = 24;
2590 std::vector<std::string> upFlags = {"up"};
2591 std::vector<std::string> downFlags = {"down"};
2592
2593 // Add test physical network
2594 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2595 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2596
2597 // Set tun interface down.
2598 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2599 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2600 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2601 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2602
2603 // Set tun interface up again.
2604 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2605 status = mNetd->interfaceSetCfg(interfaceCfg);
2606 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2607 status = mNetd->interfaceClearAddrs(sTun.name());
2608 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2609
2610 // Remove test physical network
2611 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2612}
2613
2614TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2615 // enable
2616 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2617 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2618 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2619
2620 // disable
2621 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2622 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2623 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2624}
2625
2626TEST_F(BinderTest, InterfaceClearAddr) {
2627 const std::string testAddr = "192.0.2.3";
2628 const int testPrefixLength = 24;
2629 std::vector<std::string> noFlags{};
2630
2631 // Add test physical network
2632 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2633 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2634
2635 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2636 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2637 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2638 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2639
2640 status = mNetd->interfaceClearAddrs(sTun.name());
2641 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2642 expectInterfaceNoAddr(sTun.name());
2643
2644 // Remove test physical network
2645 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2646}
2647
2648TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2649 // Add test physical network
2650 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2651 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2652
2653 // disable
2654 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2655 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2656 expectInterfaceEnableIPv6(sTun.name(), false);
2657
2658 // enable
2659 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2660 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2661 expectInterfaceEnableIPv6(sTun.name(), true);
2662
2663 // Remove test physical network
2664 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2665}
2666
2667TEST_F(BinderTest, InterfaceSetMtu) {
2668 const int testMtu = 1200;
2669
2670 // Add test physical network
2671 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2672 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2673
2674 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2675 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2676 expectInterfaceMtu(sTun.name(), testMtu);
2677
2678 // Remove test physical network
2679 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2680}
Luke Huang19b49c52018-10-22 12:12:05 +09002681
2682namespace {
2683
2684constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2685constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002686constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002687constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2688
Luke Huangae038f82018-11-05 11:17:31 +09002689int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002690 return listIptablesRuleByTable(binary, table, chainName).size();
2691}
2692
2693bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2694 const std::vector<std::string>& targetVec) {
2695 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2696 if (targetVec.size() != rules.size() - 2) {
2697 return false;
2698 }
2699
2700 /*
Luke Huangae038f82018-11-05 11:17:31 +09002701 * Check that the rules match. Note that this function matches substrings, not entire rules,
2702 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002703 * Skip first two lines since rules start from third line.
2704 * Chain chainName (x references)
2705 * pkts bytes target prot opt in out source destination
2706 * ...
2707 */
2708 int rIndex = 2;
2709 for (const auto& target : targetVec) {
2710 if (rules[rIndex].find(target) == std::string::npos) {
2711 return false;
2712 }
2713 rIndex++;
2714 }
2715 return true;
2716}
2717
2718void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2719 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2720 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2721 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002722 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002723 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2724 "DROP"};
2725
2726 // V4
2727 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2728 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002729 EXPECT_TRUE(
2730 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002731 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2732
Luke Huangae038f82018-11-05 11:17:31 +09002733 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002734 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2735
2736 // V6
2737 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002738 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2739 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002740
2741 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2742 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2743 extIf));
2744 }
2745}
2746
2747void expectNatDisable() {
2748 // It is the default DROP rule with tethering disable.
2749 // Chain tetherctrl_FORWARD (1 references)
2750 // pkts bytes target prot opt in out source destination
2751 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2752 std::vector<std::string> forwardV4Match = {"DROP"};
2753 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2754
2755 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002756 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2757 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002758
Luke Huangae038f82018-11-05 11:17:31 +09002759 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2760 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002761
2762 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2763}
2764
2765} // namespace
2766
2767TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002768 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2769 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2770 expectNatEnable(sTun.name(), sTun2.name());
2771
2772 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2773 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2774 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002775}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002776
2777namespace {
2778
2779using TripleInt = std::array<int, 3>;
2780
2781TripleInt readProcFileToTripleInt(const std::string& path) {
2782 std::string valueString;
2783 int min, def, max;
2784 EXPECT_TRUE(ReadFileToString(path, &valueString));
2785 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2786 return {min, def, max};
2787}
2788
2789void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2790 std::string testRmemValues =
2791 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2792 std::string testWmemValues =
2793 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2794 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2795
2796 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2797 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2798
2799 for (int i = 0; i < 3; i++) {
2800 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2801 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2802 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2803 }
2804}
2805
2806} // namespace
2807
2808TEST_F(BinderTest, TcpBufferSet) {
2809 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2810 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2811 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2812 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2813
2814 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2815 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2816}
Luke Huang528af602018-08-29 19:06:05 +08002817
Chenbo Feng48eaed32018-12-26 17:40:21 -08002818namespace {
2819
2820void checkUidsExist(std::vector<int32_t>& uids, bool exist) {
2821 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2822 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2823 for (int32_t uid : uids) {
2824 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2825 if (exist) {
2826 EXPECT_TRUE(isOk(permission));
2827 EXPECT_EQ(ALLOW_SOCK_CREATE, permission.value());
2828 } else {
2829 EXPECT_FALSE(isOk(permission));
2830 EXPECT_EQ(ENOENT, permission.status().code());
2831 }
2832 }
2833}
2834
2835} // namespace
2836
2837TEST_F(BinderTest, TestInternetPermission) {
2838 SKIP_IF_BPF_NOT_SUPPORTED;
2839
2840 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2841
2842 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
2843 checkUidsExist(appUids, true);
2844 mNetd->trafficSetNetPermForUids(INetd::NO_PERMISSIONS, appUids);
2845 checkUidsExist(appUids, false);
2846}
2847
Luke Huang528af602018-08-29 19:06:05 +08002848TEST_F(BinderTest, UnsolEvents) {
2849 auto testUnsolService = android::net::TestUnsolService::start();
2850 std::string oldTunName = sTun.name();
2851 std::string newTunName = "unsolTest";
2852 testUnsolService->tarVec.push_back(oldTunName);
2853 testUnsolService->tarVec.push_back(newTunName);
2854 auto& cv = testUnsolService->getCv();
2855 auto& cvMutex = testUnsolService->getCvMutex();
2856 binder::Status status = mNetd->registerUnsolicitedEventListener(
2857 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2858 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2859
2860 // TODO: Add test for below events
2861 // StrictCleartextDetected / InterfaceDnsServersAdded
2862 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2863
2864 {
2865 std::unique_lock lock(cvMutex);
2866
2867 // Re-init test Tun, and we expect that we will get some unsol events.
2868 // Use the test Tun device name to verify if we receive its unsol events.
2869 sTun.destroy();
2870 // Use predefined name
2871 sTun.init(newTunName);
2872
2873 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2874 }
2875
2876 // bit mask 1101101000
2877 // Test only covers below events currently
2878 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2879 InterfaceLinkStatusChanged | RouteChanged;
2880 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Bernie Innocentia5161a02019-01-30 22:40:53 +09002881}