blob: caab84f54bb7ed1f84c3e7d81abc077c50d3ba40 [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;
74namespace netdutils = android::netdutils;
75
76using android::IBinder;
77using android::IServiceManager;
78using android::sp;
79using android::String16;
80using android::String8;
81using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080082using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090083using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090084using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080085using android::base::Trim;
Chenbo Fengf5663d82018-11-08 16:10:48 -080086using android::base::WriteStringToFile;
Chenbo Feng837ddfc2018-05-08 13:45:08 -070087using android::bpf::hasBpfSupport;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090088using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080089using android::net::InterfaceConfigurationParcel;
90using android::net::InterfaceController;
Luke Huangcaebcbb2018-09-27 20:37:14 +080091using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090092using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090093using android::net::UidRangeParcel;
Nathan Harold21299f72018-03-16 20:13:03 -070094using android::net::XfrmController;
Luke Huangf7782042018-08-08 13:13:04 +080095using android::netdutils::sSyscalls;
Robin Leeb8087362016-03-30 18:43:08 +010096
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090097#define SKIP_IF_BPF_SUPPORTED \
98 do { \
99 if (hasBpfSupport()) return; \
100 } while (0)
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700101
Robin Leeb8087362016-03-30 18:43:08 +0100102static const char* IP_RULE_V4 = "-4";
103static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900104static const int TEST_NETID1 = 65501;
105static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -0800106
107// Use maximum reserved appId for applications to avoid conflict with existing
108// uids.
109static const int TEST_UID1 = 99999;
110static const int TEST_UID2 = 99998;
111
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900112constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900113
Benedict Wongb2daefb2017-12-06 22:05:46 -0800114static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
115static const std::string ESP_ALLOW_RULE("esp");
116
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900117class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900118 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900119 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900120 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900121 sp<IBinder> binder = sm->getService(String16("netd"));
122 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900123 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900124 }
125 }
126
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900127 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900128 ASSERT_NE(nullptr, mNetd.get());
129 }
130
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900131 void TearDown() override {
132 mNetd->networkDestroy(TEST_NETID1);
133 mNetd->networkDestroy(TEST_NETID2);
134 }
135
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900136 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700137
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900138 // Static because setting up the tun interface takes about 40ms.
139 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900140 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900141 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900142 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900143 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900144 }
145
146 static void TearDownTestCase() {
147 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900148 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900149 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900150 }
151
152 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900153
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900154 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900155 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900156 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900157 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900158};
159
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900160TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900161TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900162
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900163class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900164 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700165 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900166 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900167 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900168 }
169
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900170 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900171 std::string mName;
172};
173
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900174TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900175 TimedOperation t("isAlive RPC");
176 bool isAlive = false;
177 mNetd->isAlive(&isAlive);
178 ASSERT_TRUE(isAlive);
179}
180
181static int randomUid() {
182 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
183}
184
Robin Leeb8087362016-03-30 18:43:08 +0100185static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900186 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900187 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
188 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900189 perror("popen");
190 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900191 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900192
193 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100194 size_t bufsize = 0;
195 ssize_t linelen = 0;
196 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900197 lines.push_back(std::string(line, linelen));
198 free(line);
199 line = nullptr;
200 }
201
202 pclose(f);
203 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900204}
205
Robin Leeb8087362016-03-30 18:43:08 +0100206static std::vector<std::string> listIpRules(const char *ipVersion) {
207 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
208 return runCommand(command);
209}
210
211static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900212 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100213 return runCommand(command);
214}
215
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900216static int iptablesRuleLineLength(const char *binary, const char *chainName) {
217 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900218}
219
Benedict Wongb2daefb2017-12-06 22:05:46 -0800220static bool iptablesRuleExists(const char *binary,
221 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900222 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800223 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900224 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800225 if(rule.find(expectedRule) != std::string::npos) {
226 return true;
227 }
228 }
229 return false;
230}
231
232static bool iptablesNoSocketAllowRuleExists(const char *chainName){
233 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
234 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
235}
236
237static bool iptablesEspAllowRuleExists(const char *chainName){
238 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
239 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
240}
241
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900242TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700243 SKIP_IF_BPF_SUPPORTED;
244
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900245 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
246 const int kNumUids = 500;
247 std::vector<int32_t> noUids(0);
248 std::vector<int32_t> uids(kNumUids);
249 for (int i = 0; i < kNumUids; i++) {
250 uids[i] = randomUid();
251 }
252
253 bool ret;
254 {
255 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900256 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900257 }
258 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800259 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
260 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
261 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
262 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900263 {
264 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900265 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900266 }
267 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900268 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
269 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900270
271 {
272 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900273 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900274 }
275 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900276 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
277 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800278 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
279 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900280
281 {
282 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900283 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900284 }
285 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900286 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
287 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900288
289 // Check that the call fails if iptables returns an error.
290 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900291 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900292 EXPECT_EQ(false, ret);
293}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900294
Benedict Wong319f17e2018-05-15 17:06:44 -0700295TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700296 const struct TestData {
297 const std::string family;
298 const std::string deviceName;
299 const std::string localAddress;
300 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800301 int32_t iKey;
302 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700303 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800304 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700305 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
306 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
307 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800308 };
309
Sehee Park8659b8d2018-11-16 10:53:16 +0900310 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700311 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800312
313 binder::Status status;
314
Benedict Wong319f17e2018-05-15 17:06:44 -0700315 // Create Tunnel Interface.
316 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700317 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800318 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
319
Benedict Wonga450e722018-05-07 10:29:02 -0700320 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900321 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700322
Benedict Wong319f17e2018-05-15 17:06:44 -0700323 // Update Tunnel Interface.
324 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700325 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800326 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
327
Benedict Wong319f17e2018-05-15 17:06:44 -0700328 // Remove Tunnel Interface.
329 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800330 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700331
332 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900333 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800334 }
335}
336
Benedict Wong1cb73df2018-12-03 00:54:14 -0800337TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
338 android::base::unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
339 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
340
341 int sockOptVal = UDP_ENCAP_ESPINUDP;
342 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
343
344 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
345 EXPECT_TRUE(res.isOk());
346
347 struct stat info;
348 EXPECT_EQ(0, fstat(sockFd.get(), &info));
349 EXPECT_EQ(1001, (int) info.st_uid);
350}
351
Nathan Harold2deff322018-05-10 14:03:48 -0700352// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
353// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
354#if INTPTR_MAX != INT32_MAX
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) {
Nathan Harold21299f72018-03-16 20:13:03 -0700362 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
363 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) {
378 binder::Status status;
379
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) {
Nathan Harold21299f72018-03-16 20:13:03 -0700426 netdutils::Status status;
427 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}
Nathan Harold2deff322018-05-10 14:03:48 -0700457#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700458
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900459static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900460 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900461
462 // Output looks like this:
463 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900464 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900465 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900466 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900467 //
468 // or:
469 //
470 // Chain bw_data_saver (1 references)
471 // target prot opt source destination
472 // ... possibly connectivity critical packet rules here ...
473 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900474
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900475 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900476
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900477 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
478 // Data saver disabled.
479 return 0;
480 }
481
482 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
483
484 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
485 // Data saver enabled.
486 return 1;
487 }
488
489 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900490}
491
492bool enableDataSaver(sp<INetd>& netd, bool enable) {
493 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
494 bool ret;
495 netd->bandwidthEnableDataSaver(enable, &ret);
496 return ret;
497}
498
499int getDataSaverState() {
500 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
501 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
502 EXPECT_EQ(enabled4, enabled6);
503 EXPECT_NE(-1, enabled4);
504 EXPECT_NE(-1, enabled6);
505 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
506 return -1;
507 }
508 return enabled6;
509}
510
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900511TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900512 const int wasEnabled = getDataSaverState();
513 ASSERT_NE(-1, wasEnabled);
514
515 if (wasEnabled) {
516 ASSERT_TRUE(enableDataSaver(mNetd, false));
517 EXPECT_EQ(0, getDataSaverState());
518 }
519
520 ASSERT_TRUE(enableDataSaver(mNetd, false));
521 EXPECT_EQ(0, getDataSaverState());
522
523 ASSERT_TRUE(enableDataSaver(mNetd, true));
524 EXPECT_EQ(1, getDataSaverState());
525
526 ASSERT_TRUE(enableDataSaver(mNetd, true));
527 EXPECT_EQ(1, getDataSaverState());
528
529 if (!wasEnabled) {
530 ASSERT_TRUE(enableDataSaver(mNetd, false));
531 EXPECT_EQ(0, getDataSaverState());
532 }
533}
Robin Leeb8087362016-03-30 18:43:08 +0100534
Luke Huang94658ac2018-10-18 19:35:12 +0900535static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
536 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100537 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100538 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100539 std::vector<std::string> rules = listIpRules(ipVersion);
540
541 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900542 std::string suffix =
543 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900544 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800545 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100546 return true;
547 }
548 }
549 return false;
550}
551
Luke Huang94658ac2018-10-18 19:35:12 +0900552static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
553 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100554 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
555 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
556 EXPECT_EQ(existsIp4, existsIp6);
557 return existsIp4;
558}
559
Luke Huang94658ac2018-10-18 19:35:12 +0900560namespace {
561
562UidRangeParcel makeUidRangeParcel(int start, int stop) {
563 UidRangeParcel res;
564 res.start = start;
565 res.stop = stop;
566
567 return res;
568}
569
570} // namespace
571
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900572TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800573 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
574 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
575 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900576 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
577 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900578
579 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
580 EXPECT_EQ(EBUSY,
581 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
582
583 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
584 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
585 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800586 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900587}
588
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900589TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900590 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
591
cken67cd14c2018-12-05 17:26:59 +0900592 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
593 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900594 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
595
Luke Huang94658ac2018-10-18 19:35:12 +0900596 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
597 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
598 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900599 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
600
601 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
602
603 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
604 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
605 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
606 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
607
608 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
609 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
610 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
611 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
612
613 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
614}
615
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900616TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100617 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100618
Luke Huang94658ac2018-10-18 19:35:12 +0900619 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
620 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100621
622 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
623 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
624
625 // Create two valid rules.
626 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
627 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
628 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
629 for (auto const& range : uidRanges) {
630 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
631 }
632
633 // Remove the rules.
634 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
635 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
636 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
637 for (auto const& range : uidRanges) {
638 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
639 }
640
641 // Fail to remove the rules a second time after they are already deleted.
642 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
643 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
644 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
645
646 // All rules should be the same as before.
647 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
648 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
649}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900650
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900651// Create a socket pair that isLoopbackSocket won't think is local.
652void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900653 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900654 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900655 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
656
657 socklen_t addrlen = sizeof(server6);
658 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
659 ASSERT_EQ(0, listen(*serverSocket, 10));
660
Bernie Innocentif6918262018-06-11 17:37:35 +0900661 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900662 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900663 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900664 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
665 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
666
Bernie Innocentif6918262018-06-11 17:37:35 +0900667 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900668 ASSERT_NE(-1, *acceptedSocket);
669
670 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
671}
672
673void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
674 char buf[4096];
675 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
676 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
677 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
678}
679
680void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
681 // Check that the client socket was closed with ECONNABORTED.
682 int ret = write(clientSocket, "foo", sizeof("foo"));
683 int err = errno;
684 EXPECT_EQ(-1, ret);
685 EXPECT_EQ(ECONNABORTED, err);
686
687 // Check that it sent a RST to the server.
688 ret = write(acceptedSocket, "foo", sizeof("foo"));
689 err = errno;
690 EXPECT_EQ(-1, ret);
691 EXPECT_EQ(ECONNRESET, err);
692}
693
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900694TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900695 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900696 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900697
698 // Pick a random UID in the system UID range.
699 constexpr int baseUid = AID_APP - 2000;
700 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
701 int uid = baseUid + 500 + arc4random_uniform(1000);
702 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
703
704 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900705 std::vector<UidRangeParcel> uidRanges = {
706 makeUidRangeParcel(baseUid + 42, baseUid + 449),
707 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
708 makeUidRangeParcel(baseUid + 498, uid - 1),
709 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900710 };
711 // A skip list that doesn't contain UID.
712 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
713
714 // Close sockets. Our test socket should be intact.
715 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
716 checkSocketpairOpen(clientSocket, acceptedSocket);
717
718 // UID ranges that do contain uid.
719 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900720 makeUidRangeParcel(baseUid + 42, baseUid + 449),
721 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
722 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900723 };
724 // Add uid to the skip list.
725 skipUids.push_back(uid);
726
727 // Close sockets. Our test socket should still be intact because it's in the skip list.
728 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
729 checkSocketpairOpen(clientSocket, acceptedSocket);
730
731 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
732 skipUids.resize(skipUids.size() - 1);
733 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
734 checkSocketpairClosed(clientSocket, acceptedSocket);
735
736 close(clientSocket);
737 close(serverSocket);
738 close(acceptedSocket);
739}
Erik Klinecc4f2732016-08-03 11:24:27 +0900740
741namespace {
742
743int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
744 if (buf == nullptr) return -1;
745
746 int prefixLength = 0;
747 bool endOfContiguousBits = false;
748 for (unsigned int i = 0; i < buflen; i++) {
749 const uint8_t value = buf[i];
750
751 // Bad bit sequence: check for a contiguous set of bits from the high
752 // end by verifying that the inverted value + 1 is a power of 2
753 // (power of 2 iff. (v & (v - 1)) == 0).
754 const uint8_t inverse = ~value + 1;
755 if ((inverse & (inverse - 1)) != 0) return -1;
756
757 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
758
759 // Bogus netmask.
760 if (endOfContiguousBits && value != 0) return -1;
761
762 if (value != 0xff) endOfContiguousBits = true;
763 }
764
765 return prefixLength;
766}
767
768template<typename T>
769int netmaskToPrefixLength(const T *p) {
770 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
771}
772
773
774static bool interfaceHasAddress(
775 const std::string &ifname, const char *addrString, int prefixLength) {
776 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900777
778 const struct addrinfo hints = {
779 .ai_flags = AI_NUMERICHOST,
780 .ai_family = AF_UNSPEC,
781 .ai_socktype = SOCK_DGRAM,
782 };
783 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
784 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
785 return false;
786 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900787 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900788
789 struct ifaddrs *ifaddrsList = nullptr;
790 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
791
792 if (getifaddrs(&ifaddrsList) != 0) {
793 return false;
794 }
795
796 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
797 if (std::string(addr->ifa_name) != ifname ||
798 addr->ifa_addr == nullptr ||
799 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
800 continue;
801 }
802
803 switch (addr->ifa_addr->sa_family) {
804 case AF_INET: {
805 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
806 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
807 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
808 continue;
809 }
810
811 if (prefixLength < 0) return true; // not checking prefix lengths
812
813 if (addr->ifa_netmask == nullptr) return false;
814 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
815 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
816 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
817 }
818 case AF_INET6: {
819 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
820 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
821 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
822 continue;
823 }
824
825 if (prefixLength < 0) return true; // not checking prefix lengths
826
827 if (addr->ifa_netmask == nullptr) return false;
828 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
829 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
830 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
831 }
832 default:
833 // Cannot happen because we have already screened for matching
834 // address families at the top of each iteration.
835 continue;
836 }
837 }
838
839 return false;
840}
841
842} // namespace
843
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900844TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900845 static const struct TestData {
846 const char *addrString;
847 const int prefixLength;
848 const bool expectSuccess;
849 } kTestData[] = {
850 { "192.0.2.1", 24, true },
851 { "192.0.2.2", 25, true },
852 { "192.0.2.3", 32, true },
853 { "192.0.2.4", 33, false },
854 { "192.not.an.ip", 24, false },
855 { "2001:db8::1", 64, true },
856 { "2001:db8::2", 65, true },
857 { "2001:db8::3", 128, true },
858 { "2001:db8::4", 129, false },
859 { "foo:bar::bad", 64, false },
860 };
861
Sehee Park8659b8d2018-11-16 10:53:16 +0900862 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900863 const auto &td = kTestData[i];
864
865 // [1.a] Add the address.
866 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900867 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900868 if (td.expectSuccess) {
869 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
870 } else {
871 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
872 ASSERT_NE(0, status.serviceSpecificErrorCode());
873 }
874
875 // [1.b] Verify the addition meets the expectation.
876 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900877 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900878 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900879 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900880 }
881
882 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900883 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900884 if (td.expectSuccess) {
885 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
886 } else {
887 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
888 ASSERT_NE(0, status.serviceSpecificErrorCode());
889 }
890
891 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900892 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900893 }
894}
Erik Kline55b06f82016-07-04 09:57:18 +0900895
Erik Kline38e51f12018-09-06 20:14:44 +0900896TEST_F(BinderTest, GetProcSysNet) {
897 const char LOOPBACK[] = "lo";
898 static const struct {
899 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900900 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900901 const char* ifname;
902 const char* parameter;
903 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900904 const int expectedReturnCode;
905 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900906 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
907 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
908 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
909 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
910 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
911 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
912 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900913 };
914
Sehee Park8659b8d2018-11-16 10:53:16 +0900915 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900916 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900917
Erik Kline38e51f12018-09-06 20:14:44 +0900918 std::string value;
919 const binder::Status status =
920 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
921
922 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900923 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900924 EXPECT_EQ(0, status.exceptionCode());
925 EXPECT_EQ(0, status.serviceSpecificErrorCode());
926 EXPECT_EQ(td.expectedValue, value);
927 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900928 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900929 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
930 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
931 }
932 }
933}
934
935TEST_F(BinderTest, SetProcSysNet) {
936 static const struct {
937 const int ipversion;
938 const int which;
939 const char* ifname;
940 const char* parameter;
941 const char* value;
942 const int expectedReturnCode;
943 } kTestData[] = {
944 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
945 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
946 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
947 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
948 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
949 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
950 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
951 };
952
Sehee Park8659b8d2018-11-16 10:53:16 +0900953 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900954 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900955 const binder::Status status =
956 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900957
958 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900959 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900960 EXPECT_EQ(0, status.exceptionCode());
961 EXPECT_EQ(0, status.serviceSpecificErrorCode());
962 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900963 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900964 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
965 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
966 }
967 }
968}
Ben Schwartze7601812017-04-28 16:38:29 -0400969
Erik Kline38e51f12018-09-06 20:14:44 +0900970TEST_F(BinderTest, GetSetProcSysNet) {
971 const int ipversion = INetd::IPV6;
972 const int category = INetd::NEIGH;
973 const std::string& tun = sTun.name();
974 const std::string parameter("ucast_solicit");
975
976 std::string value{};
977 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
978 EXPECT_FALSE(value.empty());
979 const int ival = std::stoi(value);
980 EXPECT_GT(ival, 0);
981 // Try doubling the parameter value (always best!).
982 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
983 .isOk());
984 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
985 EXPECT_EQ(2 * ival, std::stoi(value));
986 // Try resetting the parameter.
987 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
988 .isOk());
989 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
990 EXPECT_EQ(ival, std::stoi(value));
991}
992
Ben Schwartze7601812017-04-28 16:38:29 -0400993static std::string base64Encode(const std::vector<uint8_t>& input) {
994 size_t out_len;
995 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
996 // out_len includes the trailing NULL.
997 uint8_t output_bytes[out_len];
998 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
999 return std::string(reinterpret_cast<char*>(output_bytes));
1000}
1001
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001002TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +09001003 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -04001004 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001005 std::vector<uint8_t> short_fp(1);
1006 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
1007 std::vector<std::string> test_domains;
1008 std::vector<int> test_params = { 300, 25, 8, 8 };
1009 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -04001010 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001011 const std::vector<std::string> servers;
1012 const std::string tlsName;
1013 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -04001014 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +09001015 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001016 { {"192.0.2.1"}, "", {}, 0 },
1017 { {"2001:db8::2"}, "host.name", {}, 0 },
1018 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
1019 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +09001020 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001021 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +09001022 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001023 { {"2001:dg8::6"}, "", {}, EINVAL },
1024 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
1025 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
1026 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
1027 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -04001028 };
1029
Sehee Park8659b8d2018-11-16 10:53:16 +09001030 for (size_t i = 0; i < std::size(kTlsTestData); i++) {
Erik Klinea1476fb2018-03-04 21:01:56 +09001031 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -04001032
1033 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001034 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -04001035 fingerprints.push_back(base64Encode(fingerprint));
1036 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001037 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001038 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
1039 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -04001040
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001041 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +09001042 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Ben Schwartze7601812017-04-28 16:38:29 -04001043 SCOPED_TRACE(status.toString8());
1044 EXPECT_EQ(0, status.exceptionCode());
1045 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +09001046 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Ben Schwartze7601812017-04-28 16:38:29 -04001047 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001048 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -04001049 }
Ben Schwartze7601812017-04-28 16:38:29 -04001050 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001051 // Ensure TLS is disabled before the start of the next test.
1052 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001053 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1054 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001055}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001056
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001057namespace {
1058
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001059void expectNoTestCounterRules() {
1060 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1061 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1062 std::string allRules = Join(runCommand(command), "\n");
1063 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1064 }
1065}
1066
Bernie Innocentif6918262018-06-11 17:37:35 +09001067void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1068 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001069 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1070 path, if1.c_str(), if2.c_str(), pkt, byte));
1071}
1072
Bernie Innocentif6918262018-06-11 17:37:35 +09001073void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001074 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1075 path, if1.c_str(), if2.c_str()));
1076 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1077 path, if2.c_str(), if1.c_str()));
1078}
1079
Luke Huangcaebcbb2018-09-27 20:37:14 +08001080std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1081 const std::string& iface) {
1082 for (auto& stats : statsVec) {
1083 if (stats.iface == iface) {
1084 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1085 }
1086 }
1087 return {};
1088}
1089
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001090} // namespace
1091
1092TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001093 expectNoTestCounterRules();
1094
1095 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1096 // disabling tethering. We don't check the return value because these commands will fail if
1097 // tethering is already enabled.
1098 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1099 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1100
1101 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1102 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1103 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1104 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1105 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1106
1107 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1108 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1109 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1110 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1111 // RX is from external to internal, and TX is from internal to external.
1112 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1113 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1114
1115 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1116 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1117
1118 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1119 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1120
1121 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1122 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1123 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1124
Luke Huangcaebcbb2018-09-27 20:37:14 +08001125 std::vector<TetherStatsParcel> statsVec;
1126 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001127 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1128
Luke Huangcaebcbb2018-09-27 20:37:14 +08001129 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001130
Luke Huangcaebcbb2018-09-27 20:37:14 +08001131 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001132
1133 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1134 delTetherCounterValues(path, intIface1, extIface1);
1135 delTetherCounterValues(path, intIface2, extIface2);
1136 if (path == IP6TABLES_PATH) {
1137 delTetherCounterValues(path, intIface3, extIface2);
1138 }
1139 }
1140
1141 expectNoTestCounterRules();
1142}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001143
Luke Huang0051a622018-07-23 20:30:16 +08001144namespace {
1145
Luke Huanga5211072018-08-01 23:36:29 +08001146constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1147constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001148
1149static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1150 const char* chainName) {
1151 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1152 return runCommand(command);
1153}
1154
Luke Huang19b49c52018-10-22 12:12:05 +09001155// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001156bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001157 const std::string& expectedInterface,
1158 const std::string& expectedRule, const char* table) {
1159 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1160 for (const auto& rule : rules) {
1161 if (rule.find(expectedInterface) != std::string::npos) {
1162 if (rule.find(expectedRule) != std::string::npos) {
1163 return true;
1164 }
1165 }
1166 }
1167 return false;
1168}
1169
1170void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001171 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001172 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001173 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001174 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001175 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1176 IdletimerRule, RAW_TABLE));
1177 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001178 ifname, IdletimerRule, MANGLE_TABLE));
1179 }
1180}
1181
1182void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001183 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001184 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001185 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001186 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001187 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1188 IdletimerRule, RAW_TABLE));
1189 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001190 ifname, IdletimerRule, MANGLE_TABLE));
1191 }
1192}
1193
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001194} // namespace
1195
1196TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001197 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1198 // rule in the table. Because we only check the result after calling remove function. We might
1199 // check the actual rule which is removed by our function (maybe compare the results between
1200 // calling function before and after)
1201 binder::Status status;
1202 const struct TestData {
1203 const std::string ifname;
1204 int32_t timeout;
1205 const std::string classLabel;
1206 } idleTestData[] = {
1207 {"wlan0", 1234, "happyday"},
1208 {"rmnet_data0", 4567, "friday"},
1209 };
1210 for (const auto& td : idleTestData) {
1211 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1212 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1213 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1214
1215 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1216 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1217 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1218 }
1219}
1220
Luke Huanga67dd562018-07-17 19:58:25 +08001221namespace {
1222
1223constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1224constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1225
1226void expectStrictSetUidAccept(const int uid) {
1227 std::string uidRule = StringPrintf("owner UID match %u", uid);
1228 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1229 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1230 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1231 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1232 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1233 }
1234}
1235
1236void expectStrictSetUidLog(const int uid) {
1237 static const char logRule[] = "st_penalty_log all";
1238 std::string uidRule = StringPrintf("owner UID match %u", uid);
1239 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1240 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1241 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1242 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1243 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1244 }
1245}
1246
1247void expectStrictSetUidReject(const int uid) {
1248 static const char rejectRule[] = "st_penalty_reject all";
1249 std::string uidRule = StringPrintf("owner UID match %u", uid);
1250 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1251 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1252 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1253 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1254 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1255 }
1256}
1257
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001258} // namespace
1259
1260TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001261 binder::Status status;
1262 int32_t uid = randomUid();
1263
1264 // setUidCleartextPenalty Policy:Log with randomUid
1265 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1266 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1267 expectStrictSetUidLog(uid);
1268
1269 // setUidCleartextPenalty Policy:Accept with randomUid
1270 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1271 expectStrictSetUidAccept(uid);
1272
1273 // setUidCleartextPenalty Policy:Reject with randomUid
1274 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1275 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1276 expectStrictSetUidReject(uid);
1277
1278 // setUidCleartextPenalty Policy:Accept with randomUid
1279 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1280 expectStrictSetUidAccept(uid);
1281
1282 // test wrong policy
1283 int32_t wrongPolicy = -123;
1284 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1285 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1286}
1287
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001288namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001289
Luke Huanga5211072018-08-01 23:36:29 +08001290bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001291 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1292 return (runCommand(cmd.c_str()).size()) ? true : false;
1293}
1294
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001295} // namespace
1296
1297TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001298 binder::Status status;
1299 // use dummy0 for test since it is set ready
1300 static const char testIf[] = "dummy0";
1301 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1302
1303 status = mNetd->clatdStart(testIf);
1304 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1305 EXPECT_TRUE(processExists(clatdName));
1306
1307 mNetd->clatdStop(testIf);
1308 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1309 EXPECT_FALSE(processExists(clatdName));
1310}
Luke Huang457d4702018-08-16 15:39:15 +08001311
1312namespace {
1313
1314bool getIpfwdV4Enable() {
1315 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1316 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1317 EXPECT_TRUE(!result.empty());
1318 int v4Enable = std::stoi(result[0]);
1319 return v4Enable;
1320}
1321
1322bool getIpfwdV6Enable() {
1323 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1324 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1325 EXPECT_TRUE(!result.empty());
1326 int v6Enable = std::stoi(result[0]);
1327 return v6Enable;
1328}
1329
1330void expectIpfwdEnable(bool enable) {
1331 int enableIPv4 = getIpfwdV4Enable();
1332 int enableIPv6 = getIpfwdV6Enable();
1333 EXPECT_EQ(enable, enableIPv4);
1334 EXPECT_EQ(enable, enableIPv6);
1335}
1336
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001337bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001338 std::vector<std::string> rules = listIpRules(ipVersion);
1339 for (const auto& rule : rules) {
1340 if (rule.find(ipfwdRule) != std::string::npos) {
1341 return true;
1342 }
1343 }
1344 return false;
1345}
1346
1347void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1348 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1349
1350 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1351 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1352 }
1353}
1354
1355void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1356 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1357
1358 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1359 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1360 }
1361}
1362
1363} // namespace
1364
1365TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1366 // Netd default enable Ipfwd with requester NetdHwService
1367 const std::string defaultRequester = "NetdHwService";
1368
1369 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1370 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1371 expectIpfwdEnable(false);
1372
1373 bool ipfwdEnabled;
1374 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1375 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1376 EXPECT_FALSE(ipfwdEnabled);
1377
1378 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1379 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1380 expectIpfwdEnable(true);
1381
1382 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1383 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1384 EXPECT_TRUE(ipfwdEnabled);
1385}
1386
1387TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1388 static const char testFromIf[] = "dummy0";
1389 static const char testToIf[] = "dummy0";
1390
1391 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1392 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1393 expectIpfwdRuleExists(testFromIf, testToIf);
1394
1395 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1396 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1397 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001398}
Luke Huang531f5d32018-08-03 15:19:05 +08001399
1400namespace {
1401
1402constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1403constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1404constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1405constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1406constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001407constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001408
Luke Huang19b49c52018-10-22 12:12:05 +09001409// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1410// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001411bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1412 const char* chainName, const std::string& expectedTargetA,
1413 const std::string& expectedTargetB) {
1414 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1415 int matchCount = 0;
1416
1417 for (const auto& rule : rules) {
1418 if (rule.find(expectedTargetA) != std::string::npos) {
1419 if (rule.find(expectedTargetB) != std::string::npos) {
1420 matchCount++;
1421 }
1422 }
1423 }
1424 return matchCount == expectedCount;
1425}
1426
1427void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1428 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1429 std::string result = "";
1430
1431 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001432 // Quota value might be decreased while matching packets
1433 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001434}
1435
1436void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1437 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1438 std::string quotaRule = StringPrintf("quota %s", ifname);
1439
1440 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1441 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1442 BANDWIDTH_COSTLY_IF));
1443 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1444 BANDWIDTH_COSTLY_IF));
1445 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1446 BANDWIDTH_COSTLY_IF));
1447 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1448 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1449 }
1450 expectXtQuotaValueEqual(ifname, quotaBytes);
1451}
1452
1453void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1454 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1455 std::string quotaRule = StringPrintf("quota %s", ifname);
1456
1457 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1458 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1459 BANDWIDTH_COSTLY_IF));
1460 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1461 BANDWIDTH_COSTLY_IF));
1462 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1463 BANDWIDTH_COSTLY_IF));
1464 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1465 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1466 }
1467}
1468
1469void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1470 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1471 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1472 std::string alertName = StringPrintf("%sAlert", ifname);
1473
1474 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1475 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1476 }
1477 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1478}
1479
1480void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1481 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1482 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1483
1484 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1485 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1486 }
1487}
1488
1489void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1490 static const char globalAlertRule[] = "quota globalAlert";
1491 static const char globalAlertName[] = "globalAlert";
1492
1493 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001494 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001495 }
1496 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1497}
1498
1499void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1500 std::string uidRule = StringPrintf("owner UID match %u", uid);
1501
1502 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1503 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1504 }
1505}
1506
1507void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1508 std::string uidRule = StringPrintf("owner UID match %u", uid);
1509
1510 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1511 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1512 }
1513}
1514
1515} // namespace
1516
1517TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1518 long testQuotaBytes = 5550;
1519
1520 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001521 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001522 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1523
1524 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1525 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1526 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1527
1528 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1529 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1530 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1531
1532 // Remove test physical network
1533 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1534}
1535
1536TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1537 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001538 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001539 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001540 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001541 // Need to have a prior interface quota set to set an alert
1542 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1543 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1544 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1545 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1546
1547 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1548 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1549 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1550
1551 // Remove interface quota
1552 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1553 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1554 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1555
1556 // Remove test physical network
1557 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1558}
1559
1560TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1561 long testAlertBytes = 2097149;
1562
1563 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1564 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1565 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1566
1567 testAlertBytes = 2097152;
1568 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1569 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1570 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1571}
1572
1573TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1574 SKIP_IF_BPF_SUPPORTED;
1575
1576 int32_t uid = randomUid();
1577 static const char targetReject[] = "REJECT";
1578 static const char targetReturn[] = "RETURN";
1579
1580 // add NaughtyApp
1581 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1582 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1583 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1584
1585 // remove NaughtyApp
1586 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1587 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1588 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1589
1590 // add NiceApp
1591 status = mNetd->bandwidthAddNiceApp(uid);
1592 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1593 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1594
1595 // remove NiceApp
1596 status = mNetd->bandwidthRemoveNiceApp(uid);
1597 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1598 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1599}
Luke Huangb5733d72018-08-21 17:17:19 +08001600
1601namespace {
1602
Luke Huangb670d162018-08-23 20:01:13 +08001603std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1604 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1605 return runCommand(command);
1606}
1607
Luke Huangc3252cc2018-10-16 15:43:23 +08001608bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001609 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1610 for (const auto& route : routes) {
1611 if (route.find(ipRoute) != std::string::npos) {
1612 return true;
1613 }
1614 }
1615 return false;
1616}
1617
Luke Huangc3252cc2018-10-16 15:43:23 +08001618std::string ipRouteString(const std::string& ifName, const std::string& dst,
1619 const std::string& nextHop) {
1620 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1621
1622 if (!nextHop.empty()) {
1623 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001624 }
1625
Luke Huangc3252cc2018-10-16 15:43:23 +08001626 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001627}
1628
Luke Huangc3252cc2018-10-16 15:43:23 +08001629void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1630 const std::string& dst, const std::string& nextHop,
1631 const char* table) {
1632 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1633}
1634
1635void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001636 const std::string& dst, const std::string& nextHop,
1637 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001638 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001639}
1640
1641bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1642 std::vector<std::string> rules = listIpRules(ipVersion);
1643 for (const auto& rule : rules) {
1644 if (rule.find(ipRule) != std::string::npos) {
1645 return true;
1646 }
1647 }
1648 return false;
1649}
1650
1651void expectNetworkDefaultIpRuleExists(const char* ifName) {
1652 std::string networkDefaultRule =
1653 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1654
1655 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1656 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1657 }
1658}
1659
1660void expectNetworkDefaultIpRuleDoesNotExist() {
1661 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1662
1663 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1664 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1665 }
1666}
1667
1668void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1669 std::string networkPermissionRule = "";
1670 switch (permission) {
1671 case INetd::PERMISSION_NONE:
1672 networkPermissionRule = StringPrintf(
1673 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1674 break;
1675 case INetd::PERMISSION_NETWORK:
1676 networkPermissionRule = StringPrintf(
1677 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1678 break;
1679 case INetd::PERMISSION_SYSTEM:
1680 networkPermissionRule = StringPrintf(
1681 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1682 break;
1683 }
1684
1685 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1686 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1687 }
1688}
1689
1690// TODO: It is a duplicate function, need to remove it
1691bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1692 const std::string& expectedInterface,
1693 const std::string& expectedRule,
1694 const char* table) {
1695 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1696 for (const auto& rule : rules) {
1697 if (rule.find(expectedInterface) != std::string::npos) {
1698 if (rule.find(expectedRule) != std::string::npos) {
1699 return true;
1700 }
1701 }
1702 }
1703 return false;
1704}
1705
1706void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1707 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1708 std::string networkIncomingPacketMarkRule = "";
1709 switch (permission) {
1710 case INetd::PERMISSION_NONE:
1711 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1712 break;
1713 case INetd::PERMISSION_NETWORK:
1714 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1715 break;
1716 case INetd::PERMISSION_SYSTEM:
1717 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1718 break;
1719 }
1720
1721 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1722 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1723 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1724 }
1725}
1726
1727} // namespace
1728
1729TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001730 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001731 const char* ipVersion;
1732 const char* testDest;
1733 const char* testNextHop;
1734 const bool expectSuccess;
1735 } kTestData[] = {
1736 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001737 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1738 {IP_RULE_V4, "10.251.0.0/16", "", true},
1739 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1740 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001741 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001742 {IP_RULE_V6, "::/0", "2001:db8::", true},
1743 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001744 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1745 };
1746
Luke Huangc3252cc2018-10-16 15:43:23 +08001747 static const struct {
1748 const char* ipVersion;
1749 const char* testDest;
1750 const char* testNextHop;
1751 } kTestDataWithNextHop[] = {
1752 {IP_RULE_V4, "10.251.10.0/30", ""},
1753 {IP_RULE_V6, "2001:db8::/32", ""},
1754 };
1755
Luke Huangb670d162018-08-23 20:01:13 +08001756 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001757 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001758 const int testUid = randomUid();
1759 const std::vector<int32_t> testUids = {testUid};
1760
1761 // Add test physical network
1762 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1763 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1764
Luke Huangc3252cc2018-10-16 15:43:23 +08001765 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001766 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001767 const auto& td = kTestDataWithNextHop[i];
1768
1769 // All route for test tun will disappear once the tun interface is deleted.
1770 binder::Status status =
1771 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1772 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1773 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1774 sTun.name().c_str());
1775
1776 // Add system permission for test uid, setup route in legacy system table.
1777 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1778
1779 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1780 testUid);
1781 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1782 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1783 testTableLegacySystem);
1784
1785 // Remove system permission for test uid, setup route in legacy network table.
1786 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1787
1788 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1789 testUid);
1790 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1791 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1792 testTableLegacyNetwork);
1793 }
1794
Sehee Park8659b8d2018-11-16 10:53:16 +09001795 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001796 const auto& td = kTestData[i];
1797
1798 binder::Status status =
1799 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1800 if (td.expectSuccess) {
1801 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001802 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001803 sTun.name().c_str());
1804 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001805 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1806 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001807 }
1808
1809 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1810 if (td.expectSuccess) {
1811 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001812 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1813 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001814 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001815 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1816 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001817 }
1818
Luke Huangc3252cc2018-10-16 15:43:23 +08001819 // Add system permission for test uid, route will be added into legacy system table.
1820 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001821
1822 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1823 testUid);
1824 if (td.expectSuccess) {
1825 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001826 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001827 testTableLegacySystem);
1828 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001829 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1830 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001831 }
1832
1833 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1834 td.testNextHop, testUid);
1835 if (td.expectSuccess) {
1836 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001837 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1838 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001839 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001840 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1841 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001842 }
1843
Luke Huangc3252cc2018-10-16 15:43:23 +08001844 // Remove system permission for test uid, route will be added into legacy network table.
1845 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1846
1847 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1848 testUid);
1849 if (td.expectSuccess) {
1850 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1851 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1852 testTableLegacyNetwork);
1853 } else {
1854 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1855 EXPECT_NE(0, status.serviceSpecificErrorCode());
1856 }
1857
1858 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1859 td.testNextHop, testUid);
1860 if (td.expectSuccess) {
1861 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1862 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1863 testTableLegacyNetwork);
1864 } else {
1865 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1866 EXPECT_NE(0, status.serviceSpecificErrorCode());
1867 }
Luke Huangb670d162018-08-23 20:01:13 +08001868 }
1869
1870 // Remove test physical network
1871 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1872}
1873
1874TEST_F(BinderTest, NetworkPermissionDefault) {
1875 // Add test physical network
1876 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1877 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1878
Luke Huangc3252cc2018-10-16 15:43:23 +08001879 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001880 int currentNetid;
1881 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1882 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1883
1884 // Test SetDefault
1885 status = mNetd->networkSetDefault(TEST_NETID1);
1886 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1887 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1888
1889 status = mNetd->networkClearDefault();
1890 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1891 expectNetworkDefaultIpRuleDoesNotExist();
1892
1893 // Add default network back
1894 status = mNetd->networkSetDefault(currentNetid);
1895 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1896
1897 // Test SetPermission
1898 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1899 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1900 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1901 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1902
1903 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1904 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1905 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1906 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1907
1908 // Remove test physical network
1909 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1910}
1911
1912TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1913 const int testUid = randomUid();
1914 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1915 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1916 bool ret = false;
1917 status = mNetd->networkCanProtect(testUid, &ret);
1918 EXPECT_TRUE(ret);
1919
1920 status = mNetd->networkSetProtectDeny(testUid);
1921 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1922 status = mNetd->networkCanProtect(testUid, &ret);
1923 EXPECT_FALSE(ret);
1924}
1925
1926namespace {
1927
Luke Huangb5733d72018-08-21 17:17:19 +08001928int readIntFromPath(const std::string& path) {
1929 std::string result = "";
1930 EXPECT_TRUE(ReadFileToString(path, &result));
1931 return std::stoi(result);
1932}
1933
1934int getTetherAcceptIPv6Ra(const std::string& ifName) {
1935 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1936 return readIntFromPath(path);
1937}
1938
1939bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1940 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1941 return readIntFromPath(path);
1942}
1943
1944int getTetherIPv6DadTransmits(const std::string& ifName) {
1945 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1946 return readIntFromPath(path);
1947}
1948
1949bool getTetherEnableIPv6(const std::string& ifName) {
1950 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1951 int disableIPv6 = readIntFromPath(path);
1952 return !disableIPv6;
1953}
1954
1955bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1956 for (const auto& iface : ifList) {
1957 if (iface == ifName) {
1958 return true;
1959 }
1960 }
1961 return false;
1962}
1963
1964void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1965 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1966 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1967 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1968 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1969}
1970
1971void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1972 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1973 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1974 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1975 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1976}
1977
1978void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1979 const std::string& ifName) {
1980 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1981}
1982
1983void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1984 const std::string& ifName) {
1985 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1986}
1987
1988void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
1989 const std::vector<std::string>& testDnsAddrs) {
1990 EXPECT_TRUE(dnsList == testDnsAddrs);
1991}
1992
1993} // namespace
1994
1995TEST_F(BinderTest, TetherStartStopStatus) {
1996 std::vector<std::string> noDhcpRange = {};
1997 static const char dnsdName[] = "dnsmasq";
1998
1999 binder::Status status = mNetd->tetherStart(noDhcpRange);
2000 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2001 EXPECT_TRUE(processExists(dnsdName));
2002
2003 bool tetherEnabled;
2004 status = mNetd->tetherIsEnabled(&tetherEnabled);
2005 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2006 EXPECT_TRUE(tetherEnabled);
2007
2008 status = mNetd->tetherStop();
2009 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2010 EXPECT_FALSE(processExists(dnsdName));
2011
2012 status = mNetd->tetherIsEnabled(&tetherEnabled);
2013 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2014 EXPECT_FALSE(tetherEnabled);
2015}
2016
2017TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2018 // TODO: verify if dnsmasq update interface successfully
2019
2020 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2021 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2022 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2023
2024 std::vector<std::string> ifList;
2025 status = mNetd->tetherInterfaceList(&ifList);
2026 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2027 expectTetherInterfaceExists(ifList, sTun.name());
2028
2029 status = mNetd->tetherInterfaceRemove(sTun.name());
2030 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2031 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2032
2033 status = mNetd->tetherInterfaceList(&ifList);
2034 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2035 expectTetherInterfaceNotExists(ifList, sTun.name());
2036}
2037
2038TEST_F(BinderTest, TetherDnsSetList) {
2039 // TODO: verify if dnsmasq update dns successfully
2040 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
2041
2042 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2043 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2044
2045 std::vector<std::string> dnsList;
2046 status = mNetd->tetherDnsList(&dnsList);
2047 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2048 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002049}
2050
2051namespace {
2052
2053constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2054constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2055constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2056constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2057constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2058constexpr char FIREWALL_STANDBY[] = "fw_standby";
2059constexpr char targetReturn[] = "RETURN";
2060constexpr char targetDrop[] = "DROP";
2061
2062void expectFirewallWhitelistMode() {
2063 static const char dropRule[] = "DROP all";
2064 static const char rejectRule[] = "REJECT all";
2065 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2066 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2067 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2068 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2069 }
2070}
2071
2072void expectFirewallBlacklistMode() {
2073 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2074 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2075 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2076 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2077 }
2078}
2079
2080bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2081 const std::string& expectedInterface,
2082 const std::string& expectedRule) {
2083 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2084 // Expected rule:
2085 // Chain fw_INPUT (1 references)
2086 // pkts bytes target prot opt in out source destination
2087 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2088 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2089 int firstRuleIndex = 2;
2090 if (rules.size() < 4) return false;
2091 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2092 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2093 return true;
2094 }
2095 }
2096 return false;
2097}
2098
2099// TODO: It is a duplicate function, need to remove it
2100bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2101 const std::string& expectedInterface,
2102 const std::string& expectedRule) {
2103 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2104 for (const auto& rule : rules) {
2105 if (rule.find(expectedInterface) != std::string::npos) {
2106 if (rule.find(expectedRule) != std::string::npos) {
2107 return true;
2108 }
2109 }
2110 }
2111 return false;
2112}
2113
2114void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2115 static const char returnRule[] = "RETURN all";
2116 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2117 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2118 returnRule));
2119 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2120 returnRule));
2121 }
2122}
2123
2124void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2125 static const char returnRule[] = "RETURN all";
2126 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2127 EXPECT_FALSE(
2128 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2129 EXPECT_FALSE(
2130 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2131 }
2132}
2133
2134bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2135 const std::string& expectedTarget,
2136 const std::string& expectedRule) {
2137 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2138 int firstRuleIndex = 2;
2139 if (rules.size() < 4) return false;
2140 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2141 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2142 return true;
2143 }
2144 }
2145 return false;
2146}
2147
2148bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2149 const std::string& expectedTarget,
2150 const std::string& expectedRule) {
2151 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2152 int lastRuleIndex = rules.size() - 1;
2153 if (lastRuleIndex < 0) return false;
2154 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2155 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2156 return true;
2157 }
2158 }
2159 return false;
2160}
2161
2162void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2163 std::string uidRule = StringPrintf("owner UID match %u", uid);
2164 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2165 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2166}
2167
2168void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2169 std::string uidRule = StringPrintf("owner UID match %u", uid);
2170 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2171 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2172}
2173
2174void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2175 std::string uidRule = StringPrintf("owner UID match %u", uid);
2176 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2177 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2178}
2179
2180void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2181 std::string uidRule = StringPrintf("owner UID match %u", uid);
2182 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2183 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2184}
2185
2186bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2187 std::vector<std::string> inputRules =
2188 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2189 std::vector<std::string> outputRules =
2190 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2191 int inputLastRuleIndex = inputRules.size() - 1;
2192 int outputLastRuleIndex = outputRules.size() - 1;
2193
2194 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2195 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2196 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2197 return true;
2198 }
2199 }
2200 return false;
2201}
2202
2203void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2204 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2205 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2206}
2207
2208void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2209 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2210 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2211 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2212 }
2213}
2214
2215} // namespace
2216
2217TEST_F(BinderTest, FirewallSetFirewallType) {
2218 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2219 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2220 expectFirewallWhitelistMode();
2221
2222 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2223 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2224 expectFirewallBlacklistMode();
2225
2226 // set firewall type blacklist twice
2227 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2228 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2229 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2230 expectFirewallBlacklistMode();
2231
2232 // set firewall type whitelist twice
2233 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2234 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2235 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2236 expectFirewallWhitelistMode();
2237
2238 // reset firewall type to default
2239 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2240 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2241 expectFirewallBlacklistMode();
2242}
2243
2244TEST_F(BinderTest, FirewallSetInterfaceRule) {
2245 // setinterfaceRule is not supported in BLACKLIST MODE
2246 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2247 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2248
2249 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2250 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2251
2252 // set WHITELIST mode first
2253 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2254 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2255
2256 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2257 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2258 expectFirewallInterfaceRuleAllowExists(sTun.name());
2259
2260 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2261 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2262 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2263
2264 // reset firewall mode to default
2265 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2266 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2267 expectFirewallBlacklistMode();
2268}
2269
2270TEST_F(BinderTest, FirewallSetUidRule) {
2271 SKIP_IF_BPF_SUPPORTED;
2272
2273 int32_t uid = randomUid();
2274
2275 // Doze allow
2276 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2277 INetd::FIREWALL_RULE_ALLOW);
2278 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2279 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2280
2281 // Doze deny
2282 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2283 INetd::FIREWALL_RULE_DENY);
2284 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2285 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2286
2287 // Powersave allow
2288 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2289 INetd::FIREWALL_RULE_ALLOW);
2290 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2291 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2292
2293 // Powersave deny
2294 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2295 INetd::FIREWALL_RULE_DENY);
2296 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2297 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2298
2299 // Standby deny
2300 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2301 INetd::FIREWALL_RULE_DENY);
2302 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2303 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2304
2305 // Standby allow
2306 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2307 INetd::FIREWALL_RULE_ALLOW);
2308 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2309 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2310
2311 // None deny in BLACKLIST
2312 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2313 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2314 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2315 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2316
2317 // None allow in BLACKLIST
2318 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2319 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2320 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2321 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2322
2323 // set firewall type whitelist twice
2324 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2325 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2326 expectFirewallWhitelistMode();
2327
2328 // None allow in WHITELIST
2329 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2330 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2331 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2332 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2333
2334 // None deny in WHITELIST
2335 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2336 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2337 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2338 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2339
2340 // reset firewall mode to default
2341 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2342 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2343 expectFirewallBlacklistMode();
2344}
2345
2346TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2347 SKIP_IF_BPF_SUPPORTED;
2348
2349 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2350 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2351 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2352
2353 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2354 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2355 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2356
2357 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2358 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2359 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2360
2361 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2362 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2363 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2364
2365 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2366 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2367 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2368
2369 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2370 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2371 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2372}
Luke Huangf7782042018-08-08 13:13:04 +08002373
2374namespace {
2375
2376std::string hwAddrToStr(unsigned char* hwaddr) {
2377 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2378 hwaddr[4], hwaddr[5]);
2379}
2380
2381int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2382 int prefixLength = 0;
2383 uint32_t m = ntohl(mask);
2384 while (m & (1 << 31)) {
2385 prefixLength++;
2386 m = m << 1;
2387 }
2388 return prefixLength;
2389}
2390
2391std::string toStdString(const String16& s) {
2392 return std::string(String8(s.string()));
2393}
2394
2395android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2396 const auto& sys = sSyscalls.get();
2397 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2398 EXPECT_TRUE(isOk(fd.status()));
2399
2400 struct ifreq ifr = {};
2401 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2402
2403 return sys.ioctl(fd.value(), flag, &ifr);
2404}
2405
2406std::string getInterfaceHwAddr(const std::string& ifName) {
2407 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2408
2409 unsigned char hwaddr[ETH_ALEN] = {};
2410 if (isOk(res.status())) {
2411 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2412 }
2413
2414 return hwAddrToStr(hwaddr);
2415}
2416
2417int getInterfaceIPv4Prefix(const std::string& ifName) {
2418 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2419
2420 int prefixLength = 0;
2421 if (isOk(res.status())) {
2422 prefixLength = ipv4NetmaskToPrefixLength(
2423 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2424 }
2425
2426 return prefixLength;
2427}
2428
2429std::string getInterfaceIPv4Addr(const std::string& ifName) {
2430 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2431
2432 struct in_addr addr = {};
2433 if (isOk(res.status())) {
2434 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2435 }
2436
2437 return std::string(inet_ntoa(addr));
2438}
2439
2440std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2441 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2442
2443 unsigned flags = 0;
2444 if (isOk(res.status())) {
2445 flags = res.value().ifr_flags;
2446 }
2447
2448 std::vector<std::string> ifFlags;
2449 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2450 : toStdString(INetd::IF_STATE_DOWN()));
2451
2452 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2453 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2454 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2455 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2456 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2457
2458 return ifFlags;
2459}
2460
2461bool compareListInterface(const std::vector<std::string>& interfaceList) {
2462 const auto& res = InterfaceController::getIfaceNames();
2463 EXPECT_TRUE(isOk(res));
2464
2465 std::vector<std::string> resIfList;
2466 resIfList.reserve(res.value().size());
2467 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2468
2469 return resIfList == interfaceList;
2470}
2471
2472int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2473 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2474 return readIntFromPath(path);
2475}
2476
2477bool getInterfaceEnableIPv6(const std::string& ifName) {
2478 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2479
2480 int disableIPv6 = readIntFromPath(path);
2481 return !disableIPv6;
2482}
2483
2484int getInterfaceMtu(const std::string& ifName) {
2485 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2486 return readIntFromPath(path);
2487}
2488
2489void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2490 EXPECT_TRUE(compareListInterface(interfaceList));
2491}
2492
2493void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2494 const InterfaceConfigurationParcel& interfaceCfg) {
2495 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2496 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2497 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2498 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2499}
2500
2501void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2502 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2503 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2504
2505 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2506 for (const auto& flag : setCfg.flags) {
2507 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2508 }
2509}
2510
2511void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2512 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2513 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2514}
2515
2516void expectInterfaceNoAddr(const std::string& ifName) {
2517 // noAddr
2518 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2519 // noPrefix
2520 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2521}
2522
2523void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2524 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2525 EXPECT_EQ(enableIPv6, enable);
2526}
2527
2528void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2529 int mtuSize = getInterfaceMtu(ifName);
2530 EXPECT_EQ(mtu, mtuSize);
2531}
2532
2533InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2534 const std::string& addr, int prefixLength,
2535 const std::vector<std::string>& flags) {
2536 InterfaceConfigurationParcel cfg;
2537 cfg.ifName = ifName;
2538 cfg.hwAddr = "";
2539 cfg.ipv4Addr = addr;
2540 cfg.prefixLength = prefixLength;
2541 cfg.flags = flags;
2542 return cfg;
2543}
2544
2545void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2546 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2547 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2548
2549 for (const auto& flag : expectedFlags) {
2550 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2551 interfaceCfg.flags.end());
2552 }
2553
2554 for (const auto& flag : unexpectedFlags) {
2555 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2556 interfaceCfg.flags.end());
2557 }
2558}
2559
2560} // namespace
2561
2562TEST_F(BinderTest, InterfaceList) {
2563 std::vector<std::string> interfaceListResult;
2564
2565 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2566 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2567 expectInterfaceList(interfaceListResult);
2568}
2569
2570TEST_F(BinderTest, InterfaceGetCfg) {
2571 InterfaceConfigurationParcel interfaceCfgResult;
2572
2573 // Add test physical network
2574 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2575 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2576
2577 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2578 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2579 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2580 expectTunFlags(interfaceCfgResult);
2581
2582 // Remove test physical network
2583 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2584}
2585
2586TEST_F(BinderTest, InterfaceSetCfg) {
2587 const std::string testAddr = "192.0.2.3";
2588 const int testPrefixLength = 24;
2589 std::vector<std::string> upFlags = {"up"};
2590 std::vector<std::string> downFlags = {"down"};
2591
2592 // Add test physical network
2593 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2594 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2595
2596 // Set tun interface down.
2597 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2598 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2599 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2600 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2601
2602 // Set tun interface up again.
2603 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2604 status = mNetd->interfaceSetCfg(interfaceCfg);
2605 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2606 status = mNetd->interfaceClearAddrs(sTun.name());
2607 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2608
2609 // Remove test physical network
2610 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2611}
2612
2613TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2614 // enable
2615 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2616 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2617 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2618
2619 // disable
2620 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2621 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2622 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2623}
2624
2625TEST_F(BinderTest, InterfaceClearAddr) {
2626 const std::string testAddr = "192.0.2.3";
2627 const int testPrefixLength = 24;
2628 std::vector<std::string> noFlags{};
2629
2630 // Add test physical network
2631 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2632 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2633
2634 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2635 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2636 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2637 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2638
2639 status = mNetd->interfaceClearAddrs(sTun.name());
2640 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2641 expectInterfaceNoAddr(sTun.name());
2642
2643 // Remove test physical network
2644 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2645}
2646
2647TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2648 // Add test physical network
2649 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2650 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2651
2652 // disable
2653 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2654 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2655 expectInterfaceEnableIPv6(sTun.name(), false);
2656
2657 // enable
2658 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2659 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2660 expectInterfaceEnableIPv6(sTun.name(), true);
2661
2662 // Remove test physical network
2663 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2664}
2665
2666TEST_F(BinderTest, InterfaceSetMtu) {
2667 const int testMtu = 1200;
2668
2669 // Add test physical network
2670 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2671 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2672
2673 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2674 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2675 expectInterfaceMtu(sTun.name(), testMtu);
2676
2677 // Remove test physical network
2678 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2679}
Luke Huang19b49c52018-10-22 12:12:05 +09002680
2681namespace {
2682
2683constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2684constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002685constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002686constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2687
Luke Huangae038f82018-11-05 11:17:31 +09002688int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002689 return listIptablesRuleByTable(binary, table, chainName).size();
2690}
2691
2692bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2693 const std::vector<std::string>& targetVec) {
2694 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2695 if (targetVec.size() != rules.size() - 2) {
2696 return false;
2697 }
2698
2699 /*
Luke Huangae038f82018-11-05 11:17:31 +09002700 * Check that the rules match. Note that this function matches substrings, not entire rules,
2701 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002702 * Skip first two lines since rules start from third line.
2703 * Chain chainName (x references)
2704 * pkts bytes target prot opt in out source destination
2705 * ...
2706 */
2707 int rIndex = 2;
2708 for (const auto& target : targetVec) {
2709 if (rules[rIndex].find(target) == std::string::npos) {
2710 return false;
2711 }
2712 rIndex++;
2713 }
2714 return true;
2715}
2716
2717void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2718 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2719 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2720 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002721 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002722 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2723 "DROP"};
2724
2725 // V4
2726 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2727 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002728 EXPECT_TRUE(
2729 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002730 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2731
Luke Huangae038f82018-11-05 11:17:31 +09002732 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002733 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2734
2735 // V6
2736 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002737 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2738 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002739
2740 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2741 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2742 extIf));
2743 }
2744}
2745
2746void expectNatDisable() {
2747 // It is the default DROP rule with tethering disable.
2748 // Chain tetherctrl_FORWARD (1 references)
2749 // pkts bytes target prot opt in out source destination
2750 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2751 std::vector<std::string> forwardV4Match = {"DROP"};
2752 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2753
2754 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002755 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2756 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002757
Luke Huangae038f82018-11-05 11:17:31 +09002758 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2759 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002760
2761 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2762}
2763
2764} // namespace
2765
2766TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002767 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2768 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2769 expectNatEnable(sTun.name(), sTun2.name());
2770
2771 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2772 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2773 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002774}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002775
2776namespace {
2777
2778using TripleInt = std::array<int, 3>;
2779
2780TripleInt readProcFileToTripleInt(const std::string& path) {
2781 std::string valueString;
2782 int min, def, max;
2783 EXPECT_TRUE(ReadFileToString(path, &valueString));
2784 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2785 return {min, def, max};
2786}
2787
2788void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2789 std::string testRmemValues =
2790 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2791 std::string testWmemValues =
2792 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2793 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2794
2795 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2796 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2797
2798 for (int i = 0; i < 3; i++) {
2799 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2800 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2801 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2802 }
2803}
2804
2805} // namespace
2806
2807TEST_F(BinderTest, TcpBufferSet) {
2808 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2809 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2810 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2811 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2812
2813 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2814 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2815}
Luke Huang528af602018-08-29 19:06:05 +08002816
Chenbo Feng48eaed32018-12-26 17:40:21 -08002817namespace {
2818
2819void checkUidsExist(std::vector<int32_t>& uids, bool exist) {
2820 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2821 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2822 for (int32_t uid : uids) {
2823 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2824 if (exist) {
2825 EXPECT_TRUE(isOk(permission));
2826 EXPECT_EQ(ALLOW_SOCK_CREATE, permission.value());
2827 } else {
2828 EXPECT_FALSE(isOk(permission));
2829 EXPECT_EQ(ENOENT, permission.status().code());
2830 }
2831 }
2832}
2833
2834} // namespace
2835
2836TEST_F(BinderTest, TestInternetPermission) {
2837 SKIP_IF_BPF_NOT_SUPPORTED;
2838
2839 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2840
2841 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
2842 checkUidsExist(appUids, true);
2843 mNetd->trafficSetNetPermForUids(INetd::NO_PERMISSIONS, appUids);
2844 checkUidsExist(appUids, false);
2845}
2846
Luke Huang528af602018-08-29 19:06:05 +08002847TEST_F(BinderTest, UnsolEvents) {
2848 auto testUnsolService = android::net::TestUnsolService::start();
2849 std::string oldTunName = sTun.name();
2850 std::string newTunName = "unsolTest";
2851 testUnsolService->tarVec.push_back(oldTunName);
2852 testUnsolService->tarVec.push_back(newTunName);
2853 auto& cv = testUnsolService->getCv();
2854 auto& cvMutex = testUnsolService->getCvMutex();
2855 binder::Status status = mNetd->registerUnsolicitedEventListener(
2856 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2857 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2858
2859 // TODO: Add test for below events
2860 // StrictCleartextDetected / InterfaceDnsServersAdded
2861 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2862
2863 {
2864 std::unique_lock lock(cvMutex);
2865
2866 // Re-init test Tun, and we expect that we will get some unsol events.
2867 // Use the test Tun device name to verify if we receive its unsol events.
2868 sTun.destroy();
2869 // Use predefined name
2870 sTun.init(newTunName);
2871
2872 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2873 }
2874
2875 // bit mask 1101101000
2876 // Test only covers below events currently
2877 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2878 InterfaceLinkStatusChanged | RouteChanged;
2879 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
2880}