blob: b69acf8230b5b1bfa58e7e3cdf01fe231c006249 [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"
Luke Huang528af602018-08-29 19:06:05 +080056#include "TestUnsolService.h"
Nathan Harold21299f72018-03-16 20:13:03 -070057#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090058#include "android/net/INetd.h"
59#include "binder/IServiceManager.h"
Mike Yue7e332f2019-03-13 17:15:48 +080060#include "netdutils/Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070061#include "netdutils/Syscalls.h"
Mike Yu5ae61542018-10-19 22:11:43 +080062#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090063
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090064#define IP_PATH "/system/bin/ip"
65#define IP6TABLES_PATH "/system/bin/ip6tables"
66#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090067#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080068#define RAW_TABLE "raw"
69#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080070#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090071#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090072
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090073namespace binder = android::binder;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090074
75using android::IBinder;
76using android::IServiceManager;
77using android::sp;
78using android::String16;
79using android::String8;
80using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080081using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090082using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090083using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080084using android::base::Trim;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090085using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080086using android::net::InterfaceConfigurationParcel;
87using android::net::InterfaceController;
Luke Huangcaebcbb2018-09-27 20:37:14 +080088using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090089using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090090using android::net::UidRangeParcel;
Luke Huangf7782042018-08-08 13:13:04 +080091using android::netdutils::sSyscalls;
Mike Yue7e332f2019-03-13 17:15:48 +080092using android::netdutils::Stopwatch;
Robin Leeb8087362016-03-30 18:43:08 +010093
94static const char* IP_RULE_V4 = "-4";
95static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090096static const int TEST_NETID1 = 65501;
97static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -080098
99// Use maximum reserved appId for applications to avoid conflict with existing
100// uids.
101static const int TEST_UID1 = 99999;
102static const int TEST_UID2 = 99998;
103
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900104constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900105
Benedict Wongb2daefb2017-12-06 22:05:46 -0800106static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
107static const std::string ESP_ALLOW_RULE("esp");
108
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900109class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900110 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900111 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900112 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900113 sp<IBinder> binder = sm->getService(String16("netd"));
114 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900115 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900116 }
117 }
118
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900119 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900120 ASSERT_NE(nullptr, mNetd.get());
121 }
122
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900123 void TearDown() override {
124 mNetd->networkDestroy(TEST_NETID1);
125 mNetd->networkDestroy(TEST_NETID2);
126 }
127
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900128 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700129
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900130 // Static because setting up the tun interface takes about 40ms.
131 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900132 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900133 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900134 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900135 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900136 }
137
138 static void TearDownTestCase() {
139 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900140 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900141 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900142 }
143
144 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900145
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900146 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900147 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900148 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900149 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900150};
151
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900152TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900153TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900154
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900155class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900156 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700157 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900158 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900159 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900160 }
161
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900162 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900163 std::string mName;
164};
165
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900166TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900167 TimedOperation t("isAlive RPC");
168 bool isAlive = false;
169 mNetd->isAlive(&isAlive);
170 ASSERT_TRUE(isAlive);
171}
172
173static int randomUid() {
174 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
175}
176
Robin Leeb8087362016-03-30 18:43:08 +0100177static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900178 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900179 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
180 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900181 perror("popen");
182 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900183 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900184
185 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100186 size_t bufsize = 0;
187 ssize_t linelen = 0;
188 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900189 lines.push_back(std::string(line, linelen));
190 free(line);
191 line = nullptr;
192 }
193
194 pclose(f);
195 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900196}
197
Robin Leeb8087362016-03-30 18:43:08 +0100198static std::vector<std::string> listIpRules(const char *ipVersion) {
199 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
200 return runCommand(command);
201}
202
203static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900204 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100205 return runCommand(command);
206}
207
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900208static int iptablesRuleLineLength(const char *binary, const char *chainName) {
209 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900210}
211
Benedict Wongb2daefb2017-12-06 22:05:46 -0800212static bool iptablesRuleExists(const char *binary,
213 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900214 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800215 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900216 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800217 if(rule.find(expectedRule) != std::string::npos) {
218 return true;
219 }
220 }
221 return false;
222}
223
224static bool iptablesNoSocketAllowRuleExists(const char *chainName){
225 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
226 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
227}
228
229static bool iptablesEspAllowRuleExists(const char *chainName){
230 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
231 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
232}
233
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900234TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700235 SKIP_IF_BPF_SUPPORTED;
236
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900237 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
238 const int kNumUids = 500;
239 std::vector<int32_t> noUids(0);
240 std::vector<int32_t> uids(kNumUids);
241 for (int i = 0; i < kNumUids; i++) {
242 uids[i] = randomUid();
243 }
244
245 bool ret;
246 {
247 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900248 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900249 }
250 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800251 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
252 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
253 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
254 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900255 {
256 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900257 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900258 }
259 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900260 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
261 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900262
263 {
264 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900265 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900266 }
267 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900268 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
269 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800270 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
271 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900272
273 {
274 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900275 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900276 }
277 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900278 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
279 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900280
281 // Check that the call fails if iptables returns an error.
282 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900283 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900284 EXPECT_EQ(false, ret);
285}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900286
Benedict Wong319f17e2018-05-15 17:06:44 -0700287TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700288 const struct TestData {
289 const std::string family;
290 const std::string deviceName;
291 const std::string localAddress;
292 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800293 int32_t iKey;
294 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700295 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800296 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700297 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
298 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
299 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800300 };
301
Sehee Park8659b8d2018-11-16 10:53:16 +0900302 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700303 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800304
305 binder::Status status;
306
Benedict Wong319f17e2018-05-15 17:06:44 -0700307 // Create Tunnel Interface.
308 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700309 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800310 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
311
Benedict Wonga450e722018-05-07 10:29:02 -0700312 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900313 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700314
Benedict Wong319f17e2018-05-15 17:06:44 -0700315 // Update Tunnel Interface.
316 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700317 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800318 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
319
Benedict Wong319f17e2018-05-15 17:06:44 -0700320 // Remove Tunnel Interface.
321 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800322 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700323
324 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900325 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800326 }
327}
328
Benedict Wong1cb73df2018-12-03 00:54:14 -0800329TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
330 android::base::unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
331 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
332
333 int sockOptVal = UDP_ENCAP_ESPINUDP;
334 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
335
336 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
337 EXPECT_TRUE(res.isOk());
338
339 struct stat info;
340 EXPECT_EQ(0, fstat(sockFd.get(), &info));
341 EXPECT_EQ(1001, (int) info.st_uid);
342}
343
Nathan Harold2deff322018-05-10 14:03:48 -0700344// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
345// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
346#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900347
348using android::net::XfrmController;
349
Benedict Wonga04ffa72018-05-09 21:42:42 -0700350static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
351 static_cast<int>(android::net::XfrmDirection::OUT)};
352static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
353
Nathan Harold21299f72018-03-16 20:13:03 -0700354#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
355 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900356bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900357 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700358 SCOPED_TRACE(status);
359 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
360
361 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700362 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700363 SCOPED_TRACE(status);
364 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
365
366 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700367 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
368 0xD00D, 0xE00D, false)
369 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700370}
371
Benedict Wonga04ffa72018-05-09 21:42:42 -0700372TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900373 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700374
375 // Repeat to ensure cleanup and recreation works correctly
376 for (int i = 0; i < 2; i++) {
377 for (int direction : XFRM_DIRECTIONS) {
378 for (int addrFamily : ADDRESS_FAMILIES) {
379 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700380 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700381 EXPECT_TRUE(status.isOk())
382 << " family: " << addrFamily << " direction: " << direction;
383 }
384 }
385
386 // Cleanup
387 for (int direction : XFRM_DIRECTIONS) {
388 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700389 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700390 EXPECT_TRUE(status.isOk());
391 }
392 }
393 }
394}
395
396TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
397 binder::Status status;
398
399 // Repeat to ensure cleanup and recreation works correctly
400 for (int i = 0; i < 2; i++) {
401 for (int direction : XFRM_DIRECTIONS) {
402 for (int addrFamily : ADDRESS_FAMILIES) {
403 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700404 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700405 EXPECT_TRUE(status.isOk())
406 << " family: " << addrFamily << " direction: " << direction;
407 }
408 }
409
410 // Cleanup
411 for (int direction : XFRM_DIRECTIONS) {
412 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700413 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700414 EXPECT_TRUE(status.isOk());
415 }
416 }
417 }
418}
419
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900420TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900421 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700422 status = XfrmController::Init();
423 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700424
425 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
426 // feature.
427 if (status.code() == EOPNOTSUPP) return;
428
Nathan Harold21299f72018-03-16 20:13:03 -0700429 ASSERT_TRUE(status.ok());
430
431 int32_t spi = 0;
432
433 ASSERT_TRUE(allocateIpSecResources(true, &spi));
434 ASSERT_TRUE(allocateIpSecResources(false, &spi));
435
436 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700437 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700438 ASSERT_TRUE(allocateIpSecResources(true, &spi));
439
440 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700441 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700442 SCOPED_TRACE(status);
443 ASSERT_TRUE(status.ok());
444
Benedict Wonga450e722018-05-07 10:29:02 -0700445 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700446 SCOPED_TRACE(status);
447 ASSERT_TRUE(status.ok());
448
449 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700450 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700451}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900452
453#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700454
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900455static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900456 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900457
458 // Output looks like this:
459 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900460 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900461 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900462 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900463 //
464 // or:
465 //
466 // Chain bw_data_saver (1 references)
467 // target prot opt source destination
468 // ... possibly connectivity critical packet rules here ...
469 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900470
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900471 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900472
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900473 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
474 // Data saver disabled.
475 return 0;
476 }
477
478 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
479
480 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
481 // Data saver enabled.
482 return 1;
483 }
484
485 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900486}
487
488bool enableDataSaver(sp<INetd>& netd, bool enable) {
489 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
490 bool ret;
491 netd->bandwidthEnableDataSaver(enable, &ret);
492 return ret;
493}
494
495int getDataSaverState() {
496 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
497 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
498 EXPECT_EQ(enabled4, enabled6);
499 EXPECT_NE(-1, enabled4);
500 EXPECT_NE(-1, enabled6);
501 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
502 return -1;
503 }
504 return enabled6;
505}
506
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900507TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900508 const int wasEnabled = getDataSaverState();
509 ASSERT_NE(-1, wasEnabled);
510
511 if (wasEnabled) {
512 ASSERT_TRUE(enableDataSaver(mNetd, false));
513 EXPECT_EQ(0, getDataSaverState());
514 }
515
516 ASSERT_TRUE(enableDataSaver(mNetd, false));
517 EXPECT_EQ(0, getDataSaverState());
518
519 ASSERT_TRUE(enableDataSaver(mNetd, true));
520 EXPECT_EQ(1, getDataSaverState());
521
522 ASSERT_TRUE(enableDataSaver(mNetd, true));
523 EXPECT_EQ(1, getDataSaverState());
524
525 if (!wasEnabled) {
526 ASSERT_TRUE(enableDataSaver(mNetd, false));
527 EXPECT_EQ(0, getDataSaverState());
528 }
529}
Robin Leeb8087362016-03-30 18:43:08 +0100530
Luke Huang94658ac2018-10-18 19:35:12 +0900531static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
532 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100533 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100534 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100535 std::vector<std::string> rules = listIpRules(ipVersion);
536
537 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900538 std::string suffix =
539 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900540 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800541 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100542 return true;
543 }
544 }
545 return false;
546}
547
Luke Huang94658ac2018-10-18 19:35:12 +0900548static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
549 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100550 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
551 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
552 EXPECT_EQ(existsIp4, existsIp6);
553 return existsIp4;
554}
555
Luke Huang94658ac2018-10-18 19:35:12 +0900556namespace {
557
558UidRangeParcel makeUidRangeParcel(int start, int stop) {
559 UidRangeParcel res;
560 res.start = start;
561 res.stop = stop;
562
563 return res;
564}
565
566} // namespace
567
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900568TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800569 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
570 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
571 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900572 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
573 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900574
575 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
576 EXPECT_EQ(EBUSY,
577 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
578
579 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
580 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
581 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800582 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900583}
584
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900585TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900586 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
587
cken67cd14c2018-12-05 17:26:59 +0900588 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
589 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900590 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
591
Luke Huang94658ac2018-10-18 19:35:12 +0900592 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
593 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
594 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900595 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
596
597 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
598
599 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
600 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
601 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
602 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
603
604 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
605 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
606 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
607 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
608
609 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
610}
611
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900612TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100613 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100614
Luke Huang94658ac2018-10-18 19:35:12 +0900615 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
616 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100617
618 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
619 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
620
621 // Create two valid rules.
622 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
623 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
624 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
625 for (auto const& range : uidRanges) {
626 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
627 }
628
629 // Remove the rules.
630 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
631 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
632 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
633 for (auto const& range : uidRanges) {
634 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
635 }
636
637 // Fail to remove the rules a second time after they are already deleted.
638 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
639 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
640 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
641
642 // All rules should be the same as before.
643 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
644 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
645}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900646
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900647// Create a socket pair that isLoopbackSocket won't think is local.
648void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900649 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900650 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900651 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
652
653 socklen_t addrlen = sizeof(server6);
654 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
655 ASSERT_EQ(0, listen(*serverSocket, 10));
656
Bernie Innocentif6918262018-06-11 17:37:35 +0900657 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900658 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900659 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900660 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
661 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
662
Bernie Innocentif6918262018-06-11 17:37:35 +0900663 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900664 ASSERT_NE(-1, *acceptedSocket);
665
666 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
667}
668
669void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
670 char buf[4096];
671 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
672 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
673 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
674}
675
676void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
677 // Check that the client socket was closed with ECONNABORTED.
678 int ret = write(clientSocket, "foo", sizeof("foo"));
679 int err = errno;
680 EXPECT_EQ(-1, ret);
681 EXPECT_EQ(ECONNABORTED, err);
682
683 // Check that it sent a RST to the server.
684 ret = write(acceptedSocket, "foo", sizeof("foo"));
685 err = errno;
686 EXPECT_EQ(-1, ret);
687 EXPECT_EQ(ECONNRESET, err);
688}
689
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900690TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900691 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900692 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900693
694 // Pick a random UID in the system UID range.
695 constexpr int baseUid = AID_APP - 2000;
696 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
697 int uid = baseUid + 500 + arc4random_uniform(1000);
698 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
699
700 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900701 std::vector<UidRangeParcel> uidRanges = {
702 makeUidRangeParcel(baseUid + 42, baseUid + 449),
703 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
704 makeUidRangeParcel(baseUid + 498, uid - 1),
705 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900706 };
707 // A skip list that doesn't contain UID.
708 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
709
710 // Close sockets. Our test socket should be intact.
711 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
712 checkSocketpairOpen(clientSocket, acceptedSocket);
713
714 // UID ranges that do contain uid.
715 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900716 makeUidRangeParcel(baseUid + 42, baseUid + 449),
717 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
718 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900719 };
720 // Add uid to the skip list.
721 skipUids.push_back(uid);
722
723 // Close sockets. Our test socket should still be intact because it's in the skip list.
724 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
725 checkSocketpairOpen(clientSocket, acceptedSocket);
726
727 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
728 skipUids.resize(skipUids.size() - 1);
729 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
730 checkSocketpairClosed(clientSocket, acceptedSocket);
731
732 close(clientSocket);
733 close(serverSocket);
734 close(acceptedSocket);
735}
Erik Klinecc4f2732016-08-03 11:24:27 +0900736
737namespace {
738
739int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
740 if (buf == nullptr) return -1;
741
742 int prefixLength = 0;
743 bool endOfContiguousBits = false;
744 for (unsigned int i = 0; i < buflen; i++) {
745 const uint8_t value = buf[i];
746
747 // Bad bit sequence: check for a contiguous set of bits from the high
748 // end by verifying that the inverted value + 1 is a power of 2
749 // (power of 2 iff. (v & (v - 1)) == 0).
750 const uint8_t inverse = ~value + 1;
751 if ((inverse & (inverse - 1)) != 0) return -1;
752
753 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
754
755 // Bogus netmask.
756 if (endOfContiguousBits && value != 0) return -1;
757
758 if (value != 0xff) endOfContiguousBits = true;
759 }
760
761 return prefixLength;
762}
763
764template<typename T>
765int netmaskToPrefixLength(const T *p) {
766 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
767}
768
769
770static bool interfaceHasAddress(
771 const std::string &ifname, const char *addrString, int prefixLength) {
772 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900773
774 const struct addrinfo hints = {
775 .ai_flags = AI_NUMERICHOST,
776 .ai_family = AF_UNSPEC,
777 .ai_socktype = SOCK_DGRAM,
778 };
779 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
780 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
781 return false;
782 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900783 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900784
785 struct ifaddrs *ifaddrsList = nullptr;
786 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
787
788 if (getifaddrs(&ifaddrsList) != 0) {
789 return false;
790 }
791
792 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
793 if (std::string(addr->ifa_name) != ifname ||
794 addr->ifa_addr == nullptr ||
795 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
796 continue;
797 }
798
799 switch (addr->ifa_addr->sa_family) {
800 case AF_INET: {
801 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
802 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
803 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
804 continue;
805 }
806
807 if (prefixLength < 0) return true; // not checking prefix lengths
808
809 if (addr->ifa_netmask == nullptr) return false;
810 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
811 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
812 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
813 }
814 case AF_INET6: {
815 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
816 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
817 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
818 continue;
819 }
820
821 if (prefixLength < 0) return true; // not checking prefix lengths
822
823 if (addr->ifa_netmask == nullptr) return false;
824 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
825 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
826 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
827 }
828 default:
829 // Cannot happen because we have already screened for matching
830 // address families at the top of each iteration.
831 continue;
832 }
833 }
834
835 return false;
836}
837
838} // namespace
839
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900840TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900841 static const struct TestData {
842 const char *addrString;
843 const int prefixLength;
844 const bool expectSuccess;
845 } kTestData[] = {
846 { "192.0.2.1", 24, true },
847 { "192.0.2.2", 25, true },
848 { "192.0.2.3", 32, true },
849 { "192.0.2.4", 33, false },
850 { "192.not.an.ip", 24, false },
851 { "2001:db8::1", 64, true },
852 { "2001:db8::2", 65, true },
853 { "2001:db8::3", 128, true },
854 { "2001:db8::4", 129, false },
855 { "foo:bar::bad", 64, false },
856 };
857
Sehee Park8659b8d2018-11-16 10:53:16 +0900858 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900859 const auto &td = kTestData[i];
860
861 // [1.a] Add the address.
862 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900863 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900864 if (td.expectSuccess) {
865 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
866 } else {
867 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
868 ASSERT_NE(0, status.serviceSpecificErrorCode());
869 }
870
871 // [1.b] Verify the addition meets the expectation.
872 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900873 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900874 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900875 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900876 }
877
878 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900879 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900880 if (td.expectSuccess) {
881 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
882 } else {
883 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
884 ASSERT_NE(0, status.serviceSpecificErrorCode());
885 }
886
887 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900888 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900889 }
890}
Erik Kline55b06f82016-07-04 09:57:18 +0900891
Erik Kline38e51f12018-09-06 20:14:44 +0900892TEST_F(BinderTest, GetProcSysNet) {
893 const char LOOPBACK[] = "lo";
894 static const struct {
895 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900896 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900897 const char* ifname;
898 const char* parameter;
899 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900900 const int expectedReturnCode;
901 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900902 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
903 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
904 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
905 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
906 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
907 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
908 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900909 };
910
Sehee Park8659b8d2018-11-16 10:53:16 +0900911 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900912 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900913
Erik Kline38e51f12018-09-06 20:14:44 +0900914 std::string value;
915 const binder::Status status =
916 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
917
918 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900919 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900920 EXPECT_EQ(0, status.exceptionCode());
921 EXPECT_EQ(0, status.serviceSpecificErrorCode());
922 EXPECT_EQ(td.expectedValue, value);
923 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900924 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900925 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
926 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
927 }
928 }
929}
930
931TEST_F(BinderTest, SetProcSysNet) {
932 static const struct {
933 const int ipversion;
934 const int which;
935 const char* ifname;
936 const char* parameter;
937 const char* value;
938 const int expectedReturnCode;
939 } kTestData[] = {
940 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
941 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
942 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
943 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
944 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
945 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
946 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
947 };
948
Sehee Park8659b8d2018-11-16 10:53:16 +0900949 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900950 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900951 const binder::Status status =
952 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900953
954 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900955 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900956 EXPECT_EQ(0, status.exceptionCode());
957 EXPECT_EQ(0, status.serviceSpecificErrorCode());
958 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900959 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900960 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
961 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
962 }
963 }
964}
Ben Schwartze7601812017-04-28 16:38:29 -0400965
Erik Kline38e51f12018-09-06 20:14:44 +0900966TEST_F(BinderTest, GetSetProcSysNet) {
967 const int ipversion = INetd::IPV6;
968 const int category = INetd::NEIGH;
969 const std::string& tun = sTun.name();
970 const std::string parameter("ucast_solicit");
971
972 std::string value{};
973 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
974 EXPECT_FALSE(value.empty());
975 const int ival = std::stoi(value);
976 EXPECT_GT(ival, 0);
977 // Try doubling the parameter value (always best!).
978 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
979 .isOk());
980 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
981 EXPECT_EQ(2 * ival, std::stoi(value));
982 // Try resetting the parameter.
983 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
984 .isOk());
985 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
986 EXPECT_EQ(ival, std::stoi(value));
987}
988
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900989namespace {
990
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900991void expectNoTestCounterRules() {
992 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
993 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
994 std::string allRules = Join(runCommand(command), "\n");
995 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
996 }
997}
998
Bernie Innocentif6918262018-06-11 17:37:35 +0900999void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1000 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001001 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1002 path, if1.c_str(), if2.c_str(), pkt, byte));
1003}
1004
Bernie Innocentif6918262018-06-11 17:37:35 +09001005void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001006 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1007 path, if1.c_str(), if2.c_str()));
1008 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1009 path, if2.c_str(), if1.c_str()));
1010}
1011
Luke Huangcaebcbb2018-09-27 20:37:14 +08001012std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1013 const std::string& iface) {
1014 for (auto& stats : statsVec) {
1015 if (stats.iface == iface) {
1016 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1017 }
1018 }
1019 return {};
1020}
1021
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001022} // namespace
1023
1024TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001025 expectNoTestCounterRules();
1026
1027 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1028 // disabling tethering. We don't check the return value because these commands will fail if
1029 // tethering is already enabled.
1030 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1031 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1032
1033 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1034 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1035 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1036 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1037 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1038
1039 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1040 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1041 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1042 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1043 // RX is from external to internal, and TX is from internal to external.
1044 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1045 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1046
1047 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1048 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1049
1050 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1051 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1052
1053 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1054 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1055 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1056
Luke Huangcaebcbb2018-09-27 20:37:14 +08001057 std::vector<TetherStatsParcel> statsVec;
1058 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001059 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1060
Luke Huangcaebcbb2018-09-27 20:37:14 +08001061 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001062
Luke Huangcaebcbb2018-09-27 20:37:14 +08001063 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001064
1065 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1066 delTetherCounterValues(path, intIface1, extIface1);
1067 delTetherCounterValues(path, intIface2, extIface2);
1068 if (path == IP6TABLES_PATH) {
1069 delTetherCounterValues(path, intIface3, extIface2);
1070 }
1071 }
1072
1073 expectNoTestCounterRules();
1074}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001075
Luke Huang0051a622018-07-23 20:30:16 +08001076namespace {
1077
Luke Huanga5211072018-08-01 23:36:29 +08001078constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1079constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001080
1081static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1082 const char* chainName) {
1083 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1084 return runCommand(command);
1085}
1086
Luke Huang19b49c52018-10-22 12:12:05 +09001087// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001088bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001089 const std::string& expectedInterface,
1090 const std::string& expectedRule, const char* table) {
1091 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1092 for (const auto& rule : rules) {
1093 if (rule.find(expectedInterface) != std::string::npos) {
1094 if (rule.find(expectedRule) != std::string::npos) {
1095 return true;
1096 }
1097 }
1098 }
1099 return false;
1100}
1101
1102void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001103 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001104 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001105 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001106 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001107 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1108 IdletimerRule, RAW_TABLE));
1109 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001110 ifname, IdletimerRule, MANGLE_TABLE));
1111 }
1112}
1113
1114void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001115 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001116 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001117 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001118 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001119 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1120 IdletimerRule, RAW_TABLE));
1121 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001122 ifname, IdletimerRule, MANGLE_TABLE));
1123 }
1124}
1125
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001126} // namespace
1127
1128TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001129 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1130 // rule in the table. Because we only check the result after calling remove function. We might
1131 // check the actual rule which is removed by our function (maybe compare the results between
1132 // calling function before and after)
1133 binder::Status status;
1134 const struct TestData {
1135 const std::string ifname;
1136 int32_t timeout;
1137 const std::string classLabel;
1138 } idleTestData[] = {
1139 {"wlan0", 1234, "happyday"},
1140 {"rmnet_data0", 4567, "friday"},
1141 };
1142 for (const auto& td : idleTestData) {
1143 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1144 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1145 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1146
1147 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1148 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1149 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1150 }
1151}
1152
Luke Huanga67dd562018-07-17 19:58:25 +08001153namespace {
1154
1155constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1156constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1157
1158void expectStrictSetUidAccept(const int uid) {
1159 std::string uidRule = StringPrintf("owner UID match %u", uid);
1160 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1161 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001162 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1163 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001164 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1165 }
1166}
1167
1168void expectStrictSetUidLog(const int uid) {
1169 static const char logRule[] = "st_penalty_log all";
1170 std::string uidRule = StringPrintf("owner UID match %u", uid);
1171 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1172 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001173 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1174 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001175 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1176 }
1177}
1178
1179void expectStrictSetUidReject(const int uid) {
1180 static const char rejectRule[] = "st_penalty_reject all";
1181 std::string uidRule = StringPrintf("owner UID match %u", uid);
1182 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1183 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001184 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1185 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001186 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1187 }
1188}
1189
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001190} // namespace
1191
1192TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001193 binder::Status status;
1194 int32_t uid = randomUid();
1195
1196 // setUidCleartextPenalty Policy:Log with randomUid
1197 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1198 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1199 expectStrictSetUidLog(uid);
1200
1201 // setUidCleartextPenalty Policy:Accept with randomUid
1202 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1203 expectStrictSetUidAccept(uid);
1204
1205 // setUidCleartextPenalty Policy:Reject with randomUid
1206 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1207 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1208 expectStrictSetUidReject(uid);
1209
1210 // setUidCleartextPenalty Policy:Accept with randomUid
1211 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1212 expectStrictSetUidAccept(uid);
1213
1214 // test wrong policy
1215 int32_t wrongPolicy = -123;
1216 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1217 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1218}
1219
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001220namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001221
Luke Huangd1675922019-03-11 17:29:27 +08001222std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001223 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001224 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001225 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1226 // ...
1227 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1228
Luke Huangd1675922019-03-11 17:29:27 +08001229 // (dnsmasq)
1230 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1231
1232 if (maxTries == 0) return {};
1233
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001234 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001235 std::vector<std::string> result;
1236 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001237 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001238 if (result.size() || ++run > maxTries) {
1239 break;
1240 }
1241
Luke Huang728cf4c2019-03-14 19:43:02 +08001242 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001243 }
1244 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001245}
1246
Luke Huangd1675922019-03-11 17:29:27 +08001247void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001248 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001249}
1250
Luke Huang728cf4c2019-03-14 19:43:02 +08001251void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001252 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001253}
1254
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001255} // namespace
1256
1257TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001258 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001259
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001260 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1261 std::string clatAddress;
1262 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001263
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001264 // Can't start clatd on an interface that's not part of any network...
1265 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1266 EXPECT_FALSE(status.isOk());
1267 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1268
1269 // ... so create a test physical network and add our tun to it.
1270 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1271 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1272
1273 // Prefix must be 96 bits long.
1274 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1275 EXPECT_FALSE(status.isOk());
1276 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1277
1278 // Can't start clatd unless there's a default route...
1279 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1280 EXPECT_FALSE(status.isOk());
1281 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1282
1283 // so add a default route.
1284 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1285
1286 // Can't start clatd unless there's a global address...
1287 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1288 EXPECT_FALSE(status.isOk());
1289 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1290
1291 // ... so add a global address.
1292 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001293 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001294
1295 // Now expect clatd to start successfully.
1296 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1297 EXPECT_TRUE(status.isOk());
1298 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1299
1300 // Starting it again returns EBUSY.
1301 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1302 EXPECT_FALSE(status.isOk());
1303 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1304
Luke Huangd1675922019-03-11 17:29:27 +08001305 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001306
1307 // Expect clatd to stop successfully.
1308 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001309 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001310 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001311
1312 // Stopping a clatd that doesn't exist returns ENODEV.
1313 status = mNetd->clatdStop(sTun.name());
1314 EXPECT_FALSE(status.isOk());
1315 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001316 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001317
1318 // Clean up.
1319 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1320 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1321 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001322}
Luke Huang457d4702018-08-16 15:39:15 +08001323
1324namespace {
1325
1326bool getIpfwdV4Enable() {
1327 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1328 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1329 EXPECT_TRUE(!result.empty());
1330 int v4Enable = std::stoi(result[0]);
1331 return v4Enable;
1332}
1333
1334bool getIpfwdV6Enable() {
1335 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1336 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1337 EXPECT_TRUE(!result.empty());
1338 int v6Enable = std::stoi(result[0]);
1339 return v6Enable;
1340}
1341
1342void expectIpfwdEnable(bool enable) {
1343 int enableIPv4 = getIpfwdV4Enable();
1344 int enableIPv6 = getIpfwdV6Enable();
1345 EXPECT_EQ(enable, enableIPv4);
1346 EXPECT_EQ(enable, enableIPv6);
1347}
1348
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001349bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001350 std::vector<std::string> rules = listIpRules(ipVersion);
1351 for (const auto& rule : rules) {
1352 if (rule.find(ipfwdRule) != std::string::npos) {
1353 return true;
1354 }
1355 }
1356 return false;
1357}
1358
1359void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1360 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1361
1362 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1363 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1364 }
1365}
1366
1367void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1368 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1369
1370 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1371 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1372 }
1373}
1374
1375} // namespace
1376
1377TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001378 // Get ipfwd requester list from Netd
1379 std::vector<std::string> requesterList;
1380 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001381 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001382
1383 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001384 if (requesterList.size() == 0) {
1385 // No requester in Netd, ipfwd should be disabled
1386 // So add one test requester and verify
1387 status = mNetd->ipfwdEnableForwarding("TestRequester");
1388 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001389
Luke Huang728cf4c2019-03-14 19:43:02 +08001390 expectIpfwdEnable(true);
1391 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1392 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1393 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001394
Luke Huang728cf4c2019-03-14 19:43:02 +08001395 // Remove test one, verify again
1396 status = mNetd->ipfwdDisableForwarding("TestRequester");
1397 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1398
1399 expectIpfwdEnable(false);
1400 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1401 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1402 EXPECT_FALSE(ipfwdEnabled);
1403 } else {
1404 // Disable all requesters
1405 for (const auto& requester : requesterList) {
1406 status = mNetd->ipfwdDisableForwarding(requester);
1407 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1408 }
1409
1410 // After disable all requester, ipfwd should be disabled
1411 expectIpfwdEnable(false);
1412 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1413 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1414 EXPECT_FALSE(ipfwdEnabled);
1415
1416 // Enable them back
1417 for (const auto& requester : requesterList) {
1418 status = mNetd->ipfwdEnableForwarding(requester);
1419 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1420 }
1421
1422 // ipfwd should be enabled
1423 expectIpfwdEnable(true);
1424 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1425 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1426 EXPECT_TRUE(ipfwdEnabled);
1427 }
Luke Huang457d4702018-08-16 15:39:15 +08001428}
1429
1430TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001431 // Add test physical network
1432 EXPECT_TRUE(
1433 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1434 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1435 EXPECT_TRUE(
1436 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1437 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001438
Luke Huangd1827b82019-02-15 15:03:27 +08001439 binder::Status status =
1440 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1441 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1442 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001443
Luke Huangd1827b82019-02-15 15:03:27 +08001444 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1445 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1446 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001447}
Luke Huang531f5d32018-08-03 15:19:05 +08001448
1449namespace {
1450
1451constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1452constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1453constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1454constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1455constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001456constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001457
Luke Huang19b49c52018-10-22 12:12:05 +09001458// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1459// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001460bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1461 const char* chainName, const std::string& expectedTargetA,
1462 const std::string& expectedTargetB) {
1463 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1464 int matchCount = 0;
1465
1466 for (const auto& rule : rules) {
1467 if (rule.find(expectedTargetA) != std::string::npos) {
1468 if (rule.find(expectedTargetB) != std::string::npos) {
1469 matchCount++;
1470 }
1471 }
1472 }
1473 return matchCount == expectedCount;
1474}
1475
1476void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1477 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1478 std::string result = "";
1479
1480 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001481 // Quota value might be decreased while matching packets
1482 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001483}
1484
1485void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1486 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1487 std::string quotaRule = StringPrintf("quota %s", ifname);
1488
1489 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1490 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1491 BANDWIDTH_COSTLY_IF));
1492 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1493 BANDWIDTH_COSTLY_IF));
1494 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1495 BANDWIDTH_COSTLY_IF));
1496 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1497 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1498 }
1499 expectXtQuotaValueEqual(ifname, quotaBytes);
1500}
1501
1502void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1503 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1504 std::string quotaRule = StringPrintf("quota %s", ifname);
1505
1506 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1507 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1508 BANDWIDTH_COSTLY_IF));
1509 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1510 BANDWIDTH_COSTLY_IF));
1511 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1512 BANDWIDTH_COSTLY_IF));
1513 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1514 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1515 }
1516}
1517
1518void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1519 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1520 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1521 std::string alertName = StringPrintf("%sAlert", ifname);
1522
1523 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1524 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1525 }
1526 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1527}
1528
1529void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1530 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1531 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1532
1533 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1534 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1535 }
1536}
1537
1538void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1539 static const char globalAlertRule[] = "quota globalAlert";
1540 static const char globalAlertName[] = "globalAlert";
1541
1542 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001543 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001544 }
1545 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1546}
1547
1548void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1549 std::string uidRule = StringPrintf("owner UID match %u", uid);
1550
1551 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1552 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1553 }
1554}
1555
1556void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1557 std::string uidRule = StringPrintf("owner UID match %u", uid);
1558
1559 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1560 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1561 }
1562}
1563
1564} // namespace
1565
1566TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1567 long testQuotaBytes = 5550;
1568
1569 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001570 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001571 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1572
1573 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1574 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1575 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1576
1577 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1578 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1579 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1580
1581 // Remove test physical network
1582 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1583}
1584
1585TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1586 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001587 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001588 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001589 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001590 // Need to have a prior interface quota set to set an alert
1591 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1592 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1593 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1594 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1595
1596 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1597 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1598 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1599
1600 // Remove interface quota
1601 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1602 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1603 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1604
1605 // Remove test physical network
1606 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1607}
1608
1609TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1610 long testAlertBytes = 2097149;
1611
1612 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1613 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1614 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1615
1616 testAlertBytes = 2097152;
1617 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1618 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1619 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1620}
1621
1622TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1623 SKIP_IF_BPF_SUPPORTED;
1624
1625 int32_t uid = randomUid();
1626 static const char targetReject[] = "REJECT";
1627 static const char targetReturn[] = "RETURN";
1628
1629 // add NaughtyApp
1630 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1631 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1632 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1633
1634 // remove NaughtyApp
1635 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1636 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1637 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1638
1639 // add NiceApp
1640 status = mNetd->bandwidthAddNiceApp(uid);
1641 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1642 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1643
1644 // remove NiceApp
1645 status = mNetd->bandwidthRemoveNiceApp(uid);
1646 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1647 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1648}
Luke Huangb5733d72018-08-21 17:17:19 +08001649
1650namespace {
1651
Luke Huangb670d162018-08-23 20:01:13 +08001652std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1653 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1654 return runCommand(command);
1655}
1656
Luke Huangc3252cc2018-10-16 15:43:23 +08001657bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001658 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1659 for (const auto& route : routes) {
1660 if (route.find(ipRoute) != std::string::npos) {
1661 return true;
1662 }
1663 }
1664 return false;
1665}
1666
Luke Huangc3252cc2018-10-16 15:43:23 +08001667std::string ipRouteString(const std::string& ifName, const std::string& dst,
1668 const std::string& nextHop) {
1669 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1670
1671 if (!nextHop.empty()) {
1672 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001673 }
1674
Luke Huangc3252cc2018-10-16 15:43:23 +08001675 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001676}
1677
Luke Huangc3252cc2018-10-16 15:43:23 +08001678void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1679 const std::string& dst, const std::string& nextHop,
1680 const char* table) {
1681 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1682}
1683
1684void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001685 const std::string& dst, const std::string& nextHop,
1686 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001687 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001688}
1689
1690bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1691 std::vector<std::string> rules = listIpRules(ipVersion);
1692 for (const auto& rule : rules) {
1693 if (rule.find(ipRule) != std::string::npos) {
1694 return true;
1695 }
1696 }
1697 return false;
1698}
1699
1700void expectNetworkDefaultIpRuleExists(const char* ifName) {
1701 std::string networkDefaultRule =
1702 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1703
1704 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1705 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1706 }
1707}
1708
1709void expectNetworkDefaultIpRuleDoesNotExist() {
1710 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1711
1712 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1713 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1714 }
1715}
1716
1717void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1718 std::string networkPermissionRule = "";
1719 switch (permission) {
1720 case INetd::PERMISSION_NONE:
1721 networkPermissionRule = StringPrintf(
1722 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1723 break;
1724 case INetd::PERMISSION_NETWORK:
1725 networkPermissionRule = StringPrintf(
1726 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1727 break;
1728 case INetd::PERMISSION_SYSTEM:
1729 networkPermissionRule = StringPrintf(
1730 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1731 break;
1732 }
1733
1734 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1735 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1736 }
1737}
1738
1739// TODO: It is a duplicate function, need to remove it
1740bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1741 const std::string& expectedInterface,
1742 const std::string& expectedRule,
1743 const char* table) {
1744 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1745 for (const auto& rule : rules) {
1746 if (rule.find(expectedInterface) != std::string::npos) {
1747 if (rule.find(expectedRule) != std::string::npos) {
1748 return true;
1749 }
1750 }
1751 }
1752 return false;
1753}
1754
1755void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1756 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1757 std::string networkIncomingPacketMarkRule = "";
1758 switch (permission) {
1759 case INetd::PERMISSION_NONE:
1760 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1761 break;
1762 case INetd::PERMISSION_NETWORK:
1763 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1764 break;
1765 case INetd::PERMISSION_SYSTEM:
1766 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1767 break;
1768 }
1769
1770 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1771 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1772 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1773 }
1774}
1775
1776} // namespace
1777
1778TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001779 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001780 const char* ipVersion;
1781 const char* testDest;
1782 const char* testNextHop;
1783 const bool expectSuccess;
1784 } kTestData[] = {
1785 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001786 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1787 {IP_RULE_V4, "10.251.0.0/16", "", true},
1788 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1789 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001790 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001791 {IP_RULE_V6, "::/0", "2001:db8::", true},
1792 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001793 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1794 };
1795
Luke Huangc3252cc2018-10-16 15:43:23 +08001796 static const struct {
1797 const char* ipVersion;
1798 const char* testDest;
1799 const char* testNextHop;
1800 } kTestDataWithNextHop[] = {
1801 {IP_RULE_V4, "10.251.10.0/30", ""},
1802 {IP_RULE_V6, "2001:db8::/32", ""},
1803 };
1804
Luke Huangb670d162018-08-23 20:01:13 +08001805 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001806 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001807 const int testUid = randomUid();
1808 const std::vector<int32_t> testUids = {testUid};
1809
1810 // Add test physical network
1811 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1812 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1813
Luke Huangc3252cc2018-10-16 15:43:23 +08001814 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001815 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001816 const auto& td = kTestDataWithNextHop[i];
1817
1818 // All route for test tun will disappear once the tun interface is deleted.
1819 binder::Status status =
1820 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1821 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1822 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1823 sTun.name().c_str());
1824
1825 // Add system permission for test uid, setup route in legacy system table.
1826 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1827
1828 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1829 testUid);
1830 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1831 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1832 testTableLegacySystem);
1833
1834 // Remove system permission for test uid, setup route in legacy network table.
1835 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1836
1837 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1838 testUid);
1839 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1840 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1841 testTableLegacyNetwork);
1842 }
1843
Sehee Park8659b8d2018-11-16 10:53:16 +09001844 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001845 const auto& td = kTestData[i];
1846
1847 binder::Status status =
1848 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1849 if (td.expectSuccess) {
1850 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001851 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001852 sTun.name().c_str());
1853 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001854 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1855 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001856 }
1857
1858 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1859 if (td.expectSuccess) {
1860 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001861 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1862 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001863 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001864 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1865 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001866 }
1867
Luke Huangc3252cc2018-10-16 15:43:23 +08001868 // Add system permission for test uid, route will be added into legacy system table.
1869 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001870
1871 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1872 testUid);
1873 if (td.expectSuccess) {
1874 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001875 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001876 testTableLegacySystem);
1877 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001878 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1879 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001880 }
1881
1882 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1883 td.testNextHop, testUid);
1884 if (td.expectSuccess) {
1885 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001886 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1887 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001888 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001889 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1890 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001891 }
1892
Luke Huangc3252cc2018-10-16 15:43:23 +08001893 // Remove system permission for test uid, route will be added into legacy network table.
1894 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1895
1896 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1897 testUid);
1898 if (td.expectSuccess) {
1899 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1900 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1901 testTableLegacyNetwork);
1902 } else {
1903 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1904 EXPECT_NE(0, status.serviceSpecificErrorCode());
1905 }
1906
1907 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1908 td.testNextHop, testUid);
1909 if (td.expectSuccess) {
1910 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1911 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1912 testTableLegacyNetwork);
1913 } else {
1914 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1915 EXPECT_NE(0, status.serviceSpecificErrorCode());
1916 }
Luke Huangb670d162018-08-23 20:01:13 +08001917 }
1918
1919 // Remove test physical network
1920 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1921}
1922
1923TEST_F(BinderTest, NetworkPermissionDefault) {
1924 // Add test physical network
1925 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1926 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1927
Luke Huangc3252cc2018-10-16 15:43:23 +08001928 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001929 int currentNetid;
1930 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1931 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1932
1933 // Test SetDefault
1934 status = mNetd->networkSetDefault(TEST_NETID1);
1935 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1936 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1937
1938 status = mNetd->networkClearDefault();
1939 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1940 expectNetworkDefaultIpRuleDoesNotExist();
1941
1942 // Add default network back
1943 status = mNetd->networkSetDefault(currentNetid);
1944 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1945
1946 // Test SetPermission
1947 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1948 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1949 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1950 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1951
1952 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1953 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1954 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1955 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1956
1957 // Remove test physical network
1958 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1959}
1960
1961TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1962 const int testUid = randomUid();
1963 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1964 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1965 bool ret = false;
1966 status = mNetd->networkCanProtect(testUid, &ret);
1967 EXPECT_TRUE(ret);
1968
1969 status = mNetd->networkSetProtectDeny(testUid);
1970 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1971 status = mNetd->networkCanProtect(testUid, &ret);
1972 EXPECT_FALSE(ret);
1973}
1974
1975namespace {
1976
Luke Huangb5733d72018-08-21 17:17:19 +08001977int readIntFromPath(const std::string& path) {
1978 std::string result = "";
1979 EXPECT_TRUE(ReadFileToString(path, &result));
1980 return std::stoi(result);
1981}
1982
1983int getTetherAcceptIPv6Ra(const std::string& ifName) {
1984 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1985 return readIntFromPath(path);
1986}
1987
1988bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1989 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1990 return readIntFromPath(path);
1991}
1992
1993int getTetherIPv6DadTransmits(const std::string& ifName) {
1994 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1995 return readIntFromPath(path);
1996}
1997
1998bool getTetherEnableIPv6(const std::string& ifName) {
1999 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2000 int disableIPv6 = readIntFromPath(path);
2001 return !disableIPv6;
2002}
2003
2004bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2005 for (const auto& iface : ifList) {
2006 if (iface == ifName) {
2007 return true;
2008 }
2009 }
2010 return false;
2011}
2012
2013void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2014 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2015 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2016 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2017 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2018}
2019
2020void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2021 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2022 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2023 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2024 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2025}
2026
2027void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2028 const std::string& ifName) {
2029 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2030}
2031
2032void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2033 const std::string& ifName) {
2034 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2035}
2036
2037void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2038 const std::vector<std::string>& testDnsAddrs) {
2039 EXPECT_TRUE(dnsList == testDnsAddrs);
2040}
2041
2042} // namespace
2043
2044TEST_F(BinderTest, TetherStartStopStatus) {
2045 std::vector<std::string> noDhcpRange = {};
2046 static const char dnsdName[] = "dnsmasq";
2047
2048 binder::Status status = mNetd->tetherStart(noDhcpRange);
2049 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangd1675922019-03-11 17:29:27 +08002050 expectProcessExists(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002051
2052 bool tetherEnabled;
2053 status = mNetd->tetherIsEnabled(&tetherEnabled);
2054 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2055 EXPECT_TRUE(tetherEnabled);
2056
2057 status = mNetd->tetherStop();
2058 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08002059 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002060
2061 status = mNetd->tetherIsEnabled(&tetherEnabled);
2062 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2063 EXPECT_FALSE(tetherEnabled);
2064}
2065
2066TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2067 // TODO: verify if dnsmasq update interface successfully
2068
2069 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2070 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2071 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2072
2073 std::vector<std::string> ifList;
2074 status = mNetd->tetherInterfaceList(&ifList);
2075 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2076 expectTetherInterfaceExists(ifList, sTun.name());
2077
2078 status = mNetd->tetherInterfaceRemove(sTun.name());
2079 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2080 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2081
2082 status = mNetd->tetherInterfaceList(&ifList);
2083 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2084 expectTetherInterfaceNotExists(ifList, sTun.name());
2085}
2086
2087TEST_F(BinderTest, TetherDnsSetList) {
2088 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002089 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2090 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002091
2092 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2093 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2094
2095 std::vector<std::string> dnsList;
2096 status = mNetd->tetherDnsList(&dnsList);
2097 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2098 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002099}
2100
2101namespace {
2102
2103constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2104constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2105constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2106constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2107constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2108constexpr char FIREWALL_STANDBY[] = "fw_standby";
2109constexpr char targetReturn[] = "RETURN";
2110constexpr char targetDrop[] = "DROP";
2111
2112void expectFirewallWhitelistMode() {
2113 static const char dropRule[] = "DROP all";
2114 static const char rejectRule[] = "REJECT all";
2115 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2116 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2117 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2118 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2119 }
2120}
2121
2122void expectFirewallBlacklistMode() {
2123 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2124 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2125 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2126 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2127 }
2128}
2129
2130bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2131 const std::string& expectedInterface,
2132 const std::string& expectedRule) {
2133 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2134 // Expected rule:
2135 // Chain fw_INPUT (1 references)
2136 // pkts bytes target prot opt in out source destination
2137 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2138 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2139 int firstRuleIndex = 2;
2140 if (rules.size() < 4) return false;
2141 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2142 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2143 return true;
2144 }
2145 }
2146 return false;
2147}
2148
2149// TODO: It is a duplicate function, need to remove it
2150bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2151 const std::string& expectedInterface,
2152 const std::string& expectedRule) {
2153 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2154 for (const auto& rule : rules) {
2155 if (rule.find(expectedInterface) != std::string::npos) {
2156 if (rule.find(expectedRule) != std::string::npos) {
2157 return true;
2158 }
2159 }
2160 }
2161 return false;
2162}
2163
2164void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2165 static const char returnRule[] = "RETURN all";
2166 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2167 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2168 returnRule));
2169 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2170 returnRule));
2171 }
2172}
2173
2174void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2175 static const char returnRule[] = "RETURN all";
2176 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2177 EXPECT_FALSE(
2178 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2179 EXPECT_FALSE(
2180 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2181 }
2182}
2183
2184bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2185 const std::string& expectedTarget,
2186 const std::string& expectedRule) {
2187 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2188 int firstRuleIndex = 2;
2189 if (rules.size() < 4) return false;
2190 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2191 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2192 return true;
2193 }
2194 }
2195 return false;
2196}
2197
2198bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2199 const std::string& expectedTarget,
2200 const std::string& expectedRule) {
2201 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2202 int lastRuleIndex = rules.size() - 1;
2203 if (lastRuleIndex < 0) return false;
2204 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2205 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2206 return true;
2207 }
2208 }
2209 return false;
2210}
2211
2212void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2213 std::string uidRule = StringPrintf("owner UID match %u", uid);
2214 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2215 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2216}
2217
2218void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2219 std::string uidRule = StringPrintf("owner UID match %u", uid);
2220 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2221 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2222}
2223
2224void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2225 std::string uidRule = StringPrintf("owner UID match %u", uid);
2226 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2227 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2228}
2229
2230void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2231 std::string uidRule = StringPrintf("owner UID match %u", uid);
2232 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2233 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2234}
2235
2236bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2237 std::vector<std::string> inputRules =
2238 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2239 std::vector<std::string> outputRules =
2240 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2241 int inputLastRuleIndex = inputRules.size() - 1;
2242 int outputLastRuleIndex = outputRules.size() - 1;
2243
2244 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2245 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2246 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2247 return true;
2248 }
2249 }
2250 return false;
2251}
2252
2253void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2254 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2255 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2256}
2257
2258void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2259 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2260 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2261 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2262 }
2263}
2264
2265} // namespace
2266
2267TEST_F(BinderTest, FirewallSetFirewallType) {
2268 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2269 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2270 expectFirewallWhitelistMode();
2271
2272 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2273 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2274 expectFirewallBlacklistMode();
2275
2276 // set firewall type blacklist twice
2277 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2278 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2279 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2280 expectFirewallBlacklistMode();
2281
2282 // set firewall type whitelist twice
2283 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2284 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2285 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2286 expectFirewallWhitelistMode();
2287
2288 // reset firewall type to default
2289 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2290 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2291 expectFirewallBlacklistMode();
2292}
2293
2294TEST_F(BinderTest, FirewallSetInterfaceRule) {
2295 // setinterfaceRule is not supported in BLACKLIST MODE
2296 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2297 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2298
2299 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2300 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2301
2302 // set WHITELIST mode first
2303 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2304 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2305
2306 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2307 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2308 expectFirewallInterfaceRuleAllowExists(sTun.name());
2309
2310 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2311 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2312 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2313
2314 // reset firewall mode to default
2315 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2316 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2317 expectFirewallBlacklistMode();
2318}
2319
2320TEST_F(BinderTest, FirewallSetUidRule) {
2321 SKIP_IF_BPF_SUPPORTED;
2322
2323 int32_t uid = randomUid();
2324
2325 // Doze allow
2326 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2327 INetd::FIREWALL_RULE_ALLOW);
2328 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2329 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2330
2331 // Doze deny
2332 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2333 INetd::FIREWALL_RULE_DENY);
2334 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2335 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2336
2337 // Powersave allow
2338 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2339 INetd::FIREWALL_RULE_ALLOW);
2340 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2341 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2342
2343 // Powersave deny
2344 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2345 INetd::FIREWALL_RULE_DENY);
2346 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2347 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2348
2349 // Standby deny
2350 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2351 INetd::FIREWALL_RULE_DENY);
2352 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2353 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2354
2355 // Standby allow
2356 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2357 INetd::FIREWALL_RULE_ALLOW);
2358 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2359 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2360
2361 // None deny in BLACKLIST
2362 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2363 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2364 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2365 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2366
2367 // None allow in BLACKLIST
2368 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2369 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2370 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2371 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2372
2373 // set firewall type whitelist twice
2374 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2375 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2376 expectFirewallWhitelistMode();
2377
2378 // None allow in WHITELIST
2379 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2380 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2381 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2382 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2383
2384 // None deny in WHITELIST
2385 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2386 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2387 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2388 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2389
2390 // reset firewall mode to default
2391 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2392 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2393 expectFirewallBlacklistMode();
2394}
2395
2396TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2397 SKIP_IF_BPF_SUPPORTED;
2398
2399 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2400 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2401 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2402
2403 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2404 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2405 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2406
2407 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2408 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2409 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2410
2411 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2412 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2413 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2414
2415 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2416 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2417 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2418
2419 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2420 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2421 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2422}
Luke Huangf7782042018-08-08 13:13:04 +08002423
2424namespace {
2425
2426std::string hwAddrToStr(unsigned char* hwaddr) {
2427 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2428 hwaddr[4], hwaddr[5]);
2429}
2430
2431int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2432 int prefixLength = 0;
2433 uint32_t m = ntohl(mask);
2434 while (m & (1 << 31)) {
2435 prefixLength++;
2436 m = m << 1;
2437 }
2438 return prefixLength;
2439}
2440
2441std::string toStdString(const String16& s) {
2442 return std::string(String8(s.string()));
2443}
2444
2445android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2446 const auto& sys = sSyscalls.get();
2447 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2448 EXPECT_TRUE(isOk(fd.status()));
2449
2450 struct ifreq ifr = {};
2451 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2452
2453 return sys.ioctl(fd.value(), flag, &ifr);
2454}
2455
2456std::string getInterfaceHwAddr(const std::string& ifName) {
2457 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2458
2459 unsigned char hwaddr[ETH_ALEN] = {};
2460 if (isOk(res.status())) {
2461 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2462 }
2463
2464 return hwAddrToStr(hwaddr);
2465}
2466
2467int getInterfaceIPv4Prefix(const std::string& ifName) {
2468 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2469
2470 int prefixLength = 0;
2471 if (isOk(res.status())) {
2472 prefixLength = ipv4NetmaskToPrefixLength(
2473 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2474 }
2475
2476 return prefixLength;
2477}
2478
2479std::string getInterfaceIPv4Addr(const std::string& ifName) {
2480 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2481
2482 struct in_addr addr = {};
2483 if (isOk(res.status())) {
2484 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2485 }
2486
2487 return std::string(inet_ntoa(addr));
2488}
2489
2490std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2491 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2492
2493 unsigned flags = 0;
2494 if (isOk(res.status())) {
2495 flags = res.value().ifr_flags;
2496 }
2497
2498 std::vector<std::string> ifFlags;
2499 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2500 : toStdString(INetd::IF_STATE_DOWN()));
2501
2502 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2503 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2504 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2505 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2506 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2507
2508 return ifFlags;
2509}
2510
2511bool compareListInterface(const std::vector<std::string>& interfaceList) {
2512 const auto& res = InterfaceController::getIfaceNames();
2513 EXPECT_TRUE(isOk(res));
2514
2515 std::vector<std::string> resIfList;
2516 resIfList.reserve(res.value().size());
2517 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2518
2519 return resIfList == interfaceList;
2520}
2521
2522int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2523 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2524 return readIntFromPath(path);
2525}
2526
2527bool getInterfaceEnableIPv6(const std::string& ifName) {
2528 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2529
2530 int disableIPv6 = readIntFromPath(path);
2531 return !disableIPv6;
2532}
2533
2534int getInterfaceMtu(const std::string& ifName) {
2535 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2536 return readIntFromPath(path);
2537}
2538
2539void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2540 EXPECT_TRUE(compareListInterface(interfaceList));
2541}
2542
2543void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2544 const InterfaceConfigurationParcel& interfaceCfg) {
2545 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2546 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2547 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2548 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2549}
2550
2551void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2552 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2553 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2554
2555 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2556 for (const auto& flag : setCfg.flags) {
2557 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2558 }
2559}
2560
2561void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2562 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2563 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2564}
2565
2566void expectInterfaceNoAddr(const std::string& ifName) {
2567 // noAddr
2568 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2569 // noPrefix
2570 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2571}
2572
2573void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2574 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2575 EXPECT_EQ(enableIPv6, enable);
2576}
2577
2578void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2579 int mtuSize = getInterfaceMtu(ifName);
2580 EXPECT_EQ(mtu, mtuSize);
2581}
2582
2583InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2584 const std::string& addr, int prefixLength,
2585 const std::vector<std::string>& flags) {
2586 InterfaceConfigurationParcel cfg;
2587 cfg.ifName = ifName;
2588 cfg.hwAddr = "";
2589 cfg.ipv4Addr = addr;
2590 cfg.prefixLength = prefixLength;
2591 cfg.flags = flags;
2592 return cfg;
2593}
2594
2595void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2596 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2597 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2598
2599 for (const auto& flag : expectedFlags) {
2600 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2601 interfaceCfg.flags.end());
2602 }
2603
2604 for (const auto& flag : unexpectedFlags) {
2605 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2606 interfaceCfg.flags.end());
2607 }
2608}
2609
2610} // namespace
2611
2612TEST_F(BinderTest, InterfaceList) {
2613 std::vector<std::string> interfaceListResult;
2614
2615 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2616 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2617 expectInterfaceList(interfaceListResult);
2618}
2619
2620TEST_F(BinderTest, InterfaceGetCfg) {
2621 InterfaceConfigurationParcel interfaceCfgResult;
2622
2623 // Add test physical network
2624 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2625 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2626
2627 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2628 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2629 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2630 expectTunFlags(interfaceCfgResult);
2631
2632 // Remove test physical network
2633 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2634}
2635
2636TEST_F(BinderTest, InterfaceSetCfg) {
2637 const std::string testAddr = "192.0.2.3";
2638 const int testPrefixLength = 24;
2639 std::vector<std::string> upFlags = {"up"};
2640 std::vector<std::string> downFlags = {"down"};
2641
2642 // Add test physical network
2643 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2644 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2645
2646 // Set tun interface down.
2647 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2648 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2649 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2650 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2651
2652 // Set tun interface up again.
2653 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2654 status = mNetd->interfaceSetCfg(interfaceCfg);
2655 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2656 status = mNetd->interfaceClearAddrs(sTun.name());
2657 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2658
2659 // Remove test physical network
2660 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2661}
2662
2663TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2664 // enable
2665 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2666 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2667 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2668
2669 // disable
2670 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2671 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2672 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2673}
2674
2675TEST_F(BinderTest, InterfaceClearAddr) {
2676 const std::string testAddr = "192.0.2.3";
2677 const int testPrefixLength = 24;
2678 std::vector<std::string> noFlags{};
2679
2680 // Add test physical network
2681 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2682 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2683
2684 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2685 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2686 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2687 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2688
2689 status = mNetd->interfaceClearAddrs(sTun.name());
2690 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2691 expectInterfaceNoAddr(sTun.name());
2692
2693 // Remove test physical network
2694 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2695}
2696
2697TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2698 // Add test physical network
2699 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2700 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2701
2702 // disable
2703 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2704 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2705 expectInterfaceEnableIPv6(sTun.name(), false);
2706
2707 // enable
2708 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2709 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2710 expectInterfaceEnableIPv6(sTun.name(), true);
2711
2712 // Remove test physical network
2713 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2714}
2715
2716TEST_F(BinderTest, InterfaceSetMtu) {
2717 const int testMtu = 1200;
2718
2719 // Add test physical network
2720 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2721 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2722
2723 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2724 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2725 expectInterfaceMtu(sTun.name(), testMtu);
2726
2727 // Remove test physical network
2728 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2729}
Luke Huang19b49c52018-10-22 12:12:05 +09002730
2731namespace {
2732
2733constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2734constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002735constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002736constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2737
Luke Huangae038f82018-11-05 11:17:31 +09002738int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002739 return listIptablesRuleByTable(binary, table, chainName).size();
2740}
2741
2742bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2743 const std::vector<std::string>& targetVec) {
2744 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2745 if (targetVec.size() != rules.size() - 2) {
2746 return false;
2747 }
2748
2749 /*
Luke Huangae038f82018-11-05 11:17:31 +09002750 * Check that the rules match. Note that this function matches substrings, not entire rules,
2751 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002752 * Skip first two lines since rules start from third line.
2753 * Chain chainName (x references)
2754 * pkts bytes target prot opt in out source destination
2755 * ...
2756 */
2757 int rIndex = 2;
2758 for (const auto& target : targetVec) {
2759 if (rules[rIndex].find(target) == std::string::npos) {
2760 return false;
2761 }
2762 rIndex++;
2763 }
2764 return true;
2765}
2766
2767void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2768 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2769 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2770 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002771 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002772 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2773 "DROP"};
2774
2775 // V4
2776 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2777 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002778 EXPECT_TRUE(
2779 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002780 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2781
Luke Huangae038f82018-11-05 11:17:31 +09002782 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002783 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2784
2785 // V6
2786 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002787 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2788 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002789
2790 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2791 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2792 extIf));
2793 }
2794}
2795
2796void expectNatDisable() {
2797 // It is the default DROP rule with tethering disable.
2798 // Chain tetherctrl_FORWARD (1 references)
2799 // pkts bytes target prot opt in out source destination
2800 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2801 std::vector<std::string> forwardV4Match = {"DROP"};
2802 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2803
2804 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002805 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2806 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002807
Luke Huangae038f82018-11-05 11:17:31 +09002808 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2809 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002810
2811 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2812}
2813
2814} // namespace
2815
2816TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002817 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2818 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2819 expectNatEnable(sTun.name(), sTun2.name());
2820
2821 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2822 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2823 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002824}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002825
2826namespace {
2827
2828using TripleInt = std::array<int, 3>;
2829
2830TripleInt readProcFileToTripleInt(const std::string& path) {
2831 std::string valueString;
2832 int min, def, max;
2833 EXPECT_TRUE(ReadFileToString(path, &valueString));
2834 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2835 return {min, def, max};
2836}
2837
2838void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2839 std::string testRmemValues =
2840 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2841 std::string testWmemValues =
2842 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2843 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2844
2845 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2846 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2847
2848 for (int i = 0; i < 3; i++) {
2849 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2850 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2851 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2852 }
2853}
2854
2855} // namespace
2856
2857TEST_F(BinderTest, TcpBufferSet) {
2858 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2859 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2860 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2861 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2862
2863 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2864 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2865}
Luke Huang528af602018-08-29 19:06:05 +08002866
Chenbo Feng48eaed32018-12-26 17:40:21 -08002867namespace {
2868
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002869void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Chenbo Feng48eaed32018-12-26 17:40:21 -08002870 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2871 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2872 for (int32_t uid : uids) {
2873 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2874 if (exist) {
2875 EXPECT_TRUE(isOk(permission));
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002876 EXPECT_EQ(INetd::NO_PERMISSIONS, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002877 } else {
2878 EXPECT_FALSE(isOk(permission));
2879 EXPECT_EQ(ENOENT, permission.status().code());
2880 }
2881 }
2882}
2883
2884} // namespace
2885
2886TEST_F(BinderTest, TestInternetPermission) {
2887 SKIP_IF_BPF_NOT_SUPPORTED;
2888
2889 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2890
2891 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002892 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002893 mNetd->trafficSetNetPermForUids(INetd::NO_PERMISSIONS, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002894 checkUidsInPermissionMap(appUids, true);
2895 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2896 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002897}
2898
Luke Huang528af602018-08-29 19:06:05 +08002899TEST_F(BinderTest, UnsolEvents) {
2900 auto testUnsolService = android::net::TestUnsolService::start();
2901 std::string oldTunName = sTun.name();
2902 std::string newTunName = "unsolTest";
2903 testUnsolService->tarVec.push_back(oldTunName);
2904 testUnsolService->tarVec.push_back(newTunName);
2905 auto& cv = testUnsolService->getCv();
2906 auto& cvMutex = testUnsolService->getCvMutex();
2907 binder::Status status = mNetd->registerUnsolicitedEventListener(
2908 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2909 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2910
2911 // TODO: Add test for below events
2912 // StrictCleartextDetected / InterfaceDnsServersAdded
2913 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2914
2915 {
2916 std::unique_lock lock(cvMutex);
2917
2918 // Re-init test Tun, and we expect that we will get some unsol events.
2919 // Use the test Tun device name to verify if we receive its unsol events.
2920 sTun.destroy();
2921 // Use predefined name
2922 sTun.init(newTunName);
2923
2924 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2925 }
2926
2927 // bit mask 1101101000
2928 // Test only covers below events currently
2929 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2930 InterfaceLinkStatusChanged | RouteChanged;
2931 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Bernie Innocentia5161a02019-01-30 22:40:53 +09002932}