blob: a6a925702b30c0c0ebc8bc76c507c415f6362adf [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
Lorenzo Colitti755faa92016-07-27 22:10:49 +090027#include <fcntl.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090028#include <ifaddrs.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090029#include <netdb.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090030#include <sys/socket.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090031#include <sys/types.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090032#include <netinet/in.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090033#include <linux/if.h>
34#include <linux/if_tun.h>
Ben Schwartze7601812017-04-28 16:38:29 -040035#include <openssl/base64.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090036
Luke Huang531f5d32018-08-03 15:19:05 +080037#include <android-base/file.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090038#include <android-base/macros.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090039#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090040#include <android-base/strings.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070041#include <bpf/BpfUtils.h>
Robin Leeb8087362016-03-30 18:43:08 +010042#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090043#include <gtest/gtest.h>
44#include <logwrap/logwrap.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090045#include <netutils/ifc.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090046
Nathan Harold21299f72018-03-16 20:13:03 -070047#include "InterfaceController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090048#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090049#include "Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070050#include "XfrmController.h"
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090051#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090052#include "android/net/INetd.h"
Robin Leeb8087362016-03-30 18:43:08 +010053#include "android/net/UidRange.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090054#include "binder/IServiceManager.h"
Nathan Harold21299f72018-03-16 20:13:03 -070055#include "netdutils/Syscalls.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090056
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090057#define IP_PATH "/system/bin/ip"
58#define IP6TABLES_PATH "/system/bin/ip6tables"
59#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090060#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080061#define RAW_TABLE "raw"
62#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080063#define FILTER_TABLE "filter"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090064
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090065namespace binder = android::binder;
66namespace netdutils = android::netdutils;
67
68using android::IBinder;
69using android::IServiceManager;
70using android::sp;
71using android::String16;
72using android::String8;
73using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080074using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090075using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090076using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080077using android::base::Trim;
Chenbo Feng837ddfc2018-05-08 13:45:08 -070078using android::bpf::hasBpfSupport;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090079using android::net::INetd;
Luke Huangcaebcbb2018-09-27 20:37:14 +080080using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090081using android::net::TunInterface;
Robin Leeb8087362016-03-30 18:43:08 +010082using android::net::UidRange;
Nathan Harold21299f72018-03-16 20:13:03 -070083using android::net::XfrmController;
Robin Leeb8087362016-03-30 18:43:08 +010084
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090085#define SKIP_IF_BPF_SUPPORTED \
86 do { \
87 if (hasBpfSupport()) return; \
88 } while (0)
Chenbo Feng837ddfc2018-05-08 13:45:08 -070089
Robin Leeb8087362016-03-30 18:43:08 +010090static const char* IP_RULE_V4 = "-4";
91static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090092static const int TEST_NETID1 = 65501;
93static const int TEST_NETID2 = 65502;
94constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090095
Benedict Wongb2daefb2017-12-06 22:05:46 -080096static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
97static const std::string ESP_ALLOW_RULE("esp");
98
Lorenzo Colitti89faa342016-02-26 11:38:47 +090099class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900100 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900101 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900102 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900103 sp<IBinder> binder = sm->getService(String16("netd"));
104 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900105 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900106 }
107 }
108
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900109 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900110 ASSERT_NE(nullptr, mNetd.get());
111 }
112
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900113 void TearDown() override {
114 mNetd->networkDestroy(TEST_NETID1);
115 mNetd->networkDestroy(TEST_NETID2);
116 }
117
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900118 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700119
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900120 // Static because setting up the tun interface takes about 40ms.
121 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900122 ASSERT_EQ(0, sTun.init());
123 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900124 }
125
126 static void TearDownTestCase() {
127 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900128 sTun.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900129 }
130
131 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900132
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900133 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900134 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900135 static TunInterface sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900136};
137
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900138TunInterface BinderTest::sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900139
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900140class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900141 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700142 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900143 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900144 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900145 }
146
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900147 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900148 std::string mName;
149};
150
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900151TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900152 TimedOperation t("isAlive RPC");
153 bool isAlive = false;
154 mNetd->isAlive(&isAlive);
155 ASSERT_TRUE(isAlive);
156}
157
158static int randomUid() {
159 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
160}
161
Robin Leeb8087362016-03-30 18:43:08 +0100162static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900163 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900164 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
165 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900166 perror("popen");
167 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900168 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900169
170 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100171 size_t bufsize = 0;
172 ssize_t linelen = 0;
173 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900174 lines.push_back(std::string(line, linelen));
175 free(line);
176 line = nullptr;
177 }
178
179 pclose(f);
180 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900181}
182
Robin Leeb8087362016-03-30 18:43:08 +0100183static std::vector<std::string> listIpRules(const char *ipVersion) {
184 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
185 return runCommand(command);
186}
187
188static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900189 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100190 return runCommand(command);
191}
192
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900193static int iptablesRuleLineLength(const char *binary, const char *chainName) {
194 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900195}
196
Benedict Wongb2daefb2017-12-06 22:05:46 -0800197static bool iptablesRuleExists(const char *binary,
198 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900199 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800200 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900201 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800202 if(rule.find(expectedRule) != std::string::npos) {
203 return true;
204 }
205 }
206 return false;
207}
208
209static bool iptablesNoSocketAllowRuleExists(const char *chainName){
210 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
211 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
212}
213
214static bool iptablesEspAllowRuleExists(const char *chainName){
215 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
216 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
217}
218
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900219TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700220 SKIP_IF_BPF_SUPPORTED;
221
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900222 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
223 const int kNumUids = 500;
224 std::vector<int32_t> noUids(0);
225 std::vector<int32_t> uids(kNumUids);
226 for (int i = 0; i < kNumUids; i++) {
227 uids[i] = randomUid();
228 }
229
230 bool ret;
231 {
232 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900233 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900234 }
235 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800236 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
237 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
238 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
239 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900240 {
241 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900242 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900243 }
244 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900245 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
246 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900247
248 {
249 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900250 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900251 }
252 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900253 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
254 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800255 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
256 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900257
258 {
259 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900260 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900261 }
262 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900263 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
264 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900265
266 // Check that the call fails if iptables returns an error.
267 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900268 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900269 EXPECT_EQ(false, ret);
270}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900271
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900272TEST_F(BinderTest, VirtualTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700273 const struct TestData {
274 const std::string family;
275 const std::string deviceName;
276 const std::string localAddress;
277 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800278 int32_t iKey;
279 int32_t oKey;
280 } kTestData[] = {
Nathan Harold21299f72018-03-16 20:13:03 -0700281 {"IPV4", "test_vti", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53},
282 {"IPV6", "test_vti6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50},
manojboopathi8707f232018-01-02 14:45:47 -0800283 };
284
Luke Huangc3252cc2018-10-16 15:43:23 +0800285 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700286 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800287
288 binder::Status status;
289
290 // Create Virtual Tunnel Interface.
Nathan Harold21299f72018-03-16 20:13:03 -0700291 status = mNetd->addVirtualTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
292 td.iKey, td.oKey);
manojboopathi8707f232018-01-02 14:45:47 -0800293 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
294
295 // Update Virtual Tunnel Interface.
296 status = mNetd->updateVirtualTunnelInterface(td.deviceName, td.localAddress,
297 td.remoteAddress, td.iKey, td.oKey);
298 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
299
300 // Remove Virtual Tunnel Interface.
301 status = mNetd->removeVirtualTunnelInterface(td.deviceName);
302 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
303 }
304}
305
Nathan Harold2deff322018-05-10 14:03:48 -0700306// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
307// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
308#if INTPTR_MAX != INT32_MAX
Benedict Wonga04ffa72018-05-09 21:42:42 -0700309static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
310 static_cast<int>(android::net::XfrmDirection::OUT)};
311static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
312
Nathan Harold21299f72018-03-16 20:13:03 -0700313#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
314 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900315bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Nathan Harold21299f72018-03-16 20:13:03 -0700316 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
317 SCOPED_TRACE(status);
318 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
319
320 // Add a policy
Benedict Wonga04ffa72018-05-09 21:42:42 -0700321 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700322 SCOPED_TRACE(status);
323 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
324
325 // Add an ipsec interface
326 status = netdutils::statusFromErrno(
327 XfrmController::addVirtualTunnelInterface(
328 "ipsec_test", "::", "::1", 0xF00D, 0xD00D, false),
329 "addVirtualTunnelInterface");
330 return (status.ok() == expectOk);
331}
332
Benedict Wonga04ffa72018-05-09 21:42:42 -0700333TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
334 binder::Status status;
335
336 // Repeat to ensure cleanup and recreation works correctly
337 for (int i = 0; i < 2; i++) {
338 for (int direction : XFRM_DIRECTIONS) {
339 for (int addrFamily : ADDRESS_FAMILIES) {
340 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
341 "127.0.0.6", 123, 0, 0);
342 EXPECT_TRUE(status.isOk())
343 << " family: " << addrFamily << " direction: " << direction;
344 }
345 }
346
347 // Cleanup
348 for (int direction : XFRM_DIRECTIONS) {
349 for (int addrFamily : ADDRESS_FAMILIES) {
350 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0);
351 EXPECT_TRUE(status.isOk());
352 }
353 }
354 }
355}
356
357TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
358 binder::Status status;
359
360 // Repeat to ensure cleanup and recreation works correctly
361 for (int i = 0; i < 2; i++) {
362 for (int direction : XFRM_DIRECTIONS) {
363 for (int addrFamily : ADDRESS_FAMILIES) {
364 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
365 "2001:db8::d00d", 123, 0, 0);
366 EXPECT_TRUE(status.isOk())
367 << " family: " << addrFamily << " direction: " << direction;
368 }
369 }
370
371 // Cleanup
372 for (int direction : XFRM_DIRECTIONS) {
373 for (int addrFamily : ADDRESS_FAMILIES) {
374 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0);
375 EXPECT_TRUE(status.isOk());
376 }
377 }
378 }
379}
380
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900381TEST_F(BinderTest, XfrmControllerInit) {
Nathan Harold21299f72018-03-16 20:13:03 -0700382 netdutils::Status status;
383 status = XfrmController::Init();
384 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700385
386 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
387 // feature.
388 if (status.code() == EOPNOTSUPP) return;
389
Nathan Harold21299f72018-03-16 20:13:03 -0700390 ASSERT_TRUE(status.ok());
391
392 int32_t spi = 0;
393
394 ASSERT_TRUE(allocateIpSecResources(true, &spi));
395 ASSERT_TRUE(allocateIpSecResources(false, &spi));
396
397 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700398 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700399 ASSERT_TRUE(allocateIpSecResources(true, &spi));
400
401 // Clean up
402 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0);
403 SCOPED_TRACE(status);
404 ASSERT_TRUE(status.ok());
405
Benedict Wonga04ffa72018-05-09 21:42:42 -0700406 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700407 SCOPED_TRACE(status);
408 ASSERT_TRUE(status.ok());
409
410 // Remove Virtual Tunnel Interface.
411 status = netdutils::statusFromErrno(
412 XfrmController::removeVirtualTunnelInterface("ipsec_test"),
413 "removeVirtualTunnelInterface");
414
415 ASSERT_TRUE(status.ok());
416}
Nathan Harold2deff322018-05-10 14:03:48 -0700417#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700418
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900419static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900420 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900421
422 // Output looks like this:
423 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900424 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900425 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900426 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900427 //
428 // or:
429 //
430 // Chain bw_data_saver (1 references)
431 // target prot opt source destination
432 // ... possibly connectivity critical packet rules here ...
433 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900434
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900435 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900436
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900437 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
438 // Data saver disabled.
439 return 0;
440 }
441
442 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
443
444 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
445 // Data saver enabled.
446 return 1;
447 }
448
449 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900450}
451
452bool enableDataSaver(sp<INetd>& netd, bool enable) {
453 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
454 bool ret;
455 netd->bandwidthEnableDataSaver(enable, &ret);
456 return ret;
457}
458
459int getDataSaverState() {
460 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
461 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
462 EXPECT_EQ(enabled4, enabled6);
463 EXPECT_NE(-1, enabled4);
464 EXPECT_NE(-1, enabled6);
465 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
466 return -1;
467 }
468 return enabled6;
469}
470
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900471TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900472 const int wasEnabled = getDataSaverState();
473 ASSERT_NE(-1, wasEnabled);
474
475 if (wasEnabled) {
476 ASSERT_TRUE(enableDataSaver(mNetd, false));
477 EXPECT_EQ(0, getDataSaverState());
478 }
479
480 ASSERT_TRUE(enableDataSaver(mNetd, false));
481 EXPECT_EQ(0, getDataSaverState());
482
483 ASSERT_TRUE(enableDataSaver(mNetd, true));
484 EXPECT_EQ(1, getDataSaverState());
485
486 ASSERT_TRUE(enableDataSaver(mNetd, true));
487 EXPECT_EQ(1, getDataSaverState());
488
489 if (!wasEnabled) {
490 ASSERT_TRUE(enableDataSaver(mNetd, false));
491 EXPECT_EQ(0, getDataSaverState());
492 }
493}
Robin Leeb8087362016-03-30 18:43:08 +0100494
495static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
496 const std::string& action, const char* ipVersion) {
497 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100498 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100499 std::vector<std::string> rules = listIpRules(ipVersion);
500
501 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
502 std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
503 range.getStart(), range.getStop(), action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900504 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800505 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100506 return true;
507 }
508 }
509 return false;
510}
511
512static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
513 const std::string& action) {
514 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
515 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
516 EXPECT_EQ(existsIp4, existsIp6);
517 return existsIp4;
518}
519
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900520TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800521 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
522 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
523 .serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900524 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
525 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
526
527 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
528 EXPECT_EQ(EBUSY,
529 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
530
531 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
532 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
533 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800534 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900535}
536
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900537TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900538 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
539
540 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
541 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
542 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
543
544 std::vector<UidRange> uidRanges = {
545 {BASE_UID + 8005, BASE_UID + 8012},
546 {BASE_UID + 8090, BASE_UID + 8099}
547 };
548 UidRange otherRange(BASE_UID + 8190, BASE_UID + 8299);
549 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
550
551 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
552
553 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
554 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
555 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
556 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
557
558 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
559 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
560 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
561 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
562
563 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
564}
565
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900566TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100567 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100568
Robin Leeb8087362016-03-30 18:43:08 +0100569 std::vector<UidRange> uidRanges = {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900570 {BASE_UID + 150, BASE_UID + 224},
571 {BASE_UID + 226, BASE_UID + 300}
Robin Leeb8087362016-03-30 18:43:08 +0100572 };
573
574 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
575 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
576
577 // Create two valid rules.
578 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
579 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
580 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
581 for (auto const& range : uidRanges) {
582 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
583 }
584
585 // Remove the rules.
586 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
587 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
588 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
589 for (auto const& range : uidRanges) {
590 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
591 }
592
593 // Fail to remove the rules a second time after they are already deleted.
594 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
595 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
596 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
597
598 // All rules should be the same as before.
599 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
600 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
601}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900602
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900603// Create a socket pair that isLoopbackSocket won't think is local.
604void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900605 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900606 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900607 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
608
609 socklen_t addrlen = sizeof(server6);
610 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
611 ASSERT_EQ(0, listen(*serverSocket, 10));
612
Bernie Innocentif6918262018-06-11 17:37:35 +0900613 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900614 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900615 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900616 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
617 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
618
Bernie Innocentif6918262018-06-11 17:37:35 +0900619 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900620 ASSERT_NE(-1, *acceptedSocket);
621
622 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
623}
624
625void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
626 char buf[4096];
627 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
628 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
629 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
630}
631
632void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
633 // Check that the client socket was closed with ECONNABORTED.
634 int ret = write(clientSocket, "foo", sizeof("foo"));
635 int err = errno;
636 EXPECT_EQ(-1, ret);
637 EXPECT_EQ(ECONNABORTED, err);
638
639 // Check that it sent a RST to the server.
640 ret = write(acceptedSocket, "foo", sizeof("foo"));
641 err = errno;
642 EXPECT_EQ(-1, ret);
643 EXPECT_EQ(ECONNRESET, err);
644}
645
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900646TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900647 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900648 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900649
650 // Pick a random UID in the system UID range.
651 constexpr int baseUid = AID_APP - 2000;
652 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
653 int uid = baseUid + 500 + arc4random_uniform(1000);
654 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
655
656 // UID ranges that don't contain uid.
657 std::vector<UidRange> uidRanges = {
658 {baseUid + 42, baseUid + 449},
659 {baseUid + 1536, AID_APP - 4},
660 {baseUid + 498, uid - 1},
661 {uid + 1, baseUid + 1520},
662 };
663 // A skip list that doesn't contain UID.
664 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
665
666 // Close sockets. Our test socket should be intact.
667 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
668 checkSocketpairOpen(clientSocket, acceptedSocket);
669
670 // UID ranges that do contain uid.
671 uidRanges = {
672 {baseUid + 42, baseUid + 449},
673 {baseUid + 1536, AID_APP - 4},
674 {baseUid + 498, baseUid + 1520},
675 };
676 // Add uid to the skip list.
677 skipUids.push_back(uid);
678
679 // Close sockets. Our test socket should still be intact because it's in the skip list.
680 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
681 checkSocketpairOpen(clientSocket, acceptedSocket);
682
683 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
684 skipUids.resize(skipUids.size() - 1);
685 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
686 checkSocketpairClosed(clientSocket, acceptedSocket);
687
688 close(clientSocket);
689 close(serverSocket);
690 close(acceptedSocket);
691}
Erik Klinecc4f2732016-08-03 11:24:27 +0900692
693namespace {
694
695int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
696 if (buf == nullptr) return -1;
697
698 int prefixLength = 0;
699 bool endOfContiguousBits = false;
700 for (unsigned int i = 0; i < buflen; i++) {
701 const uint8_t value = buf[i];
702
703 // Bad bit sequence: check for a contiguous set of bits from the high
704 // end by verifying that the inverted value + 1 is a power of 2
705 // (power of 2 iff. (v & (v - 1)) == 0).
706 const uint8_t inverse = ~value + 1;
707 if ((inverse & (inverse - 1)) != 0) return -1;
708
709 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
710
711 // Bogus netmask.
712 if (endOfContiguousBits && value != 0) return -1;
713
714 if (value != 0xff) endOfContiguousBits = true;
715 }
716
717 return prefixLength;
718}
719
720template<typename T>
721int netmaskToPrefixLength(const T *p) {
722 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
723}
724
725
726static bool interfaceHasAddress(
727 const std::string &ifname, const char *addrString, int prefixLength) {
728 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900729
730 const struct addrinfo hints = {
731 .ai_flags = AI_NUMERICHOST,
732 .ai_family = AF_UNSPEC,
733 .ai_socktype = SOCK_DGRAM,
734 };
735 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
736 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
737 return false;
738 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900739 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900740
741 struct ifaddrs *ifaddrsList = nullptr;
742 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
743
744 if (getifaddrs(&ifaddrsList) != 0) {
745 return false;
746 }
747
748 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
749 if (std::string(addr->ifa_name) != ifname ||
750 addr->ifa_addr == nullptr ||
751 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
752 continue;
753 }
754
755 switch (addr->ifa_addr->sa_family) {
756 case AF_INET: {
757 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
758 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
759 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
760 continue;
761 }
762
763 if (prefixLength < 0) return true; // not checking prefix lengths
764
765 if (addr->ifa_netmask == nullptr) return false;
766 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
767 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
768 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
769 }
770 case AF_INET6: {
771 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
772 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
773 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
774 continue;
775 }
776
777 if (prefixLength < 0) return true; // not checking prefix lengths
778
779 if (addr->ifa_netmask == nullptr) return false;
780 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
781 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
782 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
783 }
784 default:
785 // Cannot happen because we have already screened for matching
786 // address families at the top of each iteration.
787 continue;
788 }
789 }
790
791 return false;
792}
793
794} // namespace
795
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900796TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900797 static const struct TestData {
798 const char *addrString;
799 const int prefixLength;
800 const bool expectSuccess;
801 } kTestData[] = {
802 { "192.0.2.1", 24, true },
803 { "192.0.2.2", 25, true },
804 { "192.0.2.3", 32, true },
805 { "192.0.2.4", 33, false },
806 { "192.not.an.ip", 24, false },
807 { "2001:db8::1", 64, true },
808 { "2001:db8::2", 65, true },
809 { "2001:db8::3", 128, true },
810 { "2001:db8::4", 129, false },
811 { "foo:bar::bad", 64, false },
812 };
813
Luke Huangc3252cc2018-10-16 15:43:23 +0800814 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900815 const auto &td = kTestData[i];
816
817 // [1.a] Add the address.
818 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900819 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900820 if (td.expectSuccess) {
821 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
822 } else {
823 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
824 ASSERT_NE(0, status.serviceSpecificErrorCode());
825 }
826
827 // [1.b] Verify the addition meets the expectation.
828 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900829 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900830 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900831 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900832 }
833
834 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900835 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900836 if (td.expectSuccess) {
837 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
838 } else {
839 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
840 ASSERT_NE(0, status.serviceSpecificErrorCode());
841 }
842
843 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900844 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900845 }
846}
Erik Kline55b06f82016-07-04 09:57:18 +0900847
Erik Kline38e51f12018-09-06 20:14:44 +0900848TEST_F(BinderTest, GetProcSysNet) {
849 const char LOOPBACK[] = "lo";
850 static const struct {
851 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900852 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900853 const char* ifname;
854 const char* parameter;
855 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900856 const int expectedReturnCode;
857 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900858 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
859 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
860 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
861 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
862 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
863 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
864 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900865 };
866
Luke Huangc3252cc2018-10-16 15:43:23 +0800867 for (int i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900868 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900869
Erik Kline38e51f12018-09-06 20:14:44 +0900870 std::string value;
871 const binder::Status status =
872 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
873
874 if (td.expectedReturnCode == 0) {
875 SCOPED_TRACE(String8::format("test case %d should have passed", i));
876 EXPECT_EQ(0, status.exceptionCode());
877 EXPECT_EQ(0, status.serviceSpecificErrorCode());
878 EXPECT_EQ(td.expectedValue, value);
879 } else {
880 SCOPED_TRACE(String8::format("test case %d should have failed", i));
881 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
882 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
883 }
884 }
885}
886
887TEST_F(BinderTest, SetProcSysNet) {
888 static const struct {
889 const int ipversion;
890 const int which;
891 const char* ifname;
892 const char* parameter;
893 const char* value;
894 const int expectedReturnCode;
895 } kTestData[] = {
896 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
897 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
898 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
899 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
900 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
901 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
902 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
903 };
904
Luke Huangc3252cc2018-10-16 15:43:23 +0800905 for (int i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900906 const auto& td = kTestData[i];
907
908 const binder::Status status =
909 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900910
911 if (td.expectedReturnCode == 0) {
912 SCOPED_TRACE(String8::format("test case %d should have passed", i));
913 EXPECT_EQ(0, status.exceptionCode());
914 EXPECT_EQ(0, status.serviceSpecificErrorCode());
915 } else {
916 SCOPED_TRACE(String8::format("test case %d should have failed", i));
917 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
918 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
919 }
920 }
921}
Ben Schwartze7601812017-04-28 16:38:29 -0400922
Erik Kline38e51f12018-09-06 20:14:44 +0900923TEST_F(BinderTest, GetSetProcSysNet) {
924 const int ipversion = INetd::IPV6;
925 const int category = INetd::NEIGH;
926 const std::string& tun = sTun.name();
927 const std::string parameter("ucast_solicit");
928
929 std::string value{};
930 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
931 EXPECT_FALSE(value.empty());
932 const int ival = std::stoi(value);
933 EXPECT_GT(ival, 0);
934 // Try doubling the parameter value (always best!).
935 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
936 .isOk());
937 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
938 EXPECT_EQ(2 * ival, std::stoi(value));
939 // Try resetting the parameter.
940 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
941 .isOk());
942 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
943 EXPECT_EQ(ival, std::stoi(value));
944}
945
Ben Schwartze7601812017-04-28 16:38:29 -0400946static std::string base64Encode(const std::vector<uint8_t>& input) {
947 size_t out_len;
948 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
949 // out_len includes the trailing NULL.
950 uint8_t output_bytes[out_len];
951 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
952 return std::string(reinterpret_cast<char*>(output_bytes));
953}
954
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900955TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900956 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400957 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400958 std::vector<uint8_t> short_fp(1);
959 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
960 std::vector<std::string> test_domains;
961 std::vector<int> test_params = { 300, 25, 8, 8 };
962 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400963 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400964 const std::vector<std::string> servers;
965 const std::string tlsName;
966 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400967 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900968 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400969 { {"192.0.2.1"}, "", {}, 0 },
970 { {"2001:db8::2"}, "host.name", {}, 0 },
971 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
972 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900973 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400974 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900975 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400976 { {"2001:dg8::6"}, "", {}, EINVAL },
977 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
978 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
979 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
980 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400981 };
982
Luke Huangc3252cc2018-10-16 15:43:23 +0800983 for (unsigned int i = 0; i < std::size(kTlsTestData); i++) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900984 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -0400985
986 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400987 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400988 fingerprints.push_back(base64Encode(fingerprint));
989 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400990 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900991 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
992 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -0400993
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400994 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -0400995 SCOPED_TRACE(String8::format("test case %d should have passed", i));
996 SCOPED_TRACE(status.toString8());
997 EXPECT_EQ(0, status.exceptionCode());
998 } else {
999 SCOPED_TRACE(String8::format("test case %d should have failed", i));
1000 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001001 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -04001002 }
Ben Schwartze7601812017-04-28 16:38:29 -04001003 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001004 // Ensure TLS is disabled before the start of the next test.
1005 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001006 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1007 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001008}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001009
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001010namespace {
1011
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001012void expectNoTestCounterRules() {
1013 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1014 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1015 std::string allRules = Join(runCommand(command), "\n");
1016 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1017 }
1018}
1019
Bernie Innocentif6918262018-06-11 17:37:35 +09001020void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1021 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001022 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1023 path, if1.c_str(), if2.c_str(), pkt, byte));
1024}
1025
Bernie Innocentif6918262018-06-11 17:37:35 +09001026void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001027 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1028 path, if1.c_str(), if2.c_str()));
1029 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1030 path, if2.c_str(), if1.c_str()));
1031}
1032
Luke Huangcaebcbb2018-09-27 20:37:14 +08001033std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1034 const std::string& iface) {
1035 for (auto& stats : statsVec) {
1036 if (stats.iface == iface) {
1037 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1038 }
1039 }
1040 return {};
1041}
1042
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001043} // namespace
1044
1045TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001046 expectNoTestCounterRules();
1047
1048 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1049 // disabling tethering. We don't check the return value because these commands will fail if
1050 // tethering is already enabled.
1051 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1052 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1053
1054 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1055 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1056 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1057 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1058 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1059
1060 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1061 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1062 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1063 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1064 // RX is from external to internal, and TX is from internal to external.
1065 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1066 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1067
1068 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1069 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1070
1071 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1072 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1073
1074 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1075 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1076 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1077
Luke Huangcaebcbb2018-09-27 20:37:14 +08001078 std::vector<TetherStatsParcel> statsVec;
1079 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001080 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1081
Luke Huangcaebcbb2018-09-27 20:37:14 +08001082 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001083
Luke Huangcaebcbb2018-09-27 20:37:14 +08001084 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001085
1086 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1087 delTetherCounterValues(path, intIface1, extIface1);
1088 delTetherCounterValues(path, intIface2, extIface2);
1089 if (path == IP6TABLES_PATH) {
1090 delTetherCounterValues(path, intIface3, extIface2);
1091 }
1092 }
1093
1094 expectNoTestCounterRules();
1095}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001096
Luke Huang0051a622018-07-23 20:30:16 +08001097namespace {
1098
Luke Huanga5211072018-08-01 23:36:29 +08001099constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1100constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001101
1102static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1103 const char* chainName) {
1104 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1105 return runCommand(command);
1106}
1107
Luke Huanga5211072018-08-01 23:36:29 +08001108bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001109 const std::string& expectedInterface,
1110 const std::string& expectedRule, const char* table) {
1111 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1112 for (const auto& rule : rules) {
1113 if (rule.find(expectedInterface) != std::string::npos) {
1114 if (rule.find(expectedRule) != std::string::npos) {
1115 return true;
1116 }
1117 }
1118 }
1119 return false;
1120}
1121
1122void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001123 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001124 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001125 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001126 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001127 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1128 IdletimerRule, RAW_TABLE));
1129 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001130 ifname, IdletimerRule, MANGLE_TABLE));
1131 }
1132}
1133
1134void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001135 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001136 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001137 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001138 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001139 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1140 IdletimerRule, RAW_TABLE));
1141 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001142 ifname, IdletimerRule, MANGLE_TABLE));
1143 }
1144}
1145
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001146} // namespace
1147
1148TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001149 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1150 // rule in the table. Because we only check the result after calling remove function. We might
1151 // check the actual rule which is removed by our function (maybe compare the results between
1152 // calling function before and after)
1153 binder::Status status;
1154 const struct TestData {
1155 const std::string ifname;
1156 int32_t timeout;
1157 const std::string classLabel;
1158 } idleTestData[] = {
1159 {"wlan0", 1234, "happyday"},
1160 {"rmnet_data0", 4567, "friday"},
1161 };
1162 for (const auto& td : idleTestData) {
1163 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1164 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1165 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1166
1167 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1168 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1169 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1170 }
1171}
1172
Luke Huanga67dd562018-07-17 19:58:25 +08001173namespace {
1174
1175constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1176constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1177
1178void expectStrictSetUidAccept(const int uid) {
1179 std::string uidRule = StringPrintf("owner UID match %u", uid);
1180 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1181 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1182 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1183 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1184 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1185 }
1186}
1187
1188void expectStrictSetUidLog(const int uid) {
1189 static const char logRule[] = "st_penalty_log all";
1190 std::string uidRule = StringPrintf("owner UID match %u", uid);
1191 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1192 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1193 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1194 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1195 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1196 }
1197}
1198
1199void expectStrictSetUidReject(const int uid) {
1200 static const char rejectRule[] = "st_penalty_reject all";
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_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1205 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1206 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1207 }
1208}
1209
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001210} // namespace
1211
1212TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001213 binder::Status status;
1214 int32_t uid = randomUid();
1215
1216 // setUidCleartextPenalty Policy:Log with randomUid
1217 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1218 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1219 expectStrictSetUidLog(uid);
1220
1221 // setUidCleartextPenalty Policy:Accept with randomUid
1222 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1223 expectStrictSetUidAccept(uid);
1224
1225 // setUidCleartextPenalty Policy:Reject with randomUid
1226 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1227 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1228 expectStrictSetUidReject(uid);
1229
1230 // setUidCleartextPenalty Policy:Accept with randomUid
1231 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1232 expectStrictSetUidAccept(uid);
1233
1234 // test wrong policy
1235 int32_t wrongPolicy = -123;
1236 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1237 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1238}
1239
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001240namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001241
Luke Huanga5211072018-08-01 23:36:29 +08001242bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001243 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1244 return (runCommand(cmd.c_str()).size()) ? true : false;
1245}
1246
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001247} // namespace
1248
1249TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001250 binder::Status status;
1251 // use dummy0 for test since it is set ready
1252 static const char testIf[] = "dummy0";
1253 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1254
1255 status = mNetd->clatdStart(testIf);
1256 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1257 EXPECT_TRUE(processExists(clatdName));
1258
1259 mNetd->clatdStop(testIf);
1260 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1261 EXPECT_FALSE(processExists(clatdName));
1262}
Luke Huang457d4702018-08-16 15:39:15 +08001263
1264namespace {
1265
1266bool getIpfwdV4Enable() {
1267 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1268 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1269 EXPECT_TRUE(!result.empty());
1270 int v4Enable = std::stoi(result[0]);
1271 return v4Enable;
1272}
1273
1274bool getIpfwdV6Enable() {
1275 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1276 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1277 EXPECT_TRUE(!result.empty());
1278 int v6Enable = std::stoi(result[0]);
1279 return v6Enable;
1280}
1281
1282void expectIpfwdEnable(bool enable) {
1283 int enableIPv4 = getIpfwdV4Enable();
1284 int enableIPv6 = getIpfwdV6Enable();
1285 EXPECT_EQ(enable, enableIPv4);
1286 EXPECT_EQ(enable, enableIPv6);
1287}
1288
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001289bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001290 std::vector<std::string> rules = listIpRules(ipVersion);
1291 for (const auto& rule : rules) {
1292 if (rule.find(ipfwdRule) != std::string::npos) {
1293 return true;
1294 }
1295 }
1296 return false;
1297}
1298
1299void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1300 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1301
1302 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1303 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1304 }
1305}
1306
1307void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1308 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1309
1310 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1311 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1312 }
1313}
1314
1315} // namespace
1316
1317TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1318 // Netd default enable Ipfwd with requester NetdHwService
1319 const std::string defaultRequester = "NetdHwService";
1320
1321 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1322 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1323 expectIpfwdEnable(false);
1324
1325 bool ipfwdEnabled;
1326 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1327 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1328 EXPECT_FALSE(ipfwdEnabled);
1329
1330 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1331 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1332 expectIpfwdEnable(true);
1333
1334 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1335 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1336 EXPECT_TRUE(ipfwdEnabled);
1337}
1338
1339TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1340 static const char testFromIf[] = "dummy0";
1341 static const char testToIf[] = "dummy0";
1342
1343 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1344 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1345 expectIpfwdRuleExists(testFromIf, testToIf);
1346
1347 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1348 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1349 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001350}
Luke Huang531f5d32018-08-03 15:19:05 +08001351
1352namespace {
1353
1354constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1355constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1356constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1357constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1358constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
1359
1360// TODO: move iptablesTargetsExists and listIptablesRuleByTable to the top.
1361bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1362 const char* chainName, const std::string& expectedTargetA,
1363 const std::string& expectedTargetB) {
1364 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1365 int matchCount = 0;
1366
1367 for (const auto& rule : rules) {
1368 if (rule.find(expectedTargetA) != std::string::npos) {
1369 if (rule.find(expectedTargetB) != std::string::npos) {
1370 matchCount++;
1371 }
1372 }
1373 }
1374 return matchCount == expectedCount;
1375}
1376
1377void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1378 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1379 std::string result = "";
1380
1381 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001382 // Quota value might be decreased while matching packets
1383 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001384}
1385
1386void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1387 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1388 std::string quotaRule = StringPrintf("quota %s", ifname);
1389
1390 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1391 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1392 BANDWIDTH_COSTLY_IF));
1393 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1394 BANDWIDTH_COSTLY_IF));
1395 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1396 BANDWIDTH_COSTLY_IF));
1397 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1398 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1399 }
1400 expectXtQuotaValueEqual(ifname, quotaBytes);
1401}
1402
1403void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1404 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1405 std::string quotaRule = StringPrintf("quota %s", ifname);
1406
1407 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1408 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1409 BANDWIDTH_COSTLY_IF));
1410 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1411 BANDWIDTH_COSTLY_IF));
1412 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1413 BANDWIDTH_COSTLY_IF));
1414 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1415 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1416 }
1417}
1418
1419void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1420 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1421 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1422 std::string alertName = StringPrintf("%sAlert", ifname);
1423
1424 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1425 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1426 }
1427 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1428}
1429
1430void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1431 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1432 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1433
1434 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1435 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1436 }
1437}
1438
1439void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1440 static const char globalAlertRule[] = "quota globalAlert";
1441 static const char globalAlertName[] = "globalAlert";
1442
1443 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1444 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_INPUT, globalAlertRule));
1445 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_OUTPUT, globalAlertRule));
1446 }
1447 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1448}
1449
1450void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1451 std::string uidRule = StringPrintf("owner UID match %u", uid);
1452
1453 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1454 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1455 }
1456}
1457
1458void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1459 std::string uidRule = StringPrintf("owner UID match %u", uid);
1460
1461 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1462 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1463 }
1464}
1465
1466} // namespace
1467
1468TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1469 long testQuotaBytes = 5550;
1470
1471 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001472 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001473 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1474
1475 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1476 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1477 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1478
1479 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1480 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1481 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1482
1483 // Remove test physical network
1484 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1485}
1486
1487TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1488 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001489 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001490 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001491 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001492 // Need to have a prior interface quota set to set an alert
1493 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1494 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1495 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1496 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1497
1498 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1499 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1500 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1501
1502 // Remove interface quota
1503 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1504 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1505 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1506
1507 // Remove test physical network
1508 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1509}
1510
1511TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1512 long testAlertBytes = 2097149;
1513
1514 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1515 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1516 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1517
1518 testAlertBytes = 2097152;
1519 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1520 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1521 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1522}
1523
1524TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1525 SKIP_IF_BPF_SUPPORTED;
1526
1527 int32_t uid = randomUid();
1528 static const char targetReject[] = "REJECT";
1529 static const char targetReturn[] = "RETURN";
1530
1531 // add NaughtyApp
1532 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1533 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1534 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1535
1536 // remove NaughtyApp
1537 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1538 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1539 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1540
1541 // add NiceApp
1542 status = mNetd->bandwidthAddNiceApp(uid);
1543 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1544 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1545
1546 // remove NiceApp
1547 status = mNetd->bandwidthRemoveNiceApp(uid);
1548 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1549 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1550}
Luke Huangb5733d72018-08-21 17:17:19 +08001551
1552namespace {
1553
Luke Huangb670d162018-08-23 20:01:13 +08001554std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1555 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1556 return runCommand(command);
1557}
1558
Luke Huangc3252cc2018-10-16 15:43:23 +08001559bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001560 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1561 for (const auto& route : routes) {
1562 if (route.find(ipRoute) != std::string::npos) {
1563 return true;
1564 }
1565 }
1566 return false;
1567}
1568
Luke Huangc3252cc2018-10-16 15:43:23 +08001569std::string ipRouteString(const std::string& ifName, const std::string& dst,
1570 const std::string& nextHop) {
1571 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1572
1573 if (!nextHop.empty()) {
1574 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001575 }
1576
Luke Huangc3252cc2018-10-16 15:43:23 +08001577 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001578}
1579
Luke Huangc3252cc2018-10-16 15:43:23 +08001580void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1581 const std::string& dst, const std::string& nextHop,
1582 const char* table) {
1583 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1584}
1585
1586void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001587 const std::string& dst, const std::string& nextHop,
1588 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001589 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001590}
1591
1592bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1593 std::vector<std::string> rules = listIpRules(ipVersion);
1594 for (const auto& rule : rules) {
1595 if (rule.find(ipRule) != std::string::npos) {
1596 return true;
1597 }
1598 }
1599 return false;
1600}
1601
1602void expectNetworkDefaultIpRuleExists(const char* ifName) {
1603 std::string networkDefaultRule =
1604 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1605
1606 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1607 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1608 }
1609}
1610
1611void expectNetworkDefaultIpRuleDoesNotExist() {
1612 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1613
1614 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1615 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1616 }
1617}
1618
1619void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1620 std::string networkPermissionRule = "";
1621 switch (permission) {
1622 case INetd::PERMISSION_NONE:
1623 networkPermissionRule = StringPrintf(
1624 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1625 break;
1626 case INetd::PERMISSION_NETWORK:
1627 networkPermissionRule = StringPrintf(
1628 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1629 break;
1630 case INetd::PERMISSION_SYSTEM:
1631 networkPermissionRule = StringPrintf(
1632 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1633 break;
1634 }
1635
1636 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1637 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1638 }
1639}
1640
1641// TODO: It is a duplicate function, need to remove it
1642bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1643 const std::string& expectedInterface,
1644 const std::string& expectedRule,
1645 const char* table) {
1646 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1647 for (const auto& rule : rules) {
1648 if (rule.find(expectedInterface) != std::string::npos) {
1649 if (rule.find(expectedRule) != std::string::npos) {
1650 return true;
1651 }
1652 }
1653 }
1654 return false;
1655}
1656
1657void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1658 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1659 std::string networkIncomingPacketMarkRule = "";
1660 switch (permission) {
1661 case INetd::PERMISSION_NONE:
1662 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1663 break;
1664 case INetd::PERMISSION_NETWORK:
1665 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1666 break;
1667 case INetd::PERMISSION_SYSTEM:
1668 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1669 break;
1670 }
1671
1672 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1673 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1674 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1675 }
1676}
1677
1678} // namespace
1679
1680TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001681 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001682 const char* ipVersion;
1683 const char* testDest;
1684 const char* testNextHop;
1685 const bool expectSuccess;
1686 } kTestData[] = {
1687 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001688 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1689 {IP_RULE_V4, "10.251.0.0/16", "", true},
1690 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1691 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001692 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001693 {IP_RULE_V6, "::/0", "2001:db8::", true},
1694 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001695 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1696 };
1697
Luke Huangc3252cc2018-10-16 15:43:23 +08001698 static const struct {
1699 const char* ipVersion;
1700 const char* testDest;
1701 const char* testNextHop;
1702 } kTestDataWithNextHop[] = {
1703 {IP_RULE_V4, "10.251.10.0/30", ""},
1704 {IP_RULE_V6, "2001:db8::/32", ""},
1705 };
1706
Luke Huangb670d162018-08-23 20:01:13 +08001707 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001708 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001709 const int testUid = randomUid();
1710 const std::vector<int32_t> testUids = {testUid};
1711
1712 // Add test physical network
1713 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1714 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1715
Luke Huangc3252cc2018-10-16 15:43:23 +08001716 // Setup route for testing nextHop
1717 for (unsigned int i = 0; i < std::size(kTestDataWithNextHop); i++) {
1718 const auto& td = kTestDataWithNextHop[i];
1719
1720 // All route for test tun will disappear once the tun interface is deleted.
1721 binder::Status status =
1722 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1723 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1724 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1725 sTun.name().c_str());
1726
1727 // Add system permission for test uid, setup route in legacy system table.
1728 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1729
1730 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1731 testUid);
1732 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1733 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1734 testTableLegacySystem);
1735
1736 // Remove system permission for test uid, setup route in legacy network table.
1737 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1738
1739 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1740 testUid);
1741 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1742 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1743 testTableLegacyNetwork);
1744 }
1745
1746 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001747 const auto& td = kTestData[i];
1748
1749 binder::Status status =
1750 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1751 if (td.expectSuccess) {
1752 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001753 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001754 sTun.name().c_str());
1755 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001756 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1757 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001758 }
1759
1760 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1761 if (td.expectSuccess) {
1762 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001763 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1764 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001765 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001766 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1767 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001768 }
1769
Luke Huangc3252cc2018-10-16 15:43:23 +08001770 // Add system permission for test uid, route will be added into legacy system table.
1771 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001772
1773 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1774 testUid);
1775 if (td.expectSuccess) {
1776 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001777 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001778 testTableLegacySystem);
1779 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001780 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1781 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001782 }
1783
1784 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1785 td.testNextHop, testUid);
1786 if (td.expectSuccess) {
1787 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001788 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1789 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001790 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001791 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1792 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001793 }
1794
Luke Huangc3252cc2018-10-16 15:43:23 +08001795 // Remove system permission for test uid, route will be added into legacy network table.
1796 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1797
1798 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1799 testUid);
1800 if (td.expectSuccess) {
1801 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1802 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1803 testTableLegacyNetwork);
1804 } else {
1805 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1806 EXPECT_NE(0, status.serviceSpecificErrorCode());
1807 }
1808
1809 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1810 td.testNextHop, testUid);
1811 if (td.expectSuccess) {
1812 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1813 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1814 testTableLegacyNetwork);
1815 } else {
1816 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1817 EXPECT_NE(0, status.serviceSpecificErrorCode());
1818 }
Luke Huangb670d162018-08-23 20:01:13 +08001819 }
1820
1821 // Remove test physical network
1822 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1823}
1824
1825TEST_F(BinderTest, NetworkPermissionDefault) {
1826 // Add test physical network
1827 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1828 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1829
Luke Huangc3252cc2018-10-16 15:43:23 +08001830 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001831 int currentNetid;
1832 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1833 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1834
1835 // Test SetDefault
1836 status = mNetd->networkSetDefault(TEST_NETID1);
1837 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1838 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1839
1840 status = mNetd->networkClearDefault();
1841 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1842 expectNetworkDefaultIpRuleDoesNotExist();
1843
1844 // Add default network back
1845 status = mNetd->networkSetDefault(currentNetid);
1846 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1847
1848 // Test SetPermission
1849 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1850 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1851 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1852 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1853
1854 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1855 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1856 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1857 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1858
1859 // Remove test physical network
1860 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1861}
1862
1863TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1864 const int testUid = randomUid();
1865 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1866 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1867 bool ret = false;
1868 status = mNetd->networkCanProtect(testUid, &ret);
1869 EXPECT_TRUE(ret);
1870
1871 status = mNetd->networkSetProtectDeny(testUid);
1872 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1873 status = mNetd->networkCanProtect(testUid, &ret);
1874 EXPECT_FALSE(ret);
1875}
1876
1877namespace {
1878
Luke Huangb5733d72018-08-21 17:17:19 +08001879int readIntFromPath(const std::string& path) {
1880 std::string result = "";
1881 EXPECT_TRUE(ReadFileToString(path, &result));
1882 return std::stoi(result);
1883}
1884
1885int getTetherAcceptIPv6Ra(const std::string& ifName) {
1886 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1887 return readIntFromPath(path);
1888}
1889
1890bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1891 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1892 return readIntFromPath(path);
1893}
1894
1895int getTetherIPv6DadTransmits(const std::string& ifName) {
1896 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1897 return readIntFromPath(path);
1898}
1899
1900bool getTetherEnableIPv6(const std::string& ifName) {
1901 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1902 int disableIPv6 = readIntFromPath(path);
1903 return !disableIPv6;
1904}
1905
1906bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1907 for (const auto& iface : ifList) {
1908 if (iface == ifName) {
1909 return true;
1910 }
1911 }
1912 return false;
1913}
1914
1915void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1916 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1917 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1918 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1919 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1920}
1921
1922void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1923 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1924 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1925 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1926 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1927}
1928
1929void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1930 const std::string& ifName) {
1931 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1932}
1933
1934void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1935 const std::string& ifName) {
1936 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1937}
1938
1939void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
1940 const std::vector<std::string>& testDnsAddrs) {
1941 EXPECT_TRUE(dnsList == testDnsAddrs);
1942}
1943
1944} // namespace
1945
1946TEST_F(BinderTest, TetherStartStopStatus) {
1947 std::vector<std::string> noDhcpRange = {};
1948 static const char dnsdName[] = "dnsmasq";
1949
1950 binder::Status status = mNetd->tetherStart(noDhcpRange);
1951 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1952 EXPECT_TRUE(processExists(dnsdName));
1953
1954 bool tetherEnabled;
1955 status = mNetd->tetherIsEnabled(&tetherEnabled);
1956 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1957 EXPECT_TRUE(tetherEnabled);
1958
1959 status = mNetd->tetherStop();
1960 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1961 EXPECT_FALSE(processExists(dnsdName));
1962
1963 status = mNetd->tetherIsEnabled(&tetherEnabled);
1964 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1965 EXPECT_FALSE(tetherEnabled);
1966}
1967
1968TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
1969 // TODO: verify if dnsmasq update interface successfully
1970
1971 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
1972 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1973 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
1974
1975 std::vector<std::string> ifList;
1976 status = mNetd->tetherInterfaceList(&ifList);
1977 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1978 expectTetherInterfaceExists(ifList, sTun.name());
1979
1980 status = mNetd->tetherInterfaceRemove(sTun.name());
1981 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1982 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
1983
1984 status = mNetd->tetherInterfaceList(&ifList);
1985 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1986 expectTetherInterfaceNotExists(ifList, sTun.name());
1987}
1988
1989TEST_F(BinderTest, TetherDnsSetList) {
1990 // TODO: verify if dnsmasq update dns successfully
1991 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
1992
1993 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
1994 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1995
1996 std::vector<std::string> dnsList;
1997 status = mNetd->tetherDnsList(&dnsList);
1998 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1999 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002000}
2001
2002namespace {
2003
2004constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2005constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2006constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2007constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2008constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2009constexpr char FIREWALL_STANDBY[] = "fw_standby";
2010constexpr char targetReturn[] = "RETURN";
2011constexpr char targetDrop[] = "DROP";
2012
2013void expectFirewallWhitelistMode() {
2014 static const char dropRule[] = "DROP all";
2015 static const char rejectRule[] = "REJECT all";
2016 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2017 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2018 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2019 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2020 }
2021}
2022
2023void expectFirewallBlacklistMode() {
2024 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2025 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2026 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2027 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2028 }
2029}
2030
2031bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2032 const std::string& expectedInterface,
2033 const std::string& expectedRule) {
2034 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2035 // Expected rule:
2036 // Chain fw_INPUT (1 references)
2037 // pkts bytes target prot opt in out source destination
2038 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2039 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2040 int firstRuleIndex = 2;
2041 if (rules.size() < 4) return false;
2042 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2043 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2044 return true;
2045 }
2046 }
2047 return false;
2048}
2049
2050// TODO: It is a duplicate function, need to remove it
2051bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2052 const std::string& expectedInterface,
2053 const std::string& expectedRule) {
2054 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2055 for (const auto& rule : rules) {
2056 if (rule.find(expectedInterface) != std::string::npos) {
2057 if (rule.find(expectedRule) != std::string::npos) {
2058 return true;
2059 }
2060 }
2061 }
2062 return false;
2063}
2064
2065void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2066 static const char returnRule[] = "RETURN all";
2067 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2068 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2069 returnRule));
2070 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2071 returnRule));
2072 }
2073}
2074
2075void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2076 static const char returnRule[] = "RETURN all";
2077 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2078 EXPECT_FALSE(
2079 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2080 EXPECT_FALSE(
2081 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2082 }
2083}
2084
2085bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2086 const std::string& expectedTarget,
2087 const std::string& expectedRule) {
2088 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2089 int firstRuleIndex = 2;
2090 if (rules.size() < 4) return false;
2091 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2092 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2093 return true;
2094 }
2095 }
2096 return false;
2097}
2098
2099bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2100 const std::string& expectedTarget,
2101 const std::string& expectedRule) {
2102 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2103 int lastRuleIndex = rules.size() - 1;
2104 if (lastRuleIndex < 0) return false;
2105 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2106 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2107 return true;
2108 }
2109 }
2110 return false;
2111}
2112
2113void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2114 std::string uidRule = StringPrintf("owner UID match %u", uid);
2115 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2116 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2117}
2118
2119void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2120 std::string uidRule = StringPrintf("owner UID match %u", uid);
2121 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2122 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2123}
2124
2125void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2126 std::string uidRule = StringPrintf("owner UID match %u", uid);
2127 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2128 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2129}
2130
2131void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2132 std::string uidRule = StringPrintf("owner UID match %u", uid);
2133 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2134 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2135}
2136
2137bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2138 std::vector<std::string> inputRules =
2139 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2140 std::vector<std::string> outputRules =
2141 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2142 int inputLastRuleIndex = inputRules.size() - 1;
2143 int outputLastRuleIndex = outputRules.size() - 1;
2144
2145 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2146 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2147 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2148 return true;
2149 }
2150 }
2151 return false;
2152}
2153
2154void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2155 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2156 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2157}
2158
2159void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2160 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2161 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2162 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2163 }
2164}
2165
2166} // namespace
2167
2168TEST_F(BinderTest, FirewallSetFirewallType) {
2169 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2170 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2171 expectFirewallWhitelistMode();
2172
2173 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2174 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2175 expectFirewallBlacklistMode();
2176
2177 // set firewall type blacklist twice
2178 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2179 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2180 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2181 expectFirewallBlacklistMode();
2182
2183 // set firewall type whitelist twice
2184 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2185 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2186 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2187 expectFirewallWhitelistMode();
2188
2189 // reset firewall type to default
2190 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2191 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2192 expectFirewallBlacklistMode();
2193}
2194
2195TEST_F(BinderTest, FirewallSetInterfaceRule) {
2196 // setinterfaceRule is not supported in BLACKLIST MODE
2197 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2198 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2199
2200 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2201 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2202
2203 // set WHITELIST mode first
2204 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2205 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2206
2207 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2208 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2209 expectFirewallInterfaceRuleAllowExists(sTun.name());
2210
2211 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2212 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2213 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2214
2215 // reset firewall mode to default
2216 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2217 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2218 expectFirewallBlacklistMode();
2219}
2220
2221TEST_F(BinderTest, FirewallSetUidRule) {
2222 SKIP_IF_BPF_SUPPORTED;
2223
2224 int32_t uid = randomUid();
2225
2226 // Doze allow
2227 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2228 INetd::FIREWALL_RULE_ALLOW);
2229 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2230 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2231
2232 // Doze deny
2233 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2234 INetd::FIREWALL_RULE_DENY);
2235 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2236 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2237
2238 // Powersave allow
2239 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2240 INetd::FIREWALL_RULE_ALLOW);
2241 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2242 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2243
2244 // Powersave deny
2245 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2246 INetd::FIREWALL_RULE_DENY);
2247 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2248 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2249
2250 // Standby deny
2251 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2252 INetd::FIREWALL_RULE_DENY);
2253 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2254 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2255
2256 // Standby allow
2257 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2258 INetd::FIREWALL_RULE_ALLOW);
2259 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2260 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2261
2262 // None deny in BLACKLIST
2263 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2264 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2265 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2266 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2267
2268 // None allow in BLACKLIST
2269 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2270 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2271 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2272 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2273
2274 // set firewall type whitelist twice
2275 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2276 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2277 expectFirewallWhitelistMode();
2278
2279 // None allow in WHITELIST
2280 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2281 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2282 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2283 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2284
2285 // None deny in WHITELIST
2286 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2287 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2288 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2289 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2290
2291 // reset firewall mode to default
2292 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2293 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2294 expectFirewallBlacklistMode();
2295}
2296
2297TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2298 SKIP_IF_BPF_SUPPORTED;
2299
2300 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2301 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2302 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2303
2304 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2305 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2306 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2307
2308 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2309 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2310 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2311
2312 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2313 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2314 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2315
2316 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2317 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2318 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2319
2320 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2321 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2322 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2323}