blob: ad0dfefec1d02d876122d1e6ec34b32ba3b0bcdb [file] [log] [blame]
Lorenzo Colitti89faa342016-02-26 11:38:47 +09001/*
2 * Copyright 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * binder_test.cpp - unit tests for netd binder RPCs.
17 */
18
Robin Leeb8087362016-03-30 18:43:08 +010019#include <cerrno>
Luke Huang528af602018-08-29 19:06:05 +080020#include <chrono>
Robin Leeb8087362016-03-30 18:43:08 +010021#include <cinttypes>
Luke Huang528af602018-08-29 19:06:05 +080022#include <condition_variable>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090023#include <cstdint>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090024#include <cstdio>
25#include <cstdlib>
Luke Huang528af602018-08-29 19:06:05 +080026#include <mutex>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090027#include <set>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090028#include <vector>
29
Luke Huangf7782042018-08-08 13:13:04 +080030#include <dirent.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090031#include <fcntl.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090032#include <ifaddrs.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090033#include <linux/if.h>
34#include <linux/if_tun.h>
Benedict Wonga450e722018-05-07 10:29:02 -070035#include <net/if.h>
Luke Huangf7782042018-08-08 13:13:04 +080036#include <netdb.h>
37#include <netinet/in.h>
Ben Schwartze7601812017-04-28 16:38:29 -040038#include <openssl/base64.h>
Luke Huangf7782042018-08-08 13:13:04 +080039#include <sys/socket.h>
40#include <sys/types.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090041
Luke Huang531f5d32018-08-03 15:19:05 +080042#include <android-base/file.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090043#include <android-base/macros.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090044#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090045#include <android-base/strings.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080046#include <bpf/BpfMap.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070047#include <bpf/BpfUtils.h>
Robin Leeb8087362016-03-30 18:43:08 +010048#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090049#include <gtest/gtest.h>
50#include <logwrap/logwrap.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080051#include <netdbpf/bpf_shared.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090052#include <netutils/ifc.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090053
Nathan Harold21299f72018-03-16 20:13:03 -070054#include "InterfaceController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090055#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090056#include "Stopwatch.h"
Luke Huang528af602018-08-29 19:06:05 +080057#include "TestUnsolService.h"
Nathan Harold21299f72018-03-16 20:13:03 -070058#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090059#include "android/net/INetd.h"
60#include "binder/IServiceManager.h"
Nathan Harold21299f72018-03-16 20:13:03 -070061#include "netdutils/Syscalls.h"
Mike Yu5ae61542018-10-19 22:11:43 +080062#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090063
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090064#define IP_PATH "/system/bin/ip"
65#define IP6TABLES_PATH "/system/bin/ip6tables"
66#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090067#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080068#define RAW_TABLE "raw"
69#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080070#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090071#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090072
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090073namespace binder = android::binder;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090074
75using android::IBinder;
76using android::IServiceManager;
77using android::sp;
78using android::String16;
79using android::String8;
80using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080081using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090082using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090083using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080084using android::base::Trim;
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;
Robin Leeb8087362016-03-30 18:43:08 +010092
93static const char* IP_RULE_V4 = "-4";
94static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090095static const int TEST_NETID1 = 65501;
96static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -080097
98// Use maximum reserved appId for applications to avoid conflict with existing
99// uids.
100static const int TEST_UID1 = 99999;
101static const int TEST_UID2 = 99998;
102
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900103constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900104
Benedict Wongb2daefb2017-12-06 22:05:46 -0800105static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
106static const std::string ESP_ALLOW_RULE("esp");
107
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900108class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900109 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900110 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900111 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900112 sp<IBinder> binder = sm->getService(String16("netd"));
113 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900114 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900115 }
116 }
117
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900118 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900119 ASSERT_NE(nullptr, mNetd.get());
120 }
121
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900122 void TearDown() override {
123 mNetd->networkDestroy(TEST_NETID1);
124 mNetd->networkDestroy(TEST_NETID2);
125 }
126
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900127 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700128
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900129 // Static because setting up the tun interface takes about 40ms.
130 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900131 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900132 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900133 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900134 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900135 }
136
137 static void TearDownTestCase() {
138 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900139 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900140 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900141 }
142
143 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900144
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900145 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900146 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900147 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900148 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900149};
150
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900151TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900152TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900153
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900154class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900155 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700156 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900157 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900158 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900159 }
160
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900161 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900162 std::string mName;
163};
164
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900165TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900166 TimedOperation t("isAlive RPC");
167 bool isAlive = false;
168 mNetd->isAlive(&isAlive);
169 ASSERT_TRUE(isAlive);
170}
171
172static int randomUid() {
173 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
174}
175
Robin Leeb8087362016-03-30 18:43:08 +0100176static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900177 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900178 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
179 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900180 perror("popen");
181 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900182 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900183
184 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100185 size_t bufsize = 0;
186 ssize_t linelen = 0;
187 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900188 lines.push_back(std::string(line, linelen));
189 free(line);
190 line = nullptr;
191 }
192
193 pclose(f);
194 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900195}
196
Robin Leeb8087362016-03-30 18:43:08 +0100197static std::vector<std::string> listIpRules(const char *ipVersion) {
198 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
199 return runCommand(command);
200}
201
202static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900203 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100204 return runCommand(command);
205}
206
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900207static int iptablesRuleLineLength(const char *binary, const char *chainName) {
208 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900209}
210
Benedict Wongb2daefb2017-12-06 22:05:46 -0800211static bool iptablesRuleExists(const char *binary,
212 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900213 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800214 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900215 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800216 if(rule.find(expectedRule) != std::string::npos) {
217 return true;
218 }
219 }
220 return false;
221}
222
223static bool iptablesNoSocketAllowRuleExists(const char *chainName){
224 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
225 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
226}
227
228static bool iptablesEspAllowRuleExists(const char *chainName){
229 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
230 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
231}
232
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900233TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700234 SKIP_IF_BPF_SUPPORTED;
235
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900236 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
237 const int kNumUids = 500;
238 std::vector<int32_t> noUids(0);
239 std::vector<int32_t> uids(kNumUids);
240 for (int i = 0; i < kNumUids; i++) {
241 uids[i] = randomUid();
242 }
243
244 bool ret;
245 {
246 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900247 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900248 }
249 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800250 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
251 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
252 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
253 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900254 {
255 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900256 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900257 }
258 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900259 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
260 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900261
262 {
263 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900264 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900265 }
266 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900267 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
268 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800269 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
270 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900271
272 {
273 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900274 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900275 }
276 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900277 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
278 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900279
280 // Check that the call fails if iptables returns an error.
281 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900282 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900283 EXPECT_EQ(false, ret);
284}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900285
Benedict Wong319f17e2018-05-15 17:06:44 -0700286TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700287 const struct TestData {
288 const std::string family;
289 const std::string deviceName;
290 const std::string localAddress;
291 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800292 int32_t iKey;
293 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700294 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800295 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700296 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
297 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
298 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800299 };
300
Sehee Park8659b8d2018-11-16 10:53:16 +0900301 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700302 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800303
304 binder::Status status;
305
Benedict Wong319f17e2018-05-15 17:06:44 -0700306 // Create Tunnel Interface.
307 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700308 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800309 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
310
Benedict Wonga450e722018-05-07 10:29:02 -0700311 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900312 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700313
Benedict Wong319f17e2018-05-15 17:06:44 -0700314 // Update Tunnel Interface.
315 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700316 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800317 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
318
Benedict Wong319f17e2018-05-15 17:06:44 -0700319 // Remove Tunnel Interface.
320 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800321 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700322
323 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900324 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800325 }
326}
327
Benedict Wong1cb73df2018-12-03 00:54:14 -0800328TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
329 android::base::unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
330 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
331
332 int sockOptVal = UDP_ENCAP_ESPINUDP;
333 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
334
335 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
336 EXPECT_TRUE(res.isOk());
337
338 struct stat info;
339 EXPECT_EQ(0, fstat(sockFd.get(), &info));
340 EXPECT_EQ(1001, (int) info.st_uid);
341}
342
Nathan Harold2deff322018-05-10 14:03:48 -0700343// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
344// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
345#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900346
347using android::net::XfrmController;
348
Benedict Wonga04ffa72018-05-09 21:42:42 -0700349static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
350 static_cast<int>(android::net::XfrmDirection::OUT)};
351static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
352
Nathan Harold21299f72018-03-16 20:13:03 -0700353#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
354 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900355bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900356 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700357 SCOPED_TRACE(status);
358 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
359
360 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700361 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700362 SCOPED_TRACE(status);
363 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
364
365 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700366 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
367 0xD00D, 0xE00D, false)
368 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700369}
370
Benedict Wonga04ffa72018-05-09 21:42:42 -0700371TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900372 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700373
374 // Repeat to ensure cleanup and recreation works correctly
375 for (int i = 0; i < 2; i++) {
376 for (int direction : XFRM_DIRECTIONS) {
377 for (int addrFamily : ADDRESS_FAMILIES) {
378 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700379 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700380 EXPECT_TRUE(status.isOk())
381 << " family: " << addrFamily << " direction: " << direction;
382 }
383 }
384
385 // Cleanup
386 for (int direction : XFRM_DIRECTIONS) {
387 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700388 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700389 EXPECT_TRUE(status.isOk());
390 }
391 }
392 }
393}
394
395TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
396 binder::Status status;
397
398 // Repeat to ensure cleanup and recreation works correctly
399 for (int i = 0; i < 2; i++) {
400 for (int direction : XFRM_DIRECTIONS) {
401 for (int addrFamily : ADDRESS_FAMILIES) {
402 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700403 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700404 EXPECT_TRUE(status.isOk())
405 << " family: " << addrFamily << " direction: " << direction;
406 }
407 }
408
409 // Cleanup
410 for (int direction : XFRM_DIRECTIONS) {
411 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700412 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700413 EXPECT_TRUE(status.isOk());
414 }
415 }
416 }
417}
418
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900419TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900420 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700421 status = XfrmController::Init();
422 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700423
424 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
425 // feature.
426 if (status.code() == EOPNOTSUPP) return;
427
Nathan Harold21299f72018-03-16 20:13:03 -0700428 ASSERT_TRUE(status.ok());
429
430 int32_t spi = 0;
431
432 ASSERT_TRUE(allocateIpSecResources(true, &spi));
433 ASSERT_TRUE(allocateIpSecResources(false, &spi));
434
435 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700436 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700437 ASSERT_TRUE(allocateIpSecResources(true, &spi));
438
439 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700440 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700441 SCOPED_TRACE(status);
442 ASSERT_TRUE(status.ok());
443
Benedict Wonga450e722018-05-07 10:29:02 -0700444 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700445 SCOPED_TRACE(status);
446 ASSERT_TRUE(status.ok());
447
448 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700449 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700450}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900451
452#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700453
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900454static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900455 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900456
457 // Output looks like this:
458 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900459 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900460 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900461 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900462 //
463 // or:
464 //
465 // Chain bw_data_saver (1 references)
466 // target prot opt source destination
467 // ... possibly connectivity critical packet rules here ...
468 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900469
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900470 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900471
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900472 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
473 // Data saver disabled.
474 return 0;
475 }
476
477 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
478
479 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
480 // Data saver enabled.
481 return 1;
482 }
483
484 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900485}
486
487bool enableDataSaver(sp<INetd>& netd, bool enable) {
488 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
489 bool ret;
490 netd->bandwidthEnableDataSaver(enable, &ret);
491 return ret;
492}
493
494int getDataSaverState() {
495 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
496 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
497 EXPECT_EQ(enabled4, enabled6);
498 EXPECT_NE(-1, enabled4);
499 EXPECT_NE(-1, enabled6);
500 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
501 return -1;
502 }
503 return enabled6;
504}
505
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900506TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900507 const int wasEnabled = getDataSaverState();
508 ASSERT_NE(-1, wasEnabled);
509
510 if (wasEnabled) {
511 ASSERT_TRUE(enableDataSaver(mNetd, false));
512 EXPECT_EQ(0, getDataSaverState());
513 }
514
515 ASSERT_TRUE(enableDataSaver(mNetd, false));
516 EXPECT_EQ(0, getDataSaverState());
517
518 ASSERT_TRUE(enableDataSaver(mNetd, true));
519 EXPECT_EQ(1, getDataSaverState());
520
521 ASSERT_TRUE(enableDataSaver(mNetd, true));
522 EXPECT_EQ(1, getDataSaverState());
523
524 if (!wasEnabled) {
525 ASSERT_TRUE(enableDataSaver(mNetd, false));
526 EXPECT_EQ(0, getDataSaverState());
527 }
528}
Robin Leeb8087362016-03-30 18:43:08 +0100529
Luke Huang94658ac2018-10-18 19:35:12 +0900530static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
531 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100532 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100533 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100534 std::vector<std::string> rules = listIpRules(ipVersion);
535
536 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900537 std::string suffix =
538 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900539 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800540 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100541 return true;
542 }
543 }
544 return false;
545}
546
Luke Huang94658ac2018-10-18 19:35:12 +0900547static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
548 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100549 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
550 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
551 EXPECT_EQ(existsIp4, existsIp6);
552 return existsIp4;
553}
554
Luke Huang94658ac2018-10-18 19:35:12 +0900555namespace {
556
557UidRangeParcel makeUidRangeParcel(int start, int stop) {
558 UidRangeParcel res;
559 res.start = start;
560 res.stop = stop;
561
562 return res;
563}
564
565} // namespace
566
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900567TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800568 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
569 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
570 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900571 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
572 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900573
574 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
575 EXPECT_EQ(EBUSY,
576 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
577
578 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
579 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
580 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800581 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900582}
583
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900584TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900585 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
586
cken67cd14c2018-12-05 17:26:59 +0900587 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
588 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900589 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
590
Luke Huang94658ac2018-10-18 19:35:12 +0900591 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
592 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
593 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900594 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
595
596 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
597
598 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
599 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
600 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
601 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
602
603 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
604 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
605 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
606 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
607
608 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
609}
610
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900611TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100612 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100613
Luke Huang94658ac2018-10-18 19:35:12 +0900614 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
615 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100616
617 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
618 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
619
620 // Create two valid rules.
621 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
622 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
623 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
624 for (auto const& range : uidRanges) {
625 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
626 }
627
628 // Remove the rules.
629 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
630 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
631 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
632 for (auto const& range : uidRanges) {
633 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
634 }
635
636 // Fail to remove the rules a second time after they are already deleted.
637 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
638 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
639 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
640
641 // All rules should be the same as before.
642 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
643 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
644}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900645
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900646// Create a socket pair that isLoopbackSocket won't think is local.
647void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900648 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900649 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900650 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
651
652 socklen_t addrlen = sizeof(server6);
653 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
654 ASSERT_EQ(0, listen(*serverSocket, 10));
655
Bernie Innocentif6918262018-06-11 17:37:35 +0900656 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900657 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900658 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900659 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
660 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
661
Bernie Innocentif6918262018-06-11 17:37:35 +0900662 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900663 ASSERT_NE(-1, *acceptedSocket);
664
665 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
666}
667
668void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
669 char buf[4096];
670 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
671 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
672 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
673}
674
675void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
676 // Check that the client socket was closed with ECONNABORTED.
677 int ret = write(clientSocket, "foo", sizeof("foo"));
678 int err = errno;
679 EXPECT_EQ(-1, ret);
680 EXPECT_EQ(ECONNABORTED, err);
681
682 // Check that it sent a RST to the server.
683 ret = write(acceptedSocket, "foo", sizeof("foo"));
684 err = errno;
685 EXPECT_EQ(-1, ret);
686 EXPECT_EQ(ECONNRESET, err);
687}
688
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900689TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900690 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900691 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900692
693 // Pick a random UID in the system UID range.
694 constexpr int baseUid = AID_APP - 2000;
695 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
696 int uid = baseUid + 500 + arc4random_uniform(1000);
697 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
698
699 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900700 std::vector<UidRangeParcel> uidRanges = {
701 makeUidRangeParcel(baseUid + 42, baseUid + 449),
702 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
703 makeUidRangeParcel(baseUid + 498, uid - 1),
704 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900705 };
706 // A skip list that doesn't contain UID.
707 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
708
709 // Close sockets. Our test socket should be intact.
710 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
711 checkSocketpairOpen(clientSocket, acceptedSocket);
712
713 // UID ranges that do contain uid.
714 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900715 makeUidRangeParcel(baseUid + 42, baseUid + 449),
716 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
717 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900718 };
719 // Add uid to the skip list.
720 skipUids.push_back(uid);
721
722 // Close sockets. Our test socket should still be intact because it's in the skip list.
723 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
724 checkSocketpairOpen(clientSocket, acceptedSocket);
725
726 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
727 skipUids.resize(skipUids.size() - 1);
728 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
729 checkSocketpairClosed(clientSocket, acceptedSocket);
730
731 close(clientSocket);
732 close(serverSocket);
733 close(acceptedSocket);
734}
Erik Klinecc4f2732016-08-03 11:24:27 +0900735
736namespace {
737
738int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
739 if (buf == nullptr) return -1;
740
741 int prefixLength = 0;
742 bool endOfContiguousBits = false;
743 for (unsigned int i = 0; i < buflen; i++) {
744 const uint8_t value = buf[i];
745
746 // Bad bit sequence: check for a contiguous set of bits from the high
747 // end by verifying that the inverted value + 1 is a power of 2
748 // (power of 2 iff. (v & (v - 1)) == 0).
749 const uint8_t inverse = ~value + 1;
750 if ((inverse & (inverse - 1)) != 0) return -1;
751
752 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
753
754 // Bogus netmask.
755 if (endOfContiguousBits && value != 0) return -1;
756
757 if (value != 0xff) endOfContiguousBits = true;
758 }
759
760 return prefixLength;
761}
762
763template<typename T>
764int netmaskToPrefixLength(const T *p) {
765 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
766}
767
768
769static bool interfaceHasAddress(
770 const std::string &ifname, const char *addrString, int prefixLength) {
771 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900772
773 const struct addrinfo hints = {
774 .ai_flags = AI_NUMERICHOST,
775 .ai_family = AF_UNSPEC,
776 .ai_socktype = SOCK_DGRAM,
777 };
778 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
779 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
780 return false;
781 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900782 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900783
784 struct ifaddrs *ifaddrsList = nullptr;
785 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
786
787 if (getifaddrs(&ifaddrsList) != 0) {
788 return false;
789 }
790
791 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
792 if (std::string(addr->ifa_name) != ifname ||
793 addr->ifa_addr == nullptr ||
794 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
795 continue;
796 }
797
798 switch (addr->ifa_addr->sa_family) {
799 case AF_INET: {
800 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
801 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
802 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
803 continue;
804 }
805
806 if (prefixLength < 0) return true; // not checking prefix lengths
807
808 if (addr->ifa_netmask == nullptr) return false;
809 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
810 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
811 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
812 }
813 case AF_INET6: {
814 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
815 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
816 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
817 continue;
818 }
819
820 if (prefixLength < 0) return true; // not checking prefix lengths
821
822 if (addr->ifa_netmask == nullptr) return false;
823 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
824 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
825 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
826 }
827 default:
828 // Cannot happen because we have already screened for matching
829 // address families at the top of each iteration.
830 continue;
831 }
832 }
833
834 return false;
835}
836
837} // namespace
838
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900839TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900840 static const struct TestData {
841 const char *addrString;
842 const int prefixLength;
843 const bool expectSuccess;
844 } kTestData[] = {
845 { "192.0.2.1", 24, true },
846 { "192.0.2.2", 25, true },
847 { "192.0.2.3", 32, true },
848 { "192.0.2.4", 33, false },
849 { "192.not.an.ip", 24, false },
850 { "2001:db8::1", 64, true },
851 { "2001:db8::2", 65, true },
852 { "2001:db8::3", 128, true },
853 { "2001:db8::4", 129, false },
854 { "foo:bar::bad", 64, false },
855 };
856
Sehee Park8659b8d2018-11-16 10:53:16 +0900857 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900858 const auto &td = kTestData[i];
859
860 // [1.a] Add the address.
861 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900862 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900863 if (td.expectSuccess) {
864 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
865 } else {
866 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
867 ASSERT_NE(0, status.serviceSpecificErrorCode());
868 }
869
870 // [1.b] Verify the addition meets the expectation.
871 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900872 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900873 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900874 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900875 }
876
877 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900878 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900879 if (td.expectSuccess) {
880 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
881 } else {
882 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
883 ASSERT_NE(0, status.serviceSpecificErrorCode());
884 }
885
886 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900887 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900888 }
889}
Erik Kline55b06f82016-07-04 09:57:18 +0900890
Erik Kline38e51f12018-09-06 20:14:44 +0900891TEST_F(BinderTest, GetProcSysNet) {
892 const char LOOPBACK[] = "lo";
893 static const struct {
894 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900895 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900896 const char* ifname;
897 const char* parameter;
898 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900899 const int expectedReturnCode;
900 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900901 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
902 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
903 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
904 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
905 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
906 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
907 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900908 };
909
Sehee Park8659b8d2018-11-16 10:53:16 +0900910 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900911 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900912
Erik Kline38e51f12018-09-06 20:14:44 +0900913 std::string value;
914 const binder::Status status =
915 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
916
917 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900918 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900919 EXPECT_EQ(0, status.exceptionCode());
920 EXPECT_EQ(0, status.serviceSpecificErrorCode());
921 EXPECT_EQ(td.expectedValue, value);
922 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900923 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900924 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
925 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
926 }
927 }
928}
929
930TEST_F(BinderTest, SetProcSysNet) {
931 static const struct {
932 const int ipversion;
933 const int which;
934 const char* ifname;
935 const char* parameter;
936 const char* value;
937 const int expectedReturnCode;
938 } kTestData[] = {
939 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
940 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
941 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
942 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
943 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
944 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
945 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
946 };
947
Sehee Park8659b8d2018-11-16 10:53:16 +0900948 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900949 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900950 const binder::Status status =
951 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900952
953 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900954 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900955 EXPECT_EQ(0, status.exceptionCode());
956 EXPECT_EQ(0, status.serviceSpecificErrorCode());
957 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900958 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900959 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
960 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
961 }
962 }
963}
Ben Schwartze7601812017-04-28 16:38:29 -0400964
Erik Kline38e51f12018-09-06 20:14:44 +0900965TEST_F(BinderTest, GetSetProcSysNet) {
966 const int ipversion = INetd::IPV6;
967 const int category = INetd::NEIGH;
968 const std::string& tun = sTun.name();
969 const std::string parameter("ucast_solicit");
970
971 std::string value{};
972 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
973 EXPECT_FALSE(value.empty());
974 const int ival = std::stoi(value);
975 EXPECT_GT(ival, 0);
976 // Try doubling the parameter value (always best!).
977 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
978 .isOk());
979 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
980 EXPECT_EQ(2 * ival, std::stoi(value));
981 // Try resetting the parameter.
982 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
983 .isOk());
984 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
985 EXPECT_EQ(ival, std::stoi(value));
986}
987
Ben Schwartze7601812017-04-28 16:38:29 -0400988static std::string base64Encode(const std::vector<uint8_t>& input) {
989 size_t out_len;
990 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
991 // out_len includes the trailing NULL.
992 uint8_t output_bytes[out_len];
993 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
994 return std::string(reinterpret_cast<char*>(output_bytes));
995}
996
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900997TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900998 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400999 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001000 std::vector<uint8_t> short_fp(1);
1001 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
1002 std::vector<std::string> test_domains;
1003 std::vector<int> test_params = { 300, 25, 8, 8 };
1004 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -04001005 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001006 const std::vector<std::string> servers;
1007 const std::string tlsName;
1008 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -04001009 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +09001010 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001011 { {"192.0.2.1"}, "", {}, 0 },
1012 { {"2001:db8::2"}, "host.name", {}, 0 },
1013 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
1014 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +09001015 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001016 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +09001017 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001018 { {"2001:dg8::6"}, "", {}, EINVAL },
1019 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
1020 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
1021 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
1022 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -04001023 };
1024
Sehee Park8659b8d2018-11-16 10:53:16 +09001025 for (size_t i = 0; i < std::size(kTlsTestData); i++) {
Erik Klinea1476fb2018-03-04 21:01:56 +09001026 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -04001027
1028 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001029 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -04001030 fingerprints.push_back(base64Encode(fingerprint));
1031 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001032 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001033 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
1034 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -04001035
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001036 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +09001037 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Ben Schwartze7601812017-04-28 16:38:29 -04001038 SCOPED_TRACE(status.toString8());
1039 EXPECT_EQ(0, status.exceptionCode());
1040 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +09001041 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Ben Schwartze7601812017-04-28 16:38:29 -04001042 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001043 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -04001044 }
Ben Schwartze7601812017-04-28 16:38:29 -04001045 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001046 // Ensure TLS is disabled before the start of the next test.
1047 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001048 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1049 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001050}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001051
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001052namespace {
1053
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001054void expectNoTestCounterRules() {
1055 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1056 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1057 std::string allRules = Join(runCommand(command), "\n");
1058 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1059 }
1060}
1061
Bernie Innocentif6918262018-06-11 17:37:35 +09001062void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1063 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001064 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1065 path, if1.c_str(), if2.c_str(), pkt, byte));
1066}
1067
Bernie Innocentif6918262018-06-11 17:37:35 +09001068void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001069 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1070 path, if1.c_str(), if2.c_str()));
1071 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1072 path, if2.c_str(), if1.c_str()));
1073}
1074
Luke Huangcaebcbb2018-09-27 20:37:14 +08001075std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1076 const std::string& iface) {
1077 for (auto& stats : statsVec) {
1078 if (stats.iface == iface) {
1079 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1080 }
1081 }
1082 return {};
1083}
1084
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001085} // namespace
1086
1087TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001088 expectNoTestCounterRules();
1089
1090 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1091 // disabling tethering. We don't check the return value because these commands will fail if
1092 // tethering is already enabled.
1093 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1094 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1095
1096 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1097 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1098 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1099 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1100 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1101
1102 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1103 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1104 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1105 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1106 // RX is from external to internal, and TX is from internal to external.
1107 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1108 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1109
1110 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1111 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1112
1113 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1114 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1115
1116 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1117 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1118 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1119
Luke Huangcaebcbb2018-09-27 20:37:14 +08001120 std::vector<TetherStatsParcel> statsVec;
1121 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001122 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1123
Luke Huangcaebcbb2018-09-27 20:37:14 +08001124 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001125
Luke Huangcaebcbb2018-09-27 20:37:14 +08001126 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001127
1128 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1129 delTetherCounterValues(path, intIface1, extIface1);
1130 delTetherCounterValues(path, intIface2, extIface2);
1131 if (path == IP6TABLES_PATH) {
1132 delTetherCounterValues(path, intIface3, extIface2);
1133 }
1134 }
1135
1136 expectNoTestCounterRules();
1137}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001138
Luke Huang0051a622018-07-23 20:30:16 +08001139namespace {
1140
Luke Huanga5211072018-08-01 23:36:29 +08001141constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1142constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001143
1144static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1145 const char* chainName) {
1146 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1147 return runCommand(command);
1148}
1149
Luke Huang19b49c52018-10-22 12:12:05 +09001150// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001151bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001152 const std::string& expectedInterface,
1153 const std::string& expectedRule, const char* table) {
1154 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1155 for (const auto& rule : rules) {
1156 if (rule.find(expectedInterface) != std::string::npos) {
1157 if (rule.find(expectedRule) != std::string::npos) {
1158 return true;
1159 }
1160 }
1161 }
1162 return false;
1163}
1164
1165void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001166 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001167 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001168 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001169 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001170 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1171 IdletimerRule, RAW_TABLE));
1172 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001173 ifname, IdletimerRule, MANGLE_TABLE));
1174 }
1175}
1176
1177void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001178 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001179 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001180 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001181 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001182 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1183 IdletimerRule, RAW_TABLE));
1184 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001185 ifname, IdletimerRule, MANGLE_TABLE));
1186 }
1187}
1188
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001189} // namespace
1190
1191TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001192 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1193 // rule in the table. Because we only check the result after calling remove function. We might
1194 // check the actual rule which is removed by our function (maybe compare the results between
1195 // calling function before and after)
1196 binder::Status status;
1197 const struct TestData {
1198 const std::string ifname;
1199 int32_t timeout;
1200 const std::string classLabel;
1201 } idleTestData[] = {
1202 {"wlan0", 1234, "happyday"},
1203 {"rmnet_data0", 4567, "friday"},
1204 };
1205 for (const auto& td : idleTestData) {
1206 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1207 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1208 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1209
1210 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1211 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1212 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1213 }
1214}
1215
Luke Huanga67dd562018-07-17 19:58:25 +08001216namespace {
1217
1218constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1219constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1220
1221void expectStrictSetUidAccept(const int uid) {
1222 std::string uidRule = StringPrintf("owner UID match %u", uid);
1223 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1224 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001225 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1226 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001227 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1228 }
1229}
1230
1231void expectStrictSetUidLog(const int uid) {
1232 static const char logRule[] = "st_penalty_log all";
1233 std::string uidRule = StringPrintf("owner UID match %u", uid);
1234 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1235 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001236 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1237 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001238 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1239 }
1240}
1241
1242void expectStrictSetUidReject(const int uid) {
1243 static const char rejectRule[] = "st_penalty_reject all";
1244 std::string uidRule = StringPrintf("owner UID match %u", uid);
1245 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1246 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001247 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1248 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001249 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1250 }
1251}
1252
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001253} // namespace
1254
1255TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001256 binder::Status status;
1257 int32_t uid = randomUid();
1258
1259 // setUidCleartextPenalty Policy:Log with randomUid
1260 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1261 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1262 expectStrictSetUidLog(uid);
1263
1264 // setUidCleartextPenalty Policy:Accept with randomUid
1265 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1266 expectStrictSetUidAccept(uid);
1267
1268 // setUidCleartextPenalty Policy:Reject with randomUid
1269 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1270 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1271 expectStrictSetUidReject(uid);
1272
1273 // setUidCleartextPenalty Policy:Accept with randomUid
1274 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1275 expectStrictSetUidAccept(uid);
1276
1277 // test wrong policy
1278 int32_t wrongPolicy = -123;
1279 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1280 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1281}
1282
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001283namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001284
Luke Huangd1675922019-03-11 17:29:27 +08001285std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001286 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001287 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001288 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1289 // ...
1290 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1291
Luke Huangd1675922019-03-11 17:29:27 +08001292 // (dnsmasq)
1293 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1294
1295 if (maxTries == 0) return {};
1296
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001297 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001298 std::vector<std::string> result;
1299 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001300 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001301 if (result.size() || ++run > maxTries) {
1302 break;
1303 }
1304
Luke Huang728cf4c2019-03-14 19:43:02 +08001305 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001306 }
1307 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001308}
1309
Luke Huangd1675922019-03-11 17:29:27 +08001310void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001311 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001312}
1313
Luke Huang728cf4c2019-03-14 19:43:02 +08001314void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001315 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001316}
1317
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001318} // namespace
1319
1320TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001321 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001322
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001323 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1324 std::string clatAddress;
1325 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001326
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001327 // Can't start clatd on an interface that's not part of any network...
1328 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1329 EXPECT_FALSE(status.isOk());
1330 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1331
1332 // ... so create a test physical network and add our tun to it.
1333 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1334 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1335
1336 // Prefix must be 96 bits long.
1337 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1338 EXPECT_FALSE(status.isOk());
1339 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1340
1341 // Can't start clatd unless there's a default route...
1342 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1343 EXPECT_FALSE(status.isOk());
1344 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1345
1346 // so add a default route.
1347 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1348
1349 // Can't start clatd unless there's a global address...
1350 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1351 EXPECT_FALSE(status.isOk());
1352 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1353
1354 // ... so add a global address.
1355 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001356 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001357
1358 // Now expect clatd to start successfully.
1359 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1360 EXPECT_TRUE(status.isOk());
1361 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1362
1363 // Starting it again returns EBUSY.
1364 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1365 EXPECT_FALSE(status.isOk());
1366 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1367
Luke Huangd1675922019-03-11 17:29:27 +08001368 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001369
1370 // Expect clatd to stop successfully.
1371 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001372 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001373 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001374
1375 // Stopping a clatd that doesn't exist returns ENODEV.
1376 status = mNetd->clatdStop(sTun.name());
1377 EXPECT_FALSE(status.isOk());
1378 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001379 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001380
1381 // Clean up.
1382 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1383 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1384 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001385}
Luke Huang457d4702018-08-16 15:39:15 +08001386
1387namespace {
1388
1389bool getIpfwdV4Enable() {
1390 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1391 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1392 EXPECT_TRUE(!result.empty());
1393 int v4Enable = std::stoi(result[0]);
1394 return v4Enable;
1395}
1396
1397bool getIpfwdV6Enable() {
1398 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1399 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1400 EXPECT_TRUE(!result.empty());
1401 int v6Enable = std::stoi(result[0]);
1402 return v6Enable;
1403}
1404
1405void expectIpfwdEnable(bool enable) {
1406 int enableIPv4 = getIpfwdV4Enable();
1407 int enableIPv6 = getIpfwdV6Enable();
1408 EXPECT_EQ(enable, enableIPv4);
1409 EXPECT_EQ(enable, enableIPv6);
1410}
1411
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001412bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001413 std::vector<std::string> rules = listIpRules(ipVersion);
1414 for (const auto& rule : rules) {
1415 if (rule.find(ipfwdRule) != std::string::npos) {
1416 return true;
1417 }
1418 }
1419 return false;
1420}
1421
1422void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1423 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1424
1425 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1426 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1427 }
1428}
1429
1430void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1431 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1432
1433 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1434 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1435 }
1436}
1437
1438} // namespace
1439
1440TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001441 // Get ipfwd requester list from Netd
1442 std::vector<std::string> requesterList;
1443 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001444 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001445
1446 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001447 if (requesterList.size() == 0) {
1448 // No requester in Netd, ipfwd should be disabled
1449 // So add one test requester and verify
1450 status = mNetd->ipfwdEnableForwarding("TestRequester");
1451 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001452
Luke Huang728cf4c2019-03-14 19:43:02 +08001453 expectIpfwdEnable(true);
1454 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1455 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1456 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001457
Luke Huang728cf4c2019-03-14 19:43:02 +08001458 // Remove test one, verify again
1459 status = mNetd->ipfwdDisableForwarding("TestRequester");
1460 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1461
1462 expectIpfwdEnable(false);
1463 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1464 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1465 EXPECT_FALSE(ipfwdEnabled);
1466 } else {
1467 // Disable all requesters
1468 for (const auto& requester : requesterList) {
1469 status = mNetd->ipfwdDisableForwarding(requester);
1470 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1471 }
1472
1473 // After disable all requester, ipfwd should be disabled
1474 expectIpfwdEnable(false);
1475 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1476 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1477 EXPECT_FALSE(ipfwdEnabled);
1478
1479 // Enable them back
1480 for (const auto& requester : requesterList) {
1481 status = mNetd->ipfwdEnableForwarding(requester);
1482 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1483 }
1484
1485 // ipfwd should be enabled
1486 expectIpfwdEnable(true);
1487 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1488 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1489 EXPECT_TRUE(ipfwdEnabled);
1490 }
Luke Huang457d4702018-08-16 15:39:15 +08001491}
1492
1493TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001494 // Add test physical network
1495 EXPECT_TRUE(
1496 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1497 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1498 EXPECT_TRUE(
1499 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1500 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001501
Luke Huangd1827b82019-02-15 15:03:27 +08001502 binder::Status status =
1503 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1504 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1505 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001506
Luke Huangd1827b82019-02-15 15:03:27 +08001507 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1508 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1509 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001510}
Luke Huang531f5d32018-08-03 15:19:05 +08001511
1512namespace {
1513
1514constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1515constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1516constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1517constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1518constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001519constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001520
Luke Huang19b49c52018-10-22 12:12:05 +09001521// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1522// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001523bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1524 const char* chainName, const std::string& expectedTargetA,
1525 const std::string& expectedTargetB) {
1526 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1527 int matchCount = 0;
1528
1529 for (const auto& rule : rules) {
1530 if (rule.find(expectedTargetA) != std::string::npos) {
1531 if (rule.find(expectedTargetB) != std::string::npos) {
1532 matchCount++;
1533 }
1534 }
1535 }
1536 return matchCount == expectedCount;
1537}
1538
1539void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1540 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1541 std::string result = "";
1542
1543 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001544 // Quota value might be decreased while matching packets
1545 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001546}
1547
1548void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1549 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1550 std::string quotaRule = StringPrintf("quota %s", ifname);
1551
1552 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1553 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1554 BANDWIDTH_COSTLY_IF));
1555 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1556 BANDWIDTH_COSTLY_IF));
1557 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1558 BANDWIDTH_COSTLY_IF));
1559 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1560 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1561 }
1562 expectXtQuotaValueEqual(ifname, quotaBytes);
1563}
1564
1565void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1566 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1567 std::string quotaRule = StringPrintf("quota %s", ifname);
1568
1569 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1570 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1571 BANDWIDTH_COSTLY_IF));
1572 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1573 BANDWIDTH_COSTLY_IF));
1574 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1575 BANDWIDTH_COSTLY_IF));
1576 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1577 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1578 }
1579}
1580
1581void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1582 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1583 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1584 std::string alertName = StringPrintf("%sAlert", ifname);
1585
1586 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1587 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1588 }
1589 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1590}
1591
1592void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1593 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1594 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1595
1596 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1597 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1598 }
1599}
1600
1601void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1602 static const char globalAlertRule[] = "quota globalAlert";
1603 static const char globalAlertName[] = "globalAlert";
1604
1605 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001606 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001607 }
1608 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1609}
1610
1611void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1612 std::string uidRule = StringPrintf("owner UID match %u", uid);
1613
1614 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1615 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1616 }
1617}
1618
1619void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1620 std::string uidRule = StringPrintf("owner UID match %u", uid);
1621
1622 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1623 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1624 }
1625}
1626
1627} // namespace
1628
1629TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1630 long testQuotaBytes = 5550;
1631
1632 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001633 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001634 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1635
1636 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1637 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1638 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1639
1640 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1641 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1642 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1643
1644 // Remove test physical network
1645 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1646}
1647
1648TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1649 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001650 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001651 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001652 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001653 // Need to have a prior interface quota set to set an alert
1654 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1655 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1656 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1657 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1658
1659 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1660 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1661 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1662
1663 // Remove interface quota
1664 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1665 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1666 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1667
1668 // Remove test physical network
1669 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1670}
1671
1672TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1673 long testAlertBytes = 2097149;
1674
1675 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1676 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1677 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1678
1679 testAlertBytes = 2097152;
1680 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1681 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1682 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1683}
1684
1685TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1686 SKIP_IF_BPF_SUPPORTED;
1687
1688 int32_t uid = randomUid();
1689 static const char targetReject[] = "REJECT";
1690 static const char targetReturn[] = "RETURN";
1691
1692 // add NaughtyApp
1693 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1694 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1695 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1696
1697 // remove NaughtyApp
1698 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1699 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1700 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1701
1702 // add NiceApp
1703 status = mNetd->bandwidthAddNiceApp(uid);
1704 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1705 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1706
1707 // remove NiceApp
1708 status = mNetd->bandwidthRemoveNiceApp(uid);
1709 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1710 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1711}
Luke Huangb5733d72018-08-21 17:17:19 +08001712
1713namespace {
1714
Luke Huangb670d162018-08-23 20:01:13 +08001715std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1716 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1717 return runCommand(command);
1718}
1719
Luke Huangc3252cc2018-10-16 15:43:23 +08001720bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001721 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1722 for (const auto& route : routes) {
1723 if (route.find(ipRoute) != std::string::npos) {
1724 return true;
1725 }
1726 }
1727 return false;
1728}
1729
Luke Huangc3252cc2018-10-16 15:43:23 +08001730std::string ipRouteString(const std::string& ifName, const std::string& dst,
1731 const std::string& nextHop) {
1732 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1733
1734 if (!nextHop.empty()) {
1735 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001736 }
1737
Luke Huangc3252cc2018-10-16 15:43:23 +08001738 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001739}
1740
Luke Huangc3252cc2018-10-16 15:43:23 +08001741void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1742 const std::string& dst, const std::string& nextHop,
1743 const char* table) {
1744 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1745}
1746
1747void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001748 const std::string& dst, const std::string& nextHop,
1749 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001750 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001751}
1752
1753bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1754 std::vector<std::string> rules = listIpRules(ipVersion);
1755 for (const auto& rule : rules) {
1756 if (rule.find(ipRule) != std::string::npos) {
1757 return true;
1758 }
1759 }
1760 return false;
1761}
1762
1763void expectNetworkDefaultIpRuleExists(const char* ifName) {
1764 std::string networkDefaultRule =
1765 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1766
1767 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1768 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1769 }
1770}
1771
1772void expectNetworkDefaultIpRuleDoesNotExist() {
1773 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1774
1775 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1776 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1777 }
1778}
1779
1780void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1781 std::string networkPermissionRule = "";
1782 switch (permission) {
1783 case INetd::PERMISSION_NONE:
1784 networkPermissionRule = StringPrintf(
1785 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1786 break;
1787 case INetd::PERMISSION_NETWORK:
1788 networkPermissionRule = StringPrintf(
1789 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1790 break;
1791 case INetd::PERMISSION_SYSTEM:
1792 networkPermissionRule = StringPrintf(
1793 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1794 break;
1795 }
1796
1797 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1798 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1799 }
1800}
1801
1802// TODO: It is a duplicate function, need to remove it
1803bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1804 const std::string& expectedInterface,
1805 const std::string& expectedRule,
1806 const char* table) {
1807 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1808 for (const auto& rule : rules) {
1809 if (rule.find(expectedInterface) != std::string::npos) {
1810 if (rule.find(expectedRule) != std::string::npos) {
1811 return true;
1812 }
1813 }
1814 }
1815 return false;
1816}
1817
1818void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1819 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1820 std::string networkIncomingPacketMarkRule = "";
1821 switch (permission) {
1822 case INetd::PERMISSION_NONE:
1823 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1824 break;
1825 case INetd::PERMISSION_NETWORK:
1826 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1827 break;
1828 case INetd::PERMISSION_SYSTEM:
1829 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1830 break;
1831 }
1832
1833 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1834 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1835 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1836 }
1837}
1838
1839} // namespace
1840
1841TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001842 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001843 const char* ipVersion;
1844 const char* testDest;
1845 const char* testNextHop;
1846 const bool expectSuccess;
1847 } kTestData[] = {
1848 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001849 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1850 {IP_RULE_V4, "10.251.0.0/16", "", true},
1851 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1852 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001853 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001854 {IP_RULE_V6, "::/0", "2001:db8::", true},
1855 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001856 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1857 };
1858
Luke Huangc3252cc2018-10-16 15:43:23 +08001859 static const struct {
1860 const char* ipVersion;
1861 const char* testDest;
1862 const char* testNextHop;
1863 } kTestDataWithNextHop[] = {
1864 {IP_RULE_V4, "10.251.10.0/30", ""},
1865 {IP_RULE_V6, "2001:db8::/32", ""},
1866 };
1867
Luke Huangb670d162018-08-23 20:01:13 +08001868 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001869 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001870 const int testUid = randomUid();
1871 const std::vector<int32_t> testUids = {testUid};
1872
1873 // Add test physical network
1874 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1875 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1876
Luke Huangc3252cc2018-10-16 15:43:23 +08001877 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001878 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001879 const auto& td = kTestDataWithNextHop[i];
1880
1881 // All route for test tun will disappear once the tun interface is deleted.
1882 binder::Status status =
1883 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1884 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1885 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1886 sTun.name().c_str());
1887
1888 // Add system permission for test uid, setup route in legacy system table.
1889 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1890
1891 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1892 testUid);
1893 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1894 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1895 testTableLegacySystem);
1896
1897 // Remove system permission for test uid, setup route in legacy network table.
1898 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1899
1900 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1901 testUid);
1902 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1903 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1904 testTableLegacyNetwork);
1905 }
1906
Sehee Park8659b8d2018-11-16 10:53:16 +09001907 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001908 const auto& td = kTestData[i];
1909
1910 binder::Status status =
1911 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1912 if (td.expectSuccess) {
1913 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001914 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001915 sTun.name().c_str());
1916 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001917 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1918 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001919 }
1920
1921 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1922 if (td.expectSuccess) {
1923 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001924 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1925 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001926 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001927 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1928 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001929 }
1930
Luke Huangc3252cc2018-10-16 15:43:23 +08001931 // Add system permission for test uid, route will be added into legacy system table.
1932 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001933
1934 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1935 testUid);
1936 if (td.expectSuccess) {
1937 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001938 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001939 testTableLegacySystem);
1940 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001941 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1942 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001943 }
1944
1945 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1946 td.testNextHop, testUid);
1947 if (td.expectSuccess) {
1948 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001949 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1950 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001951 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001952 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1953 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001954 }
1955
Luke Huangc3252cc2018-10-16 15:43:23 +08001956 // Remove system permission for test uid, route will be added into legacy network table.
1957 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1958
1959 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1960 testUid);
1961 if (td.expectSuccess) {
1962 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1963 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1964 testTableLegacyNetwork);
1965 } else {
1966 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1967 EXPECT_NE(0, status.serviceSpecificErrorCode());
1968 }
1969
1970 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1971 td.testNextHop, testUid);
1972 if (td.expectSuccess) {
1973 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1974 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1975 testTableLegacyNetwork);
1976 } else {
1977 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1978 EXPECT_NE(0, status.serviceSpecificErrorCode());
1979 }
Luke Huangb670d162018-08-23 20:01:13 +08001980 }
1981
1982 // Remove test physical network
1983 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1984}
1985
1986TEST_F(BinderTest, NetworkPermissionDefault) {
1987 // Add test physical network
1988 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1989 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1990
Luke Huangc3252cc2018-10-16 15:43:23 +08001991 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001992 int currentNetid;
1993 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1994 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1995
1996 // Test SetDefault
1997 status = mNetd->networkSetDefault(TEST_NETID1);
1998 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1999 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
2000
2001 status = mNetd->networkClearDefault();
2002 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2003 expectNetworkDefaultIpRuleDoesNotExist();
2004
2005 // Add default network back
2006 status = mNetd->networkSetDefault(currentNetid);
2007 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2008
2009 // Test SetPermission
2010 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
2011 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2012 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
2013 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
2014
2015 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
2016 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2017 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
2018 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
2019
2020 // Remove test physical network
2021 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2022}
2023
2024TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
2025 const int testUid = randomUid();
2026 binder::Status status = mNetd->networkSetProtectAllow(testUid);
2027 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2028 bool ret = false;
2029 status = mNetd->networkCanProtect(testUid, &ret);
2030 EXPECT_TRUE(ret);
2031
2032 status = mNetd->networkSetProtectDeny(testUid);
2033 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2034 status = mNetd->networkCanProtect(testUid, &ret);
2035 EXPECT_FALSE(ret);
2036}
2037
2038namespace {
2039
Luke Huangb5733d72018-08-21 17:17:19 +08002040int readIntFromPath(const std::string& path) {
2041 std::string result = "";
2042 EXPECT_TRUE(ReadFileToString(path, &result));
2043 return std::stoi(result);
2044}
2045
2046int getTetherAcceptIPv6Ra(const std::string& ifName) {
2047 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
2048 return readIntFromPath(path);
2049}
2050
2051bool getTetherAcceptIPv6Dad(const std::string& ifName) {
2052 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
2053 return readIntFromPath(path);
2054}
2055
2056int getTetherIPv6DadTransmits(const std::string& ifName) {
2057 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
2058 return readIntFromPath(path);
2059}
2060
2061bool getTetherEnableIPv6(const std::string& ifName) {
2062 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2063 int disableIPv6 = readIntFromPath(path);
2064 return !disableIPv6;
2065}
2066
2067bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2068 for (const auto& iface : ifList) {
2069 if (iface == ifName) {
2070 return true;
2071 }
2072 }
2073 return false;
2074}
2075
2076void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2077 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2078 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2079 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2080 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2081}
2082
2083void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2084 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2085 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2086 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2087 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2088}
2089
2090void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2091 const std::string& ifName) {
2092 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2093}
2094
2095void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2096 const std::string& ifName) {
2097 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2098}
2099
2100void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2101 const std::vector<std::string>& testDnsAddrs) {
2102 EXPECT_TRUE(dnsList == testDnsAddrs);
2103}
2104
2105} // namespace
2106
2107TEST_F(BinderTest, TetherStartStopStatus) {
2108 std::vector<std::string> noDhcpRange = {};
2109 static const char dnsdName[] = "dnsmasq";
2110
2111 binder::Status status = mNetd->tetherStart(noDhcpRange);
2112 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangd1675922019-03-11 17:29:27 +08002113 expectProcessExists(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002114
2115 bool tetherEnabled;
2116 status = mNetd->tetherIsEnabled(&tetherEnabled);
2117 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2118 EXPECT_TRUE(tetherEnabled);
2119
2120 status = mNetd->tetherStop();
2121 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08002122 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002123
2124 status = mNetd->tetherIsEnabled(&tetherEnabled);
2125 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2126 EXPECT_FALSE(tetherEnabled);
2127}
2128
2129TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2130 // TODO: verify if dnsmasq update interface successfully
2131
2132 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2133 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2134 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2135
2136 std::vector<std::string> ifList;
2137 status = mNetd->tetherInterfaceList(&ifList);
2138 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2139 expectTetherInterfaceExists(ifList, sTun.name());
2140
2141 status = mNetd->tetherInterfaceRemove(sTun.name());
2142 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2143 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2144
2145 status = mNetd->tetherInterfaceList(&ifList);
2146 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2147 expectTetherInterfaceNotExists(ifList, sTun.name());
2148}
2149
2150TEST_F(BinderTest, TetherDnsSetList) {
2151 // TODO: verify if dnsmasq update dns successfully
2152 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
2153
2154 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2155 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2156
2157 std::vector<std::string> dnsList;
2158 status = mNetd->tetherDnsList(&dnsList);
2159 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2160 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002161}
2162
2163namespace {
2164
2165constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2166constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2167constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2168constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2169constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2170constexpr char FIREWALL_STANDBY[] = "fw_standby";
2171constexpr char targetReturn[] = "RETURN";
2172constexpr char targetDrop[] = "DROP";
2173
2174void expectFirewallWhitelistMode() {
2175 static const char dropRule[] = "DROP all";
2176 static const char rejectRule[] = "REJECT all";
2177 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2178 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2179 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2180 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2181 }
2182}
2183
2184void expectFirewallBlacklistMode() {
2185 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2186 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2187 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2188 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2189 }
2190}
2191
2192bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2193 const std::string& expectedInterface,
2194 const std::string& expectedRule) {
2195 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2196 // Expected rule:
2197 // Chain fw_INPUT (1 references)
2198 // pkts bytes target prot opt in out source destination
2199 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2200 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2201 int firstRuleIndex = 2;
2202 if (rules.size() < 4) return false;
2203 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2204 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2205 return true;
2206 }
2207 }
2208 return false;
2209}
2210
2211// TODO: It is a duplicate function, need to remove it
2212bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2213 const std::string& expectedInterface,
2214 const std::string& expectedRule) {
2215 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2216 for (const auto& rule : rules) {
2217 if (rule.find(expectedInterface) != std::string::npos) {
2218 if (rule.find(expectedRule) != std::string::npos) {
2219 return true;
2220 }
2221 }
2222 }
2223 return false;
2224}
2225
2226void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2227 static const char returnRule[] = "RETURN all";
2228 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2229 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2230 returnRule));
2231 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2232 returnRule));
2233 }
2234}
2235
2236void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2237 static const char returnRule[] = "RETURN all";
2238 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2239 EXPECT_FALSE(
2240 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2241 EXPECT_FALSE(
2242 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2243 }
2244}
2245
2246bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2247 const std::string& expectedTarget,
2248 const std::string& expectedRule) {
2249 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2250 int firstRuleIndex = 2;
2251 if (rules.size() < 4) return false;
2252 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2253 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2254 return true;
2255 }
2256 }
2257 return false;
2258}
2259
2260bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2261 const std::string& expectedTarget,
2262 const std::string& expectedRule) {
2263 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2264 int lastRuleIndex = rules.size() - 1;
2265 if (lastRuleIndex < 0) return false;
2266 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2267 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2268 return true;
2269 }
2270 }
2271 return false;
2272}
2273
2274void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2275 std::string uidRule = StringPrintf("owner UID match %u", uid);
2276 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2277 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2278}
2279
2280void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2281 std::string uidRule = StringPrintf("owner UID match %u", uid);
2282 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2283 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2284}
2285
2286void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2287 std::string uidRule = StringPrintf("owner UID match %u", uid);
2288 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2289 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2290}
2291
2292void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2293 std::string uidRule = StringPrintf("owner UID match %u", uid);
2294 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2295 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2296}
2297
2298bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2299 std::vector<std::string> inputRules =
2300 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2301 std::vector<std::string> outputRules =
2302 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2303 int inputLastRuleIndex = inputRules.size() - 1;
2304 int outputLastRuleIndex = outputRules.size() - 1;
2305
2306 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2307 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2308 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2309 return true;
2310 }
2311 }
2312 return false;
2313}
2314
2315void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2316 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2317 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2318}
2319
2320void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2321 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2322 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2323 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2324 }
2325}
2326
2327} // namespace
2328
2329TEST_F(BinderTest, FirewallSetFirewallType) {
2330 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2331 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2332 expectFirewallWhitelistMode();
2333
2334 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2335 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2336 expectFirewallBlacklistMode();
2337
2338 // set firewall type blacklist twice
2339 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2340 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2341 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2342 expectFirewallBlacklistMode();
2343
2344 // set firewall type whitelist twice
2345 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2346 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2347 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2348 expectFirewallWhitelistMode();
2349
2350 // reset firewall type to default
2351 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2352 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2353 expectFirewallBlacklistMode();
2354}
2355
2356TEST_F(BinderTest, FirewallSetInterfaceRule) {
2357 // setinterfaceRule is not supported in BLACKLIST MODE
2358 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2359 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2360
2361 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2362 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2363
2364 // set WHITELIST mode first
2365 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2366 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2367
2368 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2369 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2370 expectFirewallInterfaceRuleAllowExists(sTun.name());
2371
2372 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2373 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2374 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2375
2376 // reset firewall mode to default
2377 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2378 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2379 expectFirewallBlacklistMode();
2380}
2381
2382TEST_F(BinderTest, FirewallSetUidRule) {
2383 SKIP_IF_BPF_SUPPORTED;
2384
2385 int32_t uid = randomUid();
2386
2387 // Doze allow
2388 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2389 INetd::FIREWALL_RULE_ALLOW);
2390 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2391 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2392
2393 // Doze deny
2394 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2395 INetd::FIREWALL_RULE_DENY);
2396 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2397 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2398
2399 // Powersave allow
2400 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2401 INetd::FIREWALL_RULE_ALLOW);
2402 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2403 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2404
2405 // Powersave deny
2406 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2407 INetd::FIREWALL_RULE_DENY);
2408 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2409 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2410
2411 // Standby deny
2412 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2413 INetd::FIREWALL_RULE_DENY);
2414 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2415 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2416
2417 // Standby allow
2418 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2419 INetd::FIREWALL_RULE_ALLOW);
2420 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2421 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2422
2423 // None deny in BLACKLIST
2424 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2425 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2426 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2427 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2428
2429 // None allow in BLACKLIST
2430 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2431 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2432 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2433 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2434
2435 // set firewall type whitelist twice
2436 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2437 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2438 expectFirewallWhitelistMode();
2439
2440 // None allow in WHITELIST
2441 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2442 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2443 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2444 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2445
2446 // None deny in WHITELIST
2447 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2448 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2449 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2450 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2451
2452 // reset firewall mode to default
2453 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2454 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2455 expectFirewallBlacklistMode();
2456}
2457
2458TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2459 SKIP_IF_BPF_SUPPORTED;
2460
2461 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2462 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2463 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2464
2465 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2466 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2467 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2468
2469 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2470 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2471 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2472
2473 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2474 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2475 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2476
2477 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2478 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2479 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2480
2481 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2482 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2483 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2484}
Luke Huangf7782042018-08-08 13:13:04 +08002485
2486namespace {
2487
2488std::string hwAddrToStr(unsigned char* hwaddr) {
2489 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2490 hwaddr[4], hwaddr[5]);
2491}
2492
2493int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2494 int prefixLength = 0;
2495 uint32_t m = ntohl(mask);
2496 while (m & (1 << 31)) {
2497 prefixLength++;
2498 m = m << 1;
2499 }
2500 return prefixLength;
2501}
2502
2503std::string toStdString(const String16& s) {
2504 return std::string(String8(s.string()));
2505}
2506
2507android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2508 const auto& sys = sSyscalls.get();
2509 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2510 EXPECT_TRUE(isOk(fd.status()));
2511
2512 struct ifreq ifr = {};
2513 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2514
2515 return sys.ioctl(fd.value(), flag, &ifr);
2516}
2517
2518std::string getInterfaceHwAddr(const std::string& ifName) {
2519 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2520
2521 unsigned char hwaddr[ETH_ALEN] = {};
2522 if (isOk(res.status())) {
2523 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2524 }
2525
2526 return hwAddrToStr(hwaddr);
2527}
2528
2529int getInterfaceIPv4Prefix(const std::string& ifName) {
2530 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2531
2532 int prefixLength = 0;
2533 if (isOk(res.status())) {
2534 prefixLength = ipv4NetmaskToPrefixLength(
2535 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2536 }
2537
2538 return prefixLength;
2539}
2540
2541std::string getInterfaceIPv4Addr(const std::string& ifName) {
2542 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2543
2544 struct in_addr addr = {};
2545 if (isOk(res.status())) {
2546 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2547 }
2548
2549 return std::string(inet_ntoa(addr));
2550}
2551
2552std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2553 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2554
2555 unsigned flags = 0;
2556 if (isOk(res.status())) {
2557 flags = res.value().ifr_flags;
2558 }
2559
2560 std::vector<std::string> ifFlags;
2561 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2562 : toStdString(INetd::IF_STATE_DOWN()));
2563
2564 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2565 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2566 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2567 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2568 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2569
2570 return ifFlags;
2571}
2572
2573bool compareListInterface(const std::vector<std::string>& interfaceList) {
2574 const auto& res = InterfaceController::getIfaceNames();
2575 EXPECT_TRUE(isOk(res));
2576
2577 std::vector<std::string> resIfList;
2578 resIfList.reserve(res.value().size());
2579 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2580
2581 return resIfList == interfaceList;
2582}
2583
2584int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2585 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2586 return readIntFromPath(path);
2587}
2588
2589bool getInterfaceEnableIPv6(const std::string& ifName) {
2590 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2591
2592 int disableIPv6 = readIntFromPath(path);
2593 return !disableIPv6;
2594}
2595
2596int getInterfaceMtu(const std::string& ifName) {
2597 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2598 return readIntFromPath(path);
2599}
2600
2601void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2602 EXPECT_TRUE(compareListInterface(interfaceList));
2603}
2604
2605void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2606 const InterfaceConfigurationParcel& interfaceCfg) {
2607 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2608 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2609 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2610 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2611}
2612
2613void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2614 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2615 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2616
2617 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2618 for (const auto& flag : setCfg.flags) {
2619 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2620 }
2621}
2622
2623void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2624 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2625 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2626}
2627
2628void expectInterfaceNoAddr(const std::string& ifName) {
2629 // noAddr
2630 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2631 // noPrefix
2632 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2633}
2634
2635void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2636 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2637 EXPECT_EQ(enableIPv6, enable);
2638}
2639
2640void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2641 int mtuSize = getInterfaceMtu(ifName);
2642 EXPECT_EQ(mtu, mtuSize);
2643}
2644
2645InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2646 const std::string& addr, int prefixLength,
2647 const std::vector<std::string>& flags) {
2648 InterfaceConfigurationParcel cfg;
2649 cfg.ifName = ifName;
2650 cfg.hwAddr = "";
2651 cfg.ipv4Addr = addr;
2652 cfg.prefixLength = prefixLength;
2653 cfg.flags = flags;
2654 return cfg;
2655}
2656
2657void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2658 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2659 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2660
2661 for (const auto& flag : expectedFlags) {
2662 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2663 interfaceCfg.flags.end());
2664 }
2665
2666 for (const auto& flag : unexpectedFlags) {
2667 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2668 interfaceCfg.flags.end());
2669 }
2670}
2671
2672} // namespace
2673
2674TEST_F(BinderTest, InterfaceList) {
2675 std::vector<std::string> interfaceListResult;
2676
2677 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2678 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2679 expectInterfaceList(interfaceListResult);
2680}
2681
2682TEST_F(BinderTest, InterfaceGetCfg) {
2683 InterfaceConfigurationParcel interfaceCfgResult;
2684
2685 // Add test physical network
2686 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2687 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2688
2689 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2690 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2691 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2692 expectTunFlags(interfaceCfgResult);
2693
2694 // Remove test physical network
2695 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2696}
2697
2698TEST_F(BinderTest, InterfaceSetCfg) {
2699 const std::string testAddr = "192.0.2.3";
2700 const int testPrefixLength = 24;
2701 std::vector<std::string> upFlags = {"up"};
2702 std::vector<std::string> downFlags = {"down"};
2703
2704 // Add test physical network
2705 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2706 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2707
2708 // Set tun interface down.
2709 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2710 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2711 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2712 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2713
2714 // Set tun interface up again.
2715 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2716 status = mNetd->interfaceSetCfg(interfaceCfg);
2717 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2718 status = mNetd->interfaceClearAddrs(sTun.name());
2719 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2720
2721 // Remove test physical network
2722 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2723}
2724
2725TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2726 // enable
2727 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2728 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2729 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2730
2731 // disable
2732 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2733 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2734 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2735}
2736
2737TEST_F(BinderTest, InterfaceClearAddr) {
2738 const std::string testAddr = "192.0.2.3";
2739 const int testPrefixLength = 24;
2740 std::vector<std::string> noFlags{};
2741
2742 // Add test physical network
2743 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2744 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2745
2746 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2747 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2748 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2749 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2750
2751 status = mNetd->interfaceClearAddrs(sTun.name());
2752 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2753 expectInterfaceNoAddr(sTun.name());
2754
2755 // Remove test physical network
2756 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2757}
2758
2759TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2760 // Add test physical network
2761 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2762 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2763
2764 // disable
2765 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2766 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2767 expectInterfaceEnableIPv6(sTun.name(), false);
2768
2769 // enable
2770 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2771 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2772 expectInterfaceEnableIPv6(sTun.name(), true);
2773
2774 // Remove test physical network
2775 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2776}
2777
2778TEST_F(BinderTest, InterfaceSetMtu) {
2779 const int testMtu = 1200;
2780
2781 // Add test physical network
2782 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2783 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2784
2785 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2786 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2787 expectInterfaceMtu(sTun.name(), testMtu);
2788
2789 // Remove test physical network
2790 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2791}
Luke Huang19b49c52018-10-22 12:12:05 +09002792
2793namespace {
2794
2795constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2796constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002797constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002798constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2799
Luke Huangae038f82018-11-05 11:17:31 +09002800int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002801 return listIptablesRuleByTable(binary, table, chainName).size();
2802}
2803
2804bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2805 const std::vector<std::string>& targetVec) {
2806 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2807 if (targetVec.size() != rules.size() - 2) {
2808 return false;
2809 }
2810
2811 /*
Luke Huangae038f82018-11-05 11:17:31 +09002812 * Check that the rules match. Note that this function matches substrings, not entire rules,
2813 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002814 * Skip first two lines since rules start from third line.
2815 * Chain chainName (x references)
2816 * pkts bytes target prot opt in out source destination
2817 * ...
2818 */
2819 int rIndex = 2;
2820 for (const auto& target : targetVec) {
2821 if (rules[rIndex].find(target) == std::string::npos) {
2822 return false;
2823 }
2824 rIndex++;
2825 }
2826 return true;
2827}
2828
2829void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2830 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2831 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2832 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002833 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002834 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2835 "DROP"};
2836
2837 // V4
2838 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2839 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002840 EXPECT_TRUE(
2841 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002842 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2843
Luke Huangae038f82018-11-05 11:17:31 +09002844 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002845 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2846
2847 // V6
2848 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002849 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2850 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002851
2852 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2853 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2854 extIf));
2855 }
2856}
2857
2858void expectNatDisable() {
2859 // It is the default DROP rule with tethering disable.
2860 // Chain tetherctrl_FORWARD (1 references)
2861 // pkts bytes target prot opt in out source destination
2862 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2863 std::vector<std::string> forwardV4Match = {"DROP"};
2864 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2865
2866 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002867 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2868 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002869
Luke Huangae038f82018-11-05 11:17:31 +09002870 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2871 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002872
2873 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2874}
2875
2876} // namespace
2877
2878TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002879 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2880 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2881 expectNatEnable(sTun.name(), sTun2.name());
2882
2883 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2884 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2885 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002886}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002887
2888namespace {
2889
2890using TripleInt = std::array<int, 3>;
2891
2892TripleInt readProcFileToTripleInt(const std::string& path) {
2893 std::string valueString;
2894 int min, def, max;
2895 EXPECT_TRUE(ReadFileToString(path, &valueString));
2896 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2897 return {min, def, max};
2898}
2899
2900void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2901 std::string testRmemValues =
2902 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2903 std::string testWmemValues =
2904 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2905 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2906
2907 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2908 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2909
2910 for (int i = 0; i < 3; i++) {
2911 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2912 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2913 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2914 }
2915}
2916
2917} // namespace
2918
2919TEST_F(BinderTest, TcpBufferSet) {
2920 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2921 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2922 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2923 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2924
2925 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2926 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2927}
Luke Huang528af602018-08-29 19:06:05 +08002928
Chenbo Feng48eaed32018-12-26 17:40:21 -08002929namespace {
2930
2931void checkUidsExist(std::vector<int32_t>& uids, bool exist) {
2932 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2933 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2934 for (int32_t uid : uids) {
2935 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2936 if (exist) {
2937 EXPECT_TRUE(isOk(permission));
2938 EXPECT_EQ(ALLOW_SOCK_CREATE, permission.value());
2939 } else {
2940 EXPECT_FALSE(isOk(permission));
2941 EXPECT_EQ(ENOENT, permission.status().code());
2942 }
2943 }
2944}
2945
2946} // namespace
2947
2948TEST_F(BinderTest, TestInternetPermission) {
2949 SKIP_IF_BPF_NOT_SUPPORTED;
2950
2951 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2952
2953 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
2954 checkUidsExist(appUids, true);
2955 mNetd->trafficSetNetPermForUids(INetd::NO_PERMISSIONS, appUids);
2956 checkUidsExist(appUids, false);
2957}
2958
Luke Huang528af602018-08-29 19:06:05 +08002959TEST_F(BinderTest, UnsolEvents) {
2960 auto testUnsolService = android::net::TestUnsolService::start();
2961 std::string oldTunName = sTun.name();
2962 std::string newTunName = "unsolTest";
2963 testUnsolService->tarVec.push_back(oldTunName);
2964 testUnsolService->tarVec.push_back(newTunName);
2965 auto& cv = testUnsolService->getCv();
2966 auto& cvMutex = testUnsolService->getCvMutex();
2967 binder::Status status = mNetd->registerUnsolicitedEventListener(
2968 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2969 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2970
2971 // TODO: Add test for below events
2972 // StrictCleartextDetected / InterfaceDnsServersAdded
2973 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2974
2975 {
2976 std::unique_lock lock(cvMutex);
2977
2978 // Re-init test Tun, and we expect that we will get some unsol events.
2979 // Use the test Tun device name to verify if we receive its unsol events.
2980 sTun.destroy();
2981 // Use predefined name
2982 sTun.init(newTunName);
2983
2984 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2985 }
2986
2987 // bit mask 1101101000
2988 // Test only covers below events currently
2989 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2990 InterfaceLinkStatusChanged | RouteChanged;
2991 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Bernie Innocentia5161a02019-01-30 22:40:53 +09002992}