blob: 801226d83ff0f7bacf7dd15d3a4f1566be7f8d37 [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>
20#include <cinttypes>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090021#include <cstdint>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090022#include <cstdio>
23#include <cstdlib>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090024#include <set>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090025#include <vector>
26
Luke Huangf7782042018-08-08 13:13:04 +080027#include <dirent.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090028#include <fcntl.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090029#include <ifaddrs.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090030#include <linux/if.h>
31#include <linux/if_tun.h>
Benedict Wonga450e722018-05-07 10:29:02 -070032#include <net/if.h>
Luke Huangf7782042018-08-08 13:13:04 +080033#include <netdb.h>
34#include <netinet/in.h>
Ben Schwartze7601812017-04-28 16:38:29 -040035#include <openssl/base64.h>
Luke Huangf7782042018-08-08 13:13:04 +080036#include <sys/socket.h>
37#include <sys/types.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090038
Luke Huang531f5d32018-08-03 15:19:05 +080039#include <android-base/file.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090040#include <android-base/macros.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090041#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090042#include <android-base/strings.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070043#include <bpf/BpfUtils.h>
Robin Leeb8087362016-03-30 18:43:08 +010044#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090045#include <gtest/gtest.h>
46#include <logwrap/logwrap.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090047#include <netutils/ifc.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090048
Nathan Harold21299f72018-03-16 20:13:03 -070049#include "InterfaceController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090050#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090051#include "Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070052#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090053#include "android/net/INetd.h"
54#include "binder/IServiceManager.h"
Nathan Harold21299f72018-03-16 20:13:03 -070055#include "netdutils/Syscalls.h"
Mike Yu5ae61542018-10-19 22:11:43 +080056#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090057
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090058#define IP_PATH "/system/bin/ip"
59#define IP6TABLES_PATH "/system/bin/ip6tables"
60#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090061#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080062#define RAW_TABLE "raw"
63#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080064#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090065#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090066
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090067namespace binder = android::binder;
68namespace netdutils = android::netdutils;
69
70using android::IBinder;
71using android::IServiceManager;
72using android::sp;
73using android::String16;
74using android::String8;
75using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080076using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090077using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090078using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080079using android::base::Trim;
Chenbo Fengf5663d82018-11-08 16:10:48 -080080using android::base::WriteStringToFile;
Chenbo Feng837ddfc2018-05-08 13:45:08 -070081using android::bpf::hasBpfSupport;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090082using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080083using android::net::InterfaceConfigurationParcel;
84using android::net::InterfaceController;
Luke Huangcaebcbb2018-09-27 20:37:14 +080085using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090086using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090087using android::net::UidRangeParcel;
Nathan Harold21299f72018-03-16 20:13:03 -070088using android::net::XfrmController;
Luke Huangf7782042018-08-08 13:13:04 +080089using android::netdutils::sSyscalls;
Robin Leeb8087362016-03-30 18:43:08 +010090
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090091#define SKIP_IF_BPF_SUPPORTED \
92 do { \
93 if (hasBpfSupport()) return; \
94 } while (0)
Chenbo Feng837ddfc2018-05-08 13:45:08 -070095
Robin Leeb8087362016-03-30 18:43:08 +010096static const char* IP_RULE_V4 = "-4";
97static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090098static const int TEST_NETID1 = 65501;
99static const int TEST_NETID2 = 65502;
100constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900101
Benedict Wongb2daefb2017-12-06 22:05:46 -0800102static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
103static const std::string ESP_ALLOW_RULE("esp");
104
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900105class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900106 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900107 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900108 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900109 sp<IBinder> binder = sm->getService(String16("netd"));
110 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900111 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900112 }
113 }
114
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900115 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900116 ASSERT_NE(nullptr, mNetd.get());
117 }
118
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900119 void TearDown() override {
120 mNetd->networkDestroy(TEST_NETID1);
121 mNetd->networkDestroy(TEST_NETID2);
122 }
123
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900124 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700125
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900126 // Static because setting up the tun interface takes about 40ms.
127 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900128 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900129 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900130 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900131 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900132 }
133
134 static void TearDownTestCase() {
135 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900136 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900137 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900138 }
139
140 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900141
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900142 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900143 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900144 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900145 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900146};
147
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900148TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900149TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900150
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900151class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900152 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700153 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900154 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900155 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900156 }
157
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900158 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900159 std::string mName;
160};
161
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900162TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900163 TimedOperation t("isAlive RPC");
164 bool isAlive = false;
165 mNetd->isAlive(&isAlive);
166 ASSERT_TRUE(isAlive);
167}
168
169static int randomUid() {
170 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
171}
172
Robin Leeb8087362016-03-30 18:43:08 +0100173static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900174 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900175 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
176 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900177 perror("popen");
178 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900179 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900180
181 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100182 size_t bufsize = 0;
183 ssize_t linelen = 0;
184 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900185 lines.push_back(std::string(line, linelen));
186 free(line);
187 line = nullptr;
188 }
189
190 pclose(f);
191 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900192}
193
Robin Leeb8087362016-03-30 18:43:08 +0100194static std::vector<std::string> listIpRules(const char *ipVersion) {
195 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
196 return runCommand(command);
197}
198
199static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900200 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100201 return runCommand(command);
202}
203
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900204static int iptablesRuleLineLength(const char *binary, const char *chainName) {
205 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900206}
207
Benedict Wongb2daefb2017-12-06 22:05:46 -0800208static bool iptablesRuleExists(const char *binary,
209 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900210 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800211 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900212 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800213 if(rule.find(expectedRule) != std::string::npos) {
214 return true;
215 }
216 }
217 return false;
218}
219
220static bool iptablesNoSocketAllowRuleExists(const char *chainName){
221 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
222 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
223}
224
225static bool iptablesEspAllowRuleExists(const char *chainName){
226 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
227 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
228}
229
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900230TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700231 SKIP_IF_BPF_SUPPORTED;
232
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900233 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
234 const int kNumUids = 500;
235 std::vector<int32_t> noUids(0);
236 std::vector<int32_t> uids(kNumUids);
237 for (int i = 0; i < kNumUids; i++) {
238 uids[i] = randomUid();
239 }
240
241 bool ret;
242 {
243 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900244 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900245 }
246 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800247 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
248 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
249 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
250 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900251 {
252 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900253 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900254 }
255 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900256 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
257 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900258
259 {
260 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900261 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900262 }
263 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900264 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
265 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800266 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
267 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900268
269 {
270 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900271 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900272 }
273 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900274 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
275 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900276
277 // Check that the call fails if iptables returns an error.
278 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900279 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900280 EXPECT_EQ(false, ret);
281}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900282
Benedict Wong319f17e2018-05-15 17:06:44 -0700283TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700284 const struct TestData {
285 const std::string family;
286 const std::string deviceName;
287 const std::string localAddress;
288 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800289 int32_t iKey;
290 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700291 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800292 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700293 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
294 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
295 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800296 };
297
Luke Huangc3252cc2018-10-16 15:43:23 +0800298 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700299 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800300
301 binder::Status status;
302
Benedict Wong319f17e2018-05-15 17:06:44 -0700303 // Create Tunnel Interface.
304 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700305 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800306 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
307
Benedict Wonga450e722018-05-07 10:29:02 -0700308 // Check that the interface exists
309 EXPECT_NE(0, if_nametoindex(td.deviceName.c_str()));
310
Benedict Wong319f17e2018-05-15 17:06:44 -0700311 // Update Tunnel Interface.
312 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700313 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800314 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
315
Benedict Wong319f17e2018-05-15 17:06:44 -0700316 // Remove Tunnel Interface.
317 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800318 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700319
320 // Check that the interface no longer exists
321 EXPECT_EQ(0, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800322 }
323}
324
Nathan Harold2deff322018-05-10 14:03:48 -0700325// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
326// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
327#if INTPTR_MAX != INT32_MAX
Benedict Wonga04ffa72018-05-09 21:42:42 -0700328static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
329 static_cast<int>(android::net::XfrmDirection::OUT)};
330static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
331
Nathan Harold21299f72018-03-16 20:13:03 -0700332#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
333 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900334bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Nathan Harold21299f72018-03-16 20:13:03 -0700335 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
336 SCOPED_TRACE(status);
337 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
338
339 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700340 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700341 SCOPED_TRACE(status);
342 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
343
344 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700345 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
346 0xD00D, 0xE00D, false)
347 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700348}
349
Benedict Wonga04ffa72018-05-09 21:42:42 -0700350TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
351 binder::Status status;
352
353 // Repeat to ensure cleanup and recreation works correctly
354 for (int i = 0; i < 2; i++) {
355 for (int direction : XFRM_DIRECTIONS) {
356 for (int addrFamily : ADDRESS_FAMILIES) {
357 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700358 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700359 EXPECT_TRUE(status.isOk())
360 << " family: " << addrFamily << " direction: " << direction;
361 }
362 }
363
364 // Cleanup
365 for (int direction : XFRM_DIRECTIONS) {
366 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700367 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700368 EXPECT_TRUE(status.isOk());
369 }
370 }
371 }
372}
373
374TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
375 binder::Status status;
376
377 // Repeat to ensure cleanup and recreation works correctly
378 for (int i = 0; i < 2; i++) {
379 for (int direction : XFRM_DIRECTIONS) {
380 for (int addrFamily : ADDRESS_FAMILIES) {
381 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700382 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700383 EXPECT_TRUE(status.isOk())
384 << " family: " << addrFamily << " direction: " << direction;
385 }
386 }
387
388 // Cleanup
389 for (int direction : XFRM_DIRECTIONS) {
390 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700391 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700392 EXPECT_TRUE(status.isOk());
393 }
394 }
395 }
396}
397
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900398TEST_F(BinderTest, XfrmControllerInit) {
Nathan Harold21299f72018-03-16 20:13:03 -0700399 netdutils::Status status;
400 status = XfrmController::Init();
401 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700402
403 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
404 // feature.
405 if (status.code() == EOPNOTSUPP) return;
406
Nathan Harold21299f72018-03-16 20:13:03 -0700407 ASSERT_TRUE(status.ok());
408
409 int32_t spi = 0;
410
411 ASSERT_TRUE(allocateIpSecResources(true, &spi));
412 ASSERT_TRUE(allocateIpSecResources(false, &spi));
413
414 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700415 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700416 ASSERT_TRUE(allocateIpSecResources(true, &spi));
417
418 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700419 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700420 SCOPED_TRACE(status);
421 ASSERT_TRUE(status.ok());
422
Benedict Wonga450e722018-05-07 10:29:02 -0700423 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700424 SCOPED_TRACE(status);
425 ASSERT_TRUE(status.ok());
426
427 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700428 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700429}
Nathan Harold2deff322018-05-10 14:03:48 -0700430#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700431
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900432static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900433 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900434
435 // Output looks like this:
436 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900437 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900438 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900439 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900440 //
441 // or:
442 //
443 // Chain bw_data_saver (1 references)
444 // target prot opt source destination
445 // ... possibly connectivity critical packet rules here ...
446 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900447
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900448 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900449
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900450 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
451 // Data saver disabled.
452 return 0;
453 }
454
455 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
456
457 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
458 // Data saver enabled.
459 return 1;
460 }
461
462 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900463}
464
465bool enableDataSaver(sp<INetd>& netd, bool enable) {
466 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
467 bool ret;
468 netd->bandwidthEnableDataSaver(enable, &ret);
469 return ret;
470}
471
472int getDataSaverState() {
473 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
474 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
475 EXPECT_EQ(enabled4, enabled6);
476 EXPECT_NE(-1, enabled4);
477 EXPECT_NE(-1, enabled6);
478 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
479 return -1;
480 }
481 return enabled6;
482}
483
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900484TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900485 const int wasEnabled = getDataSaverState();
486 ASSERT_NE(-1, wasEnabled);
487
488 if (wasEnabled) {
489 ASSERT_TRUE(enableDataSaver(mNetd, false));
490 EXPECT_EQ(0, getDataSaverState());
491 }
492
493 ASSERT_TRUE(enableDataSaver(mNetd, false));
494 EXPECT_EQ(0, getDataSaverState());
495
496 ASSERT_TRUE(enableDataSaver(mNetd, true));
497 EXPECT_EQ(1, getDataSaverState());
498
499 ASSERT_TRUE(enableDataSaver(mNetd, true));
500 EXPECT_EQ(1, getDataSaverState());
501
502 if (!wasEnabled) {
503 ASSERT_TRUE(enableDataSaver(mNetd, false));
504 EXPECT_EQ(0, getDataSaverState());
505 }
506}
Robin Leeb8087362016-03-30 18:43:08 +0100507
Luke Huang94658ac2018-10-18 19:35:12 +0900508static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
509 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100510 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100511 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100512 std::vector<std::string> rules = listIpRules(ipVersion);
513
514 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900515 std::string suffix =
516 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900517 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800518 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100519 return true;
520 }
521 }
522 return false;
523}
524
Luke Huang94658ac2018-10-18 19:35:12 +0900525static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
526 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100527 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
528 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
529 EXPECT_EQ(existsIp4, existsIp6);
530 return existsIp4;
531}
532
Luke Huang94658ac2018-10-18 19:35:12 +0900533namespace {
534
535UidRangeParcel makeUidRangeParcel(int start, int stop) {
536 UidRangeParcel res;
537 res.start = start;
538 res.stop = stop;
539
540 return res;
541}
542
543} // namespace
544
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900545TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800546 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
547 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
548 .serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900549 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
550 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
551
552 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
553 EXPECT_EQ(EBUSY,
554 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
555
556 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
557 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
558 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800559 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900560}
561
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900562TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900563 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
564
565 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
566 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
567 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
568
Luke Huang94658ac2018-10-18 19:35:12 +0900569 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
570 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
571 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900572 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
573
574 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
575
576 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
577 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
578 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
579 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
580
581 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
582 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
583 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
584 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
585
586 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
587}
588
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900589TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100590 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100591
Luke Huang94658ac2018-10-18 19:35:12 +0900592 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
593 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100594
595 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
596 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
597
598 // Create two valid rules.
599 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
600 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
601 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
602 for (auto const& range : uidRanges) {
603 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
604 }
605
606 // Remove the rules.
607 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
608 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
609 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
610 for (auto const& range : uidRanges) {
611 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
612 }
613
614 // Fail to remove the rules a second time after they are already deleted.
615 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
616 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
617 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
618
619 // All rules should be the same as before.
620 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
621 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
622}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900623
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900624// Create a socket pair that isLoopbackSocket won't think is local.
625void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900626 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900627 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900628 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
629
630 socklen_t addrlen = sizeof(server6);
631 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
632 ASSERT_EQ(0, listen(*serverSocket, 10));
633
Bernie Innocentif6918262018-06-11 17:37:35 +0900634 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900635 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900636 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900637 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
638 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
639
Bernie Innocentif6918262018-06-11 17:37:35 +0900640 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900641 ASSERT_NE(-1, *acceptedSocket);
642
643 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
644}
645
646void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
647 char buf[4096];
648 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
649 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
650 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
651}
652
653void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
654 // Check that the client socket was closed with ECONNABORTED.
655 int ret = write(clientSocket, "foo", sizeof("foo"));
656 int err = errno;
657 EXPECT_EQ(-1, ret);
658 EXPECT_EQ(ECONNABORTED, err);
659
660 // Check that it sent a RST to the server.
661 ret = write(acceptedSocket, "foo", sizeof("foo"));
662 err = errno;
663 EXPECT_EQ(-1, ret);
664 EXPECT_EQ(ECONNRESET, err);
665}
666
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900667TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900668 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900669 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900670
671 // Pick a random UID in the system UID range.
672 constexpr int baseUid = AID_APP - 2000;
673 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
674 int uid = baseUid + 500 + arc4random_uniform(1000);
675 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
676
677 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900678 std::vector<UidRangeParcel> uidRanges = {
679 makeUidRangeParcel(baseUid + 42, baseUid + 449),
680 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
681 makeUidRangeParcel(baseUid + 498, uid - 1),
682 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900683 };
684 // A skip list that doesn't contain UID.
685 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
686
687 // Close sockets. Our test socket should be intact.
688 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
689 checkSocketpairOpen(clientSocket, acceptedSocket);
690
691 // UID ranges that do contain uid.
692 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900693 makeUidRangeParcel(baseUid + 42, baseUid + 449),
694 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
695 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900696 };
697 // Add uid to the skip list.
698 skipUids.push_back(uid);
699
700 // Close sockets. Our test socket should still be intact because it's in the skip list.
701 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
702 checkSocketpairOpen(clientSocket, acceptedSocket);
703
704 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
705 skipUids.resize(skipUids.size() - 1);
706 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
707 checkSocketpairClosed(clientSocket, acceptedSocket);
708
709 close(clientSocket);
710 close(serverSocket);
711 close(acceptedSocket);
712}
Erik Klinecc4f2732016-08-03 11:24:27 +0900713
714namespace {
715
716int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
717 if (buf == nullptr) return -1;
718
719 int prefixLength = 0;
720 bool endOfContiguousBits = false;
721 for (unsigned int i = 0; i < buflen; i++) {
722 const uint8_t value = buf[i];
723
724 // Bad bit sequence: check for a contiguous set of bits from the high
725 // end by verifying that the inverted value + 1 is a power of 2
726 // (power of 2 iff. (v & (v - 1)) == 0).
727 const uint8_t inverse = ~value + 1;
728 if ((inverse & (inverse - 1)) != 0) return -1;
729
730 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
731
732 // Bogus netmask.
733 if (endOfContiguousBits && value != 0) return -1;
734
735 if (value != 0xff) endOfContiguousBits = true;
736 }
737
738 return prefixLength;
739}
740
741template<typename T>
742int netmaskToPrefixLength(const T *p) {
743 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
744}
745
746
747static bool interfaceHasAddress(
748 const std::string &ifname, const char *addrString, int prefixLength) {
749 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900750
751 const struct addrinfo hints = {
752 .ai_flags = AI_NUMERICHOST,
753 .ai_family = AF_UNSPEC,
754 .ai_socktype = SOCK_DGRAM,
755 };
756 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
757 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
758 return false;
759 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900760 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900761
762 struct ifaddrs *ifaddrsList = nullptr;
763 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
764
765 if (getifaddrs(&ifaddrsList) != 0) {
766 return false;
767 }
768
769 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
770 if (std::string(addr->ifa_name) != ifname ||
771 addr->ifa_addr == nullptr ||
772 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
773 continue;
774 }
775
776 switch (addr->ifa_addr->sa_family) {
777 case AF_INET: {
778 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
779 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
780 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
781 continue;
782 }
783
784 if (prefixLength < 0) return true; // not checking prefix lengths
785
786 if (addr->ifa_netmask == nullptr) return false;
787 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
788 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
789 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
790 }
791 case AF_INET6: {
792 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
793 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
794 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
795 continue;
796 }
797
798 if (prefixLength < 0) return true; // not checking prefix lengths
799
800 if (addr->ifa_netmask == nullptr) return false;
801 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
802 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
803 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
804 }
805 default:
806 // Cannot happen because we have already screened for matching
807 // address families at the top of each iteration.
808 continue;
809 }
810 }
811
812 return false;
813}
814
815} // namespace
816
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900817TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900818 static const struct TestData {
819 const char *addrString;
820 const int prefixLength;
821 const bool expectSuccess;
822 } kTestData[] = {
823 { "192.0.2.1", 24, true },
824 { "192.0.2.2", 25, true },
825 { "192.0.2.3", 32, true },
826 { "192.0.2.4", 33, false },
827 { "192.not.an.ip", 24, false },
828 { "2001:db8::1", 64, true },
829 { "2001:db8::2", 65, true },
830 { "2001:db8::3", 128, true },
831 { "2001:db8::4", 129, false },
832 { "foo:bar::bad", 64, false },
833 };
834
Luke Huangc3252cc2018-10-16 15:43:23 +0800835 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900836 const auto &td = kTestData[i];
837
838 // [1.a] Add the address.
839 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900840 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900841 if (td.expectSuccess) {
842 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
843 } else {
844 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
845 ASSERT_NE(0, status.serviceSpecificErrorCode());
846 }
847
848 // [1.b] Verify the addition meets the expectation.
849 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900850 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900851 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900852 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900853 }
854
855 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900856 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900857 if (td.expectSuccess) {
858 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
859 } else {
860 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
861 ASSERT_NE(0, status.serviceSpecificErrorCode());
862 }
863
864 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900865 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900866 }
867}
Erik Kline55b06f82016-07-04 09:57:18 +0900868
Erik Kline38e51f12018-09-06 20:14:44 +0900869TEST_F(BinderTest, GetProcSysNet) {
870 const char LOOPBACK[] = "lo";
871 static const struct {
872 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900873 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900874 const char* ifname;
875 const char* parameter;
876 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900877 const int expectedReturnCode;
878 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900879 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
880 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
881 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
882 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
883 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
884 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
885 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900886 };
887
Luke Huangc3252cc2018-10-16 15:43:23 +0800888 for (int i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900889 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900890
Erik Kline38e51f12018-09-06 20:14:44 +0900891 std::string value;
892 const binder::Status status =
893 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
894
895 if (td.expectedReturnCode == 0) {
896 SCOPED_TRACE(String8::format("test case %d should have passed", i));
897 EXPECT_EQ(0, status.exceptionCode());
898 EXPECT_EQ(0, status.serviceSpecificErrorCode());
899 EXPECT_EQ(td.expectedValue, value);
900 } else {
901 SCOPED_TRACE(String8::format("test case %d should have failed", i));
902 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
903 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
904 }
905 }
906}
907
908TEST_F(BinderTest, SetProcSysNet) {
909 static const struct {
910 const int ipversion;
911 const int which;
912 const char* ifname;
913 const char* parameter;
914 const char* value;
915 const int expectedReturnCode;
916 } kTestData[] = {
917 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
918 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
919 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
920 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
921 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
922 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
923 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
924 };
925
Luke Huangc3252cc2018-10-16 15:43:23 +0800926 for (int i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900927 const auto& td = kTestData[i];
928
929 const binder::Status status =
930 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900931
932 if (td.expectedReturnCode == 0) {
933 SCOPED_TRACE(String8::format("test case %d should have passed", i));
934 EXPECT_EQ(0, status.exceptionCode());
935 EXPECT_EQ(0, status.serviceSpecificErrorCode());
936 } else {
937 SCOPED_TRACE(String8::format("test case %d should have failed", i));
938 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
939 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
940 }
941 }
942}
Ben Schwartze7601812017-04-28 16:38:29 -0400943
Erik Kline38e51f12018-09-06 20:14:44 +0900944TEST_F(BinderTest, GetSetProcSysNet) {
945 const int ipversion = INetd::IPV6;
946 const int category = INetd::NEIGH;
947 const std::string& tun = sTun.name();
948 const std::string parameter("ucast_solicit");
949
950 std::string value{};
951 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
952 EXPECT_FALSE(value.empty());
953 const int ival = std::stoi(value);
954 EXPECT_GT(ival, 0);
955 // Try doubling the parameter value (always best!).
956 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
957 .isOk());
958 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
959 EXPECT_EQ(2 * ival, std::stoi(value));
960 // Try resetting the parameter.
961 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
962 .isOk());
963 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
964 EXPECT_EQ(ival, std::stoi(value));
965}
966
Ben Schwartze7601812017-04-28 16:38:29 -0400967static std::string base64Encode(const std::vector<uint8_t>& input) {
968 size_t out_len;
969 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
970 // out_len includes the trailing NULL.
971 uint8_t output_bytes[out_len];
972 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
973 return std::string(reinterpret_cast<char*>(output_bytes));
974}
975
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900976TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900977 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400978 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400979 std::vector<uint8_t> short_fp(1);
980 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
981 std::vector<std::string> test_domains;
982 std::vector<int> test_params = { 300, 25, 8, 8 };
983 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400984 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400985 const std::vector<std::string> servers;
986 const std::string tlsName;
987 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400988 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900989 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400990 { {"192.0.2.1"}, "", {}, 0 },
991 { {"2001:db8::2"}, "host.name", {}, 0 },
992 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
993 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900994 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400995 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900996 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400997 { {"2001:dg8::6"}, "", {}, EINVAL },
998 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
999 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
1000 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
1001 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -04001002 };
1003
Luke Huangc3252cc2018-10-16 15:43:23 +08001004 for (unsigned int i = 0; i < std::size(kTlsTestData); i++) {
Erik Klinea1476fb2018-03-04 21:01:56 +09001005 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -04001006
1007 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001008 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -04001009 fingerprints.push_back(base64Encode(fingerprint));
1010 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001011 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001012 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
1013 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -04001014
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001015 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -04001016 SCOPED_TRACE(String8::format("test case %d should have passed", i));
1017 SCOPED_TRACE(status.toString8());
1018 EXPECT_EQ(0, status.exceptionCode());
1019 } else {
1020 SCOPED_TRACE(String8::format("test case %d should have failed", i));
1021 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001022 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -04001023 }
Ben Schwartze7601812017-04-28 16:38:29 -04001024 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001025 // Ensure TLS is disabled before the start of the next test.
1026 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001027 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1028 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001029}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001030
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001031namespace {
1032
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001033void expectNoTestCounterRules() {
1034 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1035 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1036 std::string allRules = Join(runCommand(command), "\n");
1037 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1038 }
1039}
1040
Bernie Innocentif6918262018-06-11 17:37:35 +09001041void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1042 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001043 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1044 path, if1.c_str(), if2.c_str(), pkt, byte));
1045}
1046
Bernie Innocentif6918262018-06-11 17:37:35 +09001047void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001048 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1049 path, if1.c_str(), if2.c_str()));
1050 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1051 path, if2.c_str(), if1.c_str()));
1052}
1053
Luke Huangcaebcbb2018-09-27 20:37:14 +08001054std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1055 const std::string& iface) {
1056 for (auto& stats : statsVec) {
1057 if (stats.iface == iface) {
1058 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1059 }
1060 }
1061 return {};
1062}
1063
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001064} // namespace
1065
1066TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001067 expectNoTestCounterRules();
1068
1069 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1070 // disabling tethering. We don't check the return value because these commands will fail if
1071 // tethering is already enabled.
1072 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1073 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1074
1075 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1076 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1077 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1078 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1079 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1080
1081 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1082 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1083 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1084 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1085 // RX is from external to internal, and TX is from internal to external.
1086 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1087 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1088
1089 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1090 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1091
1092 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1093 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1094
1095 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1096 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1097 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1098
Luke Huangcaebcbb2018-09-27 20:37:14 +08001099 std::vector<TetherStatsParcel> statsVec;
1100 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001101 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1102
Luke Huangcaebcbb2018-09-27 20:37:14 +08001103 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001104
Luke Huangcaebcbb2018-09-27 20:37:14 +08001105 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001106
1107 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1108 delTetherCounterValues(path, intIface1, extIface1);
1109 delTetherCounterValues(path, intIface2, extIface2);
1110 if (path == IP6TABLES_PATH) {
1111 delTetherCounterValues(path, intIface3, extIface2);
1112 }
1113 }
1114
1115 expectNoTestCounterRules();
1116}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001117
Luke Huang0051a622018-07-23 20:30:16 +08001118namespace {
1119
Luke Huanga5211072018-08-01 23:36:29 +08001120constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1121constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001122
1123static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1124 const char* chainName) {
1125 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1126 return runCommand(command);
1127}
1128
Luke Huang19b49c52018-10-22 12:12:05 +09001129// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001130bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001131 const std::string& expectedInterface,
1132 const std::string& expectedRule, const char* table) {
1133 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1134 for (const auto& rule : rules) {
1135 if (rule.find(expectedInterface) != std::string::npos) {
1136 if (rule.find(expectedRule) != std::string::npos) {
1137 return true;
1138 }
1139 }
1140 }
1141 return false;
1142}
1143
1144void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001145 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001146 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001147 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001148 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001149 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1150 IdletimerRule, RAW_TABLE));
1151 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001152 ifname, IdletimerRule, MANGLE_TABLE));
1153 }
1154}
1155
1156void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001157 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001158 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001159 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001160 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001161 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1162 IdletimerRule, RAW_TABLE));
1163 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001164 ifname, IdletimerRule, MANGLE_TABLE));
1165 }
1166}
1167
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001168} // namespace
1169
1170TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001171 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1172 // rule in the table. Because we only check the result after calling remove function. We might
1173 // check the actual rule which is removed by our function (maybe compare the results between
1174 // calling function before and after)
1175 binder::Status status;
1176 const struct TestData {
1177 const std::string ifname;
1178 int32_t timeout;
1179 const std::string classLabel;
1180 } idleTestData[] = {
1181 {"wlan0", 1234, "happyday"},
1182 {"rmnet_data0", 4567, "friday"},
1183 };
1184 for (const auto& td : idleTestData) {
1185 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1186 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1187 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1188
1189 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1190 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1191 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1192 }
1193}
1194
Luke Huanga67dd562018-07-17 19:58:25 +08001195namespace {
1196
1197constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1198constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1199
1200void expectStrictSetUidAccept(const int uid) {
1201 std::string uidRule = StringPrintf("owner UID match %u", uid);
1202 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1203 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1204 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1205 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1206 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1207 }
1208}
1209
1210void expectStrictSetUidLog(const int uid) {
1211 static const char logRule[] = "st_penalty_log all";
1212 std::string uidRule = StringPrintf("owner UID match %u", uid);
1213 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1214 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1215 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1216 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1217 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1218 }
1219}
1220
1221void expectStrictSetUidReject(const int uid) {
1222 static const char rejectRule[] = "st_penalty_reject all";
1223 std::string uidRule = StringPrintf("owner UID match %u", uid);
1224 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1225 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1226 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1227 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1228 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1229 }
1230}
1231
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001232} // namespace
1233
1234TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001235 binder::Status status;
1236 int32_t uid = randomUid();
1237
1238 // setUidCleartextPenalty Policy:Log with randomUid
1239 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1240 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1241 expectStrictSetUidLog(uid);
1242
1243 // setUidCleartextPenalty Policy:Accept with randomUid
1244 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1245 expectStrictSetUidAccept(uid);
1246
1247 // setUidCleartextPenalty Policy:Reject with randomUid
1248 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1249 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1250 expectStrictSetUidReject(uid);
1251
1252 // setUidCleartextPenalty Policy:Accept with randomUid
1253 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1254 expectStrictSetUidAccept(uid);
1255
1256 // test wrong policy
1257 int32_t wrongPolicy = -123;
1258 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1259 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1260}
1261
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001262namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001263
Luke Huanga5211072018-08-01 23:36:29 +08001264bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001265 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1266 return (runCommand(cmd.c_str()).size()) ? true : false;
1267}
1268
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001269} // namespace
1270
1271TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001272 binder::Status status;
1273 // use dummy0 for test since it is set ready
1274 static const char testIf[] = "dummy0";
1275 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1276
1277 status = mNetd->clatdStart(testIf);
1278 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1279 EXPECT_TRUE(processExists(clatdName));
1280
1281 mNetd->clatdStop(testIf);
1282 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1283 EXPECT_FALSE(processExists(clatdName));
1284}
Luke Huang457d4702018-08-16 15:39:15 +08001285
1286namespace {
1287
1288bool getIpfwdV4Enable() {
1289 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1290 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1291 EXPECT_TRUE(!result.empty());
1292 int v4Enable = std::stoi(result[0]);
1293 return v4Enable;
1294}
1295
1296bool getIpfwdV6Enable() {
1297 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1298 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1299 EXPECT_TRUE(!result.empty());
1300 int v6Enable = std::stoi(result[0]);
1301 return v6Enable;
1302}
1303
1304void expectIpfwdEnable(bool enable) {
1305 int enableIPv4 = getIpfwdV4Enable();
1306 int enableIPv6 = getIpfwdV6Enable();
1307 EXPECT_EQ(enable, enableIPv4);
1308 EXPECT_EQ(enable, enableIPv6);
1309}
1310
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001311bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001312 std::vector<std::string> rules = listIpRules(ipVersion);
1313 for (const auto& rule : rules) {
1314 if (rule.find(ipfwdRule) != std::string::npos) {
1315 return true;
1316 }
1317 }
1318 return false;
1319}
1320
1321void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1322 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1323
1324 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1325 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1326 }
1327}
1328
1329void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1330 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1331
1332 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1333 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1334 }
1335}
1336
1337} // namespace
1338
1339TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1340 // Netd default enable Ipfwd with requester NetdHwService
1341 const std::string defaultRequester = "NetdHwService";
1342
1343 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1344 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1345 expectIpfwdEnable(false);
1346
1347 bool ipfwdEnabled;
1348 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1349 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1350 EXPECT_FALSE(ipfwdEnabled);
1351
1352 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1353 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1354 expectIpfwdEnable(true);
1355
1356 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1357 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1358 EXPECT_TRUE(ipfwdEnabled);
1359}
1360
1361TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1362 static const char testFromIf[] = "dummy0";
1363 static const char testToIf[] = "dummy0";
1364
1365 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1366 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1367 expectIpfwdRuleExists(testFromIf, testToIf);
1368
1369 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1370 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1371 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001372}
Luke Huang531f5d32018-08-03 15:19:05 +08001373
1374namespace {
1375
1376constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1377constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1378constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1379constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1380constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001381constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001382
Luke Huang19b49c52018-10-22 12:12:05 +09001383// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1384// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001385bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1386 const char* chainName, const std::string& expectedTargetA,
1387 const std::string& expectedTargetB) {
1388 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1389 int matchCount = 0;
1390
1391 for (const auto& rule : rules) {
1392 if (rule.find(expectedTargetA) != std::string::npos) {
1393 if (rule.find(expectedTargetB) != std::string::npos) {
1394 matchCount++;
1395 }
1396 }
1397 }
1398 return matchCount == expectedCount;
1399}
1400
1401void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1402 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1403 std::string result = "";
1404
1405 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001406 // Quota value might be decreased while matching packets
1407 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001408}
1409
1410void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1411 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1412 std::string quotaRule = StringPrintf("quota %s", ifname);
1413
1414 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1415 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1416 BANDWIDTH_COSTLY_IF));
1417 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1418 BANDWIDTH_COSTLY_IF));
1419 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1420 BANDWIDTH_COSTLY_IF));
1421 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1422 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1423 }
1424 expectXtQuotaValueEqual(ifname, quotaBytes);
1425}
1426
1427void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1428 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1429 std::string quotaRule = StringPrintf("quota %s", ifname);
1430
1431 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1432 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1433 BANDWIDTH_COSTLY_IF));
1434 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1435 BANDWIDTH_COSTLY_IF));
1436 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1437 BANDWIDTH_COSTLY_IF));
1438 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1439 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1440 }
1441}
1442
1443void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1444 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1445 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1446 std::string alertName = StringPrintf("%sAlert", ifname);
1447
1448 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1449 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1450 }
1451 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1452}
1453
1454void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1455 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1456 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1457
1458 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1459 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1460 }
1461}
1462
1463void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1464 static const char globalAlertRule[] = "quota globalAlert";
1465 static const char globalAlertName[] = "globalAlert";
1466
1467 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001468 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001469 }
1470 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1471}
1472
1473void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1474 std::string uidRule = StringPrintf("owner UID match %u", uid);
1475
1476 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1477 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1478 }
1479}
1480
1481void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1482 std::string uidRule = StringPrintf("owner UID match %u", uid);
1483
1484 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1485 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1486 }
1487}
1488
1489} // namespace
1490
1491TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1492 long testQuotaBytes = 5550;
1493
1494 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001495 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001496 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1497
1498 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1499 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1500 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1501
1502 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1503 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1504 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1505
1506 // Remove test physical network
1507 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1508}
1509
1510TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1511 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001512 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001513 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001514 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001515 // Need to have a prior interface quota set to set an alert
1516 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1517 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1518 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1519 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1520
1521 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1522 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1523 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1524
1525 // Remove interface quota
1526 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1527 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1528 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1529
1530 // Remove test physical network
1531 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1532}
1533
1534TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1535 long testAlertBytes = 2097149;
1536
1537 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1538 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1539 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1540
1541 testAlertBytes = 2097152;
1542 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1543 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1544 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1545}
1546
1547TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1548 SKIP_IF_BPF_SUPPORTED;
1549
1550 int32_t uid = randomUid();
1551 static const char targetReject[] = "REJECT";
1552 static const char targetReturn[] = "RETURN";
1553
1554 // add NaughtyApp
1555 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1556 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1557 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1558
1559 // remove NaughtyApp
1560 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1561 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1562 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1563
1564 // add NiceApp
1565 status = mNetd->bandwidthAddNiceApp(uid);
1566 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1567 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1568
1569 // remove NiceApp
1570 status = mNetd->bandwidthRemoveNiceApp(uid);
1571 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1572 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1573}
Luke Huangb5733d72018-08-21 17:17:19 +08001574
1575namespace {
1576
Luke Huangb670d162018-08-23 20:01:13 +08001577std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1578 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1579 return runCommand(command);
1580}
1581
Luke Huangc3252cc2018-10-16 15:43:23 +08001582bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001583 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1584 for (const auto& route : routes) {
1585 if (route.find(ipRoute) != std::string::npos) {
1586 return true;
1587 }
1588 }
1589 return false;
1590}
1591
Luke Huangc3252cc2018-10-16 15:43:23 +08001592std::string ipRouteString(const std::string& ifName, const std::string& dst,
1593 const std::string& nextHop) {
1594 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1595
1596 if (!nextHop.empty()) {
1597 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001598 }
1599
Luke Huangc3252cc2018-10-16 15:43:23 +08001600 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001601}
1602
Luke Huangc3252cc2018-10-16 15:43:23 +08001603void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1604 const std::string& dst, const std::string& nextHop,
1605 const char* table) {
1606 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1607}
1608
1609void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001610 const std::string& dst, const std::string& nextHop,
1611 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001612 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001613}
1614
1615bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1616 std::vector<std::string> rules = listIpRules(ipVersion);
1617 for (const auto& rule : rules) {
1618 if (rule.find(ipRule) != std::string::npos) {
1619 return true;
1620 }
1621 }
1622 return false;
1623}
1624
1625void expectNetworkDefaultIpRuleExists(const char* ifName) {
1626 std::string networkDefaultRule =
1627 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1628
1629 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1630 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1631 }
1632}
1633
1634void expectNetworkDefaultIpRuleDoesNotExist() {
1635 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1636
1637 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1638 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1639 }
1640}
1641
1642void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1643 std::string networkPermissionRule = "";
1644 switch (permission) {
1645 case INetd::PERMISSION_NONE:
1646 networkPermissionRule = StringPrintf(
1647 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1648 break;
1649 case INetd::PERMISSION_NETWORK:
1650 networkPermissionRule = StringPrintf(
1651 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1652 break;
1653 case INetd::PERMISSION_SYSTEM:
1654 networkPermissionRule = StringPrintf(
1655 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1656 break;
1657 }
1658
1659 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1660 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1661 }
1662}
1663
1664// TODO: It is a duplicate function, need to remove it
1665bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1666 const std::string& expectedInterface,
1667 const std::string& expectedRule,
1668 const char* table) {
1669 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1670 for (const auto& rule : rules) {
1671 if (rule.find(expectedInterface) != std::string::npos) {
1672 if (rule.find(expectedRule) != std::string::npos) {
1673 return true;
1674 }
1675 }
1676 }
1677 return false;
1678}
1679
1680void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1681 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1682 std::string networkIncomingPacketMarkRule = "";
1683 switch (permission) {
1684 case INetd::PERMISSION_NONE:
1685 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1686 break;
1687 case INetd::PERMISSION_NETWORK:
1688 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1689 break;
1690 case INetd::PERMISSION_SYSTEM:
1691 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1692 break;
1693 }
1694
1695 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1696 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1697 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1698 }
1699}
1700
1701} // namespace
1702
1703TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001704 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001705 const char* ipVersion;
1706 const char* testDest;
1707 const char* testNextHop;
1708 const bool expectSuccess;
1709 } kTestData[] = {
1710 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001711 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1712 {IP_RULE_V4, "10.251.0.0/16", "", true},
1713 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1714 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001715 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001716 {IP_RULE_V6, "::/0", "2001:db8::", true},
1717 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001718 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1719 };
1720
Luke Huangc3252cc2018-10-16 15:43:23 +08001721 static const struct {
1722 const char* ipVersion;
1723 const char* testDest;
1724 const char* testNextHop;
1725 } kTestDataWithNextHop[] = {
1726 {IP_RULE_V4, "10.251.10.0/30", ""},
1727 {IP_RULE_V6, "2001:db8::/32", ""},
1728 };
1729
Luke Huangb670d162018-08-23 20:01:13 +08001730 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001731 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001732 const int testUid = randomUid();
1733 const std::vector<int32_t> testUids = {testUid};
1734
1735 // Add test physical network
1736 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1737 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1738
Luke Huangc3252cc2018-10-16 15:43:23 +08001739 // Setup route for testing nextHop
1740 for (unsigned int i = 0; i < std::size(kTestDataWithNextHop); i++) {
1741 const auto& td = kTestDataWithNextHop[i];
1742
1743 // All route for test tun will disappear once the tun interface is deleted.
1744 binder::Status status =
1745 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1746 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1747 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1748 sTun.name().c_str());
1749
1750 // Add system permission for test uid, setup route in legacy system table.
1751 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1752
1753 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1754 testUid);
1755 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1756 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1757 testTableLegacySystem);
1758
1759 // Remove system permission for test uid, setup route in legacy network table.
1760 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1761
1762 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1763 testUid);
1764 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1765 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1766 testTableLegacyNetwork);
1767 }
1768
1769 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001770 const auto& td = kTestData[i];
1771
1772 binder::Status status =
1773 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1774 if (td.expectSuccess) {
1775 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001776 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001777 sTun.name().c_str());
1778 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001779 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1780 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001781 }
1782
1783 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1784 if (td.expectSuccess) {
1785 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001786 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1787 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001788 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001789 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1790 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001791 }
1792
Luke Huangc3252cc2018-10-16 15:43:23 +08001793 // Add system permission for test uid, route will be added into legacy system table.
1794 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001795
1796 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1797 testUid);
1798 if (td.expectSuccess) {
1799 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001800 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001801 testTableLegacySystem);
1802 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001803 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1804 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001805 }
1806
1807 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1808 td.testNextHop, testUid);
1809 if (td.expectSuccess) {
1810 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001811 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1812 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001813 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001814 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1815 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001816 }
1817
Luke Huangc3252cc2018-10-16 15:43:23 +08001818 // Remove system permission for test uid, route will be added into legacy network table.
1819 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1820
1821 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1822 testUid);
1823 if (td.expectSuccess) {
1824 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1825 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1826 testTableLegacyNetwork);
1827 } else {
1828 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1829 EXPECT_NE(0, status.serviceSpecificErrorCode());
1830 }
1831
1832 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1833 td.testNextHop, testUid);
1834 if (td.expectSuccess) {
1835 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1836 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1837 testTableLegacyNetwork);
1838 } else {
1839 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1840 EXPECT_NE(0, status.serviceSpecificErrorCode());
1841 }
Luke Huangb670d162018-08-23 20:01:13 +08001842 }
1843
1844 // Remove test physical network
1845 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1846}
1847
1848TEST_F(BinderTest, NetworkPermissionDefault) {
1849 // Add test physical network
1850 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1851 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1852
Luke Huangc3252cc2018-10-16 15:43:23 +08001853 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001854 int currentNetid;
1855 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1856 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1857
1858 // Test SetDefault
1859 status = mNetd->networkSetDefault(TEST_NETID1);
1860 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1861 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1862
1863 status = mNetd->networkClearDefault();
1864 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1865 expectNetworkDefaultIpRuleDoesNotExist();
1866
1867 // Add default network back
1868 status = mNetd->networkSetDefault(currentNetid);
1869 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1870
1871 // Test SetPermission
1872 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1873 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1874 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1875 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1876
1877 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1878 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1879 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1880 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1881
1882 // Remove test physical network
1883 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1884}
1885
1886TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1887 const int testUid = randomUid();
1888 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1889 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1890 bool ret = false;
1891 status = mNetd->networkCanProtect(testUid, &ret);
1892 EXPECT_TRUE(ret);
1893
1894 status = mNetd->networkSetProtectDeny(testUid);
1895 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1896 status = mNetd->networkCanProtect(testUid, &ret);
1897 EXPECT_FALSE(ret);
1898}
1899
1900namespace {
1901
Luke Huangb5733d72018-08-21 17:17:19 +08001902int readIntFromPath(const std::string& path) {
1903 std::string result = "";
1904 EXPECT_TRUE(ReadFileToString(path, &result));
1905 return std::stoi(result);
1906}
1907
1908int getTetherAcceptIPv6Ra(const std::string& ifName) {
1909 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1910 return readIntFromPath(path);
1911}
1912
1913bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1914 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1915 return readIntFromPath(path);
1916}
1917
1918int getTetherIPv6DadTransmits(const std::string& ifName) {
1919 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1920 return readIntFromPath(path);
1921}
1922
1923bool getTetherEnableIPv6(const std::string& ifName) {
1924 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1925 int disableIPv6 = readIntFromPath(path);
1926 return !disableIPv6;
1927}
1928
1929bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1930 for (const auto& iface : ifList) {
1931 if (iface == ifName) {
1932 return true;
1933 }
1934 }
1935 return false;
1936}
1937
1938void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1939 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1940 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1941 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1942 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1943}
1944
1945void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1946 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1947 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1948 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1949 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1950}
1951
1952void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1953 const std::string& ifName) {
1954 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1955}
1956
1957void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1958 const std::string& ifName) {
1959 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1960}
1961
1962void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
1963 const std::vector<std::string>& testDnsAddrs) {
1964 EXPECT_TRUE(dnsList == testDnsAddrs);
1965}
1966
1967} // namespace
1968
1969TEST_F(BinderTest, TetherStartStopStatus) {
1970 std::vector<std::string> noDhcpRange = {};
1971 static const char dnsdName[] = "dnsmasq";
1972
1973 binder::Status status = mNetd->tetherStart(noDhcpRange);
1974 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1975 EXPECT_TRUE(processExists(dnsdName));
1976
1977 bool tetherEnabled;
1978 status = mNetd->tetherIsEnabled(&tetherEnabled);
1979 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1980 EXPECT_TRUE(tetherEnabled);
1981
1982 status = mNetd->tetherStop();
1983 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1984 EXPECT_FALSE(processExists(dnsdName));
1985
1986 status = mNetd->tetherIsEnabled(&tetherEnabled);
1987 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1988 EXPECT_FALSE(tetherEnabled);
1989}
1990
1991TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
1992 // TODO: verify if dnsmasq update interface successfully
1993
1994 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
1995 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1996 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
1997
1998 std::vector<std::string> ifList;
1999 status = mNetd->tetherInterfaceList(&ifList);
2000 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2001 expectTetherInterfaceExists(ifList, sTun.name());
2002
2003 status = mNetd->tetherInterfaceRemove(sTun.name());
2004 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2005 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2006
2007 status = mNetd->tetherInterfaceList(&ifList);
2008 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2009 expectTetherInterfaceNotExists(ifList, sTun.name());
2010}
2011
2012TEST_F(BinderTest, TetherDnsSetList) {
2013 // TODO: verify if dnsmasq update dns successfully
2014 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
2015
2016 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2017 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2018
2019 std::vector<std::string> dnsList;
2020 status = mNetd->tetherDnsList(&dnsList);
2021 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2022 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002023}
2024
2025namespace {
2026
2027constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2028constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2029constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2030constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2031constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2032constexpr char FIREWALL_STANDBY[] = "fw_standby";
2033constexpr char targetReturn[] = "RETURN";
2034constexpr char targetDrop[] = "DROP";
2035
2036void expectFirewallWhitelistMode() {
2037 static const char dropRule[] = "DROP all";
2038 static const char rejectRule[] = "REJECT all";
2039 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2040 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2041 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2042 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2043 }
2044}
2045
2046void expectFirewallBlacklistMode() {
2047 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2048 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2049 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2050 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2051 }
2052}
2053
2054bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2055 const std::string& expectedInterface,
2056 const std::string& expectedRule) {
2057 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2058 // Expected rule:
2059 // Chain fw_INPUT (1 references)
2060 // pkts bytes target prot opt in out source destination
2061 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2062 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2063 int firstRuleIndex = 2;
2064 if (rules.size() < 4) return false;
2065 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2066 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2067 return true;
2068 }
2069 }
2070 return false;
2071}
2072
2073// TODO: It is a duplicate function, need to remove it
2074bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2075 const std::string& expectedInterface,
2076 const std::string& expectedRule) {
2077 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2078 for (const auto& rule : rules) {
2079 if (rule.find(expectedInterface) != std::string::npos) {
2080 if (rule.find(expectedRule) != std::string::npos) {
2081 return true;
2082 }
2083 }
2084 }
2085 return false;
2086}
2087
2088void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2089 static const char returnRule[] = "RETURN all";
2090 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2091 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2092 returnRule));
2093 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2094 returnRule));
2095 }
2096}
2097
2098void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2099 static const char returnRule[] = "RETURN all";
2100 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2101 EXPECT_FALSE(
2102 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2103 EXPECT_FALSE(
2104 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2105 }
2106}
2107
2108bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2109 const std::string& expectedTarget,
2110 const std::string& expectedRule) {
2111 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2112 int firstRuleIndex = 2;
2113 if (rules.size() < 4) return false;
2114 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2115 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2116 return true;
2117 }
2118 }
2119 return false;
2120}
2121
2122bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2123 const std::string& expectedTarget,
2124 const std::string& expectedRule) {
2125 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2126 int lastRuleIndex = rules.size() - 1;
2127 if (lastRuleIndex < 0) return false;
2128 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2129 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2130 return true;
2131 }
2132 }
2133 return false;
2134}
2135
2136void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2137 std::string uidRule = StringPrintf("owner UID match %u", uid);
2138 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2139 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2140}
2141
2142void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2143 std::string uidRule = StringPrintf("owner UID match %u", uid);
2144 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2145 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2146}
2147
2148void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2149 std::string uidRule = StringPrintf("owner UID match %u", uid);
2150 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2151 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2152}
2153
2154void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2155 std::string uidRule = StringPrintf("owner UID match %u", uid);
2156 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2157 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2158}
2159
2160bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2161 std::vector<std::string> inputRules =
2162 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2163 std::vector<std::string> outputRules =
2164 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2165 int inputLastRuleIndex = inputRules.size() - 1;
2166 int outputLastRuleIndex = outputRules.size() - 1;
2167
2168 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2169 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2170 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2171 return true;
2172 }
2173 }
2174 return false;
2175}
2176
2177void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2178 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2179 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2180}
2181
2182void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2183 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2184 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2185 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2186 }
2187}
2188
2189} // namespace
2190
2191TEST_F(BinderTest, FirewallSetFirewallType) {
2192 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2193 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2194 expectFirewallWhitelistMode();
2195
2196 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2197 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2198 expectFirewallBlacklistMode();
2199
2200 // set firewall type blacklist twice
2201 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2202 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2203 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2204 expectFirewallBlacklistMode();
2205
2206 // set firewall type whitelist twice
2207 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2208 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2209 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2210 expectFirewallWhitelistMode();
2211
2212 // reset firewall type to default
2213 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2214 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2215 expectFirewallBlacklistMode();
2216}
2217
2218TEST_F(BinderTest, FirewallSetInterfaceRule) {
2219 // setinterfaceRule is not supported in BLACKLIST MODE
2220 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2221 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2222
2223 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2224 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2225
2226 // set WHITELIST mode first
2227 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2228 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2229
2230 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2231 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2232 expectFirewallInterfaceRuleAllowExists(sTun.name());
2233
2234 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2235 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2236 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2237
2238 // reset firewall mode to default
2239 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2240 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2241 expectFirewallBlacklistMode();
2242}
2243
2244TEST_F(BinderTest, FirewallSetUidRule) {
2245 SKIP_IF_BPF_SUPPORTED;
2246
2247 int32_t uid = randomUid();
2248
2249 // Doze allow
2250 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2251 INetd::FIREWALL_RULE_ALLOW);
2252 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2253 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2254
2255 // Doze deny
2256 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2257 INetd::FIREWALL_RULE_DENY);
2258 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2259 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2260
2261 // Powersave allow
2262 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2263 INetd::FIREWALL_RULE_ALLOW);
2264 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2265 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2266
2267 // Powersave deny
2268 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2269 INetd::FIREWALL_RULE_DENY);
2270 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2271 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2272
2273 // Standby deny
2274 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2275 INetd::FIREWALL_RULE_DENY);
2276 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2277 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2278
2279 // Standby allow
2280 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2281 INetd::FIREWALL_RULE_ALLOW);
2282 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2283 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2284
2285 // None deny in BLACKLIST
2286 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2287 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2288 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2289 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2290
2291 // None allow in BLACKLIST
2292 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2293 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2294 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2295 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2296
2297 // set firewall type whitelist twice
2298 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2299 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2300 expectFirewallWhitelistMode();
2301
2302 // None allow in WHITELIST
2303 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2304 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2305 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2306 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2307
2308 // None deny in WHITELIST
2309 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2310 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2311 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2312 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2313
2314 // reset firewall mode to default
2315 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2316 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2317 expectFirewallBlacklistMode();
2318}
2319
2320TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2321 SKIP_IF_BPF_SUPPORTED;
2322
2323 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2324 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2325 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2326
2327 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2328 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2329 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2330
2331 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2332 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2333 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2334
2335 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2336 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2337 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2338
2339 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2340 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2341 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2342
2343 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2344 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2345 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2346}
Luke Huangf7782042018-08-08 13:13:04 +08002347
2348namespace {
2349
2350std::string hwAddrToStr(unsigned char* hwaddr) {
2351 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2352 hwaddr[4], hwaddr[5]);
2353}
2354
2355int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2356 int prefixLength = 0;
2357 uint32_t m = ntohl(mask);
2358 while (m & (1 << 31)) {
2359 prefixLength++;
2360 m = m << 1;
2361 }
2362 return prefixLength;
2363}
2364
2365std::string toStdString(const String16& s) {
2366 return std::string(String8(s.string()));
2367}
2368
2369android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2370 const auto& sys = sSyscalls.get();
2371 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2372 EXPECT_TRUE(isOk(fd.status()));
2373
2374 struct ifreq ifr = {};
2375 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2376
2377 return sys.ioctl(fd.value(), flag, &ifr);
2378}
2379
2380std::string getInterfaceHwAddr(const std::string& ifName) {
2381 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2382
2383 unsigned char hwaddr[ETH_ALEN] = {};
2384 if (isOk(res.status())) {
2385 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2386 }
2387
2388 return hwAddrToStr(hwaddr);
2389}
2390
2391int getInterfaceIPv4Prefix(const std::string& ifName) {
2392 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2393
2394 int prefixLength = 0;
2395 if (isOk(res.status())) {
2396 prefixLength = ipv4NetmaskToPrefixLength(
2397 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2398 }
2399
2400 return prefixLength;
2401}
2402
2403std::string getInterfaceIPv4Addr(const std::string& ifName) {
2404 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2405
2406 struct in_addr addr = {};
2407 if (isOk(res.status())) {
2408 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2409 }
2410
2411 return std::string(inet_ntoa(addr));
2412}
2413
2414std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2415 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2416
2417 unsigned flags = 0;
2418 if (isOk(res.status())) {
2419 flags = res.value().ifr_flags;
2420 }
2421
2422 std::vector<std::string> ifFlags;
2423 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2424 : toStdString(INetd::IF_STATE_DOWN()));
2425
2426 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2427 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2428 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2429 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2430 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2431
2432 return ifFlags;
2433}
2434
2435bool compareListInterface(const std::vector<std::string>& interfaceList) {
2436 const auto& res = InterfaceController::getIfaceNames();
2437 EXPECT_TRUE(isOk(res));
2438
2439 std::vector<std::string> resIfList;
2440 resIfList.reserve(res.value().size());
2441 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2442
2443 return resIfList == interfaceList;
2444}
2445
2446int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2447 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2448 return readIntFromPath(path);
2449}
2450
2451bool getInterfaceEnableIPv6(const std::string& ifName) {
2452 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2453
2454 int disableIPv6 = readIntFromPath(path);
2455 return !disableIPv6;
2456}
2457
2458int getInterfaceMtu(const std::string& ifName) {
2459 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2460 return readIntFromPath(path);
2461}
2462
2463void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2464 EXPECT_TRUE(compareListInterface(interfaceList));
2465}
2466
2467void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2468 const InterfaceConfigurationParcel& interfaceCfg) {
2469 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2470 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2471 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2472 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2473}
2474
2475void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2476 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2477 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2478
2479 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2480 for (const auto& flag : setCfg.flags) {
2481 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2482 }
2483}
2484
2485void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2486 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2487 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2488}
2489
2490void expectInterfaceNoAddr(const std::string& ifName) {
2491 // noAddr
2492 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2493 // noPrefix
2494 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2495}
2496
2497void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2498 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2499 EXPECT_EQ(enableIPv6, enable);
2500}
2501
2502void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2503 int mtuSize = getInterfaceMtu(ifName);
2504 EXPECT_EQ(mtu, mtuSize);
2505}
2506
2507InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2508 const std::string& addr, int prefixLength,
2509 const std::vector<std::string>& flags) {
2510 InterfaceConfigurationParcel cfg;
2511 cfg.ifName = ifName;
2512 cfg.hwAddr = "";
2513 cfg.ipv4Addr = addr;
2514 cfg.prefixLength = prefixLength;
2515 cfg.flags = flags;
2516 return cfg;
2517}
2518
2519void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2520 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2521 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2522
2523 for (const auto& flag : expectedFlags) {
2524 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2525 interfaceCfg.flags.end());
2526 }
2527
2528 for (const auto& flag : unexpectedFlags) {
2529 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2530 interfaceCfg.flags.end());
2531 }
2532}
2533
2534} // namespace
2535
2536TEST_F(BinderTest, InterfaceList) {
2537 std::vector<std::string> interfaceListResult;
2538
2539 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2540 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2541 expectInterfaceList(interfaceListResult);
2542}
2543
2544TEST_F(BinderTest, InterfaceGetCfg) {
2545 InterfaceConfigurationParcel interfaceCfgResult;
2546
2547 // Add test physical network
2548 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2549 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2550
2551 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2552 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2553 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2554 expectTunFlags(interfaceCfgResult);
2555
2556 // Remove test physical network
2557 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2558}
2559
2560TEST_F(BinderTest, InterfaceSetCfg) {
2561 const std::string testAddr = "192.0.2.3";
2562 const int testPrefixLength = 24;
2563 std::vector<std::string> upFlags = {"up"};
2564 std::vector<std::string> downFlags = {"down"};
2565
2566 // Add test physical network
2567 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2568 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2569
2570 // Set tun interface down.
2571 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2572 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2573 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2574 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2575
2576 // Set tun interface up again.
2577 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2578 status = mNetd->interfaceSetCfg(interfaceCfg);
2579 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2580 status = mNetd->interfaceClearAddrs(sTun.name());
2581 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2582
2583 // Remove test physical network
2584 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2585}
2586
2587TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2588 // enable
2589 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2590 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2591 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2592
2593 // disable
2594 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2595 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2596 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2597}
2598
2599TEST_F(BinderTest, InterfaceClearAddr) {
2600 const std::string testAddr = "192.0.2.3";
2601 const int testPrefixLength = 24;
2602 std::vector<std::string> noFlags{};
2603
2604 // Add test physical network
2605 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2606 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2607
2608 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2609 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2610 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2611 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2612
2613 status = mNetd->interfaceClearAddrs(sTun.name());
2614 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2615 expectInterfaceNoAddr(sTun.name());
2616
2617 // Remove test physical network
2618 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2619}
2620
2621TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2622 // Add test physical network
2623 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2624 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2625
2626 // disable
2627 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2628 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2629 expectInterfaceEnableIPv6(sTun.name(), false);
2630
2631 // enable
2632 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2633 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2634 expectInterfaceEnableIPv6(sTun.name(), true);
2635
2636 // Remove test physical network
2637 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2638}
2639
2640TEST_F(BinderTest, InterfaceSetMtu) {
2641 const int testMtu = 1200;
2642
2643 // Add test physical network
2644 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2645 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2646
2647 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2648 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2649 expectInterfaceMtu(sTun.name(), testMtu);
2650
2651 // Remove test physical network
2652 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2653}
Luke Huang19b49c52018-10-22 12:12:05 +09002654
2655namespace {
2656
2657constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2658constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002659constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002660constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2661
Luke Huangae038f82018-11-05 11:17:31 +09002662int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002663 return listIptablesRuleByTable(binary, table, chainName).size();
2664}
2665
2666bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2667 const std::vector<std::string>& targetVec) {
2668 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2669 if (targetVec.size() != rules.size() - 2) {
2670 return false;
2671 }
2672
2673 /*
Luke Huangae038f82018-11-05 11:17:31 +09002674 * Check that the rules match. Note that this function matches substrings, not entire rules,
2675 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002676 * Skip first two lines since rules start from third line.
2677 * Chain chainName (x references)
2678 * pkts bytes target prot opt in out source destination
2679 * ...
2680 */
2681 int rIndex = 2;
2682 for (const auto& target : targetVec) {
2683 if (rules[rIndex].find(target) == std::string::npos) {
2684 return false;
2685 }
2686 rIndex++;
2687 }
2688 return true;
2689}
2690
2691void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2692 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2693 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2694 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002695 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002696 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2697 "DROP"};
2698
2699 // V4
2700 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2701 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002702 EXPECT_TRUE(
2703 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002704 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2705
Luke Huangae038f82018-11-05 11:17:31 +09002706 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002707 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2708
2709 // V6
2710 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002711 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2712 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002713
2714 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2715 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2716 extIf));
2717 }
2718}
2719
2720void expectNatDisable() {
2721 // It is the default DROP rule with tethering disable.
2722 // Chain tetherctrl_FORWARD (1 references)
2723 // pkts bytes target prot opt in out source destination
2724 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2725 std::vector<std::string> forwardV4Match = {"DROP"};
2726 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2727
2728 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002729 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2730 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002731
Luke Huangae038f82018-11-05 11:17:31 +09002732 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2733 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002734
2735 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2736}
2737
2738} // namespace
2739
2740TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002741 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2742 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2743 expectNatEnable(sTun.name(), sTun2.name());
2744
2745 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2746 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2747 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002748}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002749
2750namespace {
2751
2752using TripleInt = std::array<int, 3>;
2753
2754TripleInt readProcFileToTripleInt(const std::string& path) {
2755 std::string valueString;
2756 int min, def, max;
2757 EXPECT_TRUE(ReadFileToString(path, &valueString));
2758 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2759 return {min, def, max};
2760}
2761
2762void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2763 std::string testRmemValues =
2764 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2765 std::string testWmemValues =
2766 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2767 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2768
2769 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2770 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2771
2772 for (int i = 0; i < 3; i++) {
2773 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2774 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2775 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2776 }
2777}
2778
2779} // namespace
2780
2781TEST_F(BinderTest, TcpBufferSet) {
2782 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2783 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2784 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2785 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2786
2787 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2788 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2789}