blob: af74bd26308a4e4e6d22a5900ec0155776077480 [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 Colitti89faa342016-02-26 11:38:47 +090051#include "android/net/INetd.h"
52#include "binder/IServiceManager.h"
Nathan Harold21299f72018-03-16 20:13:03 -070053#include "netdutils/Syscalls.h"
Mike Yu5ae61542018-10-19 22:11:43 +080054#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090055
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090056#define IP_PATH "/system/bin/ip"
57#define IP6TABLES_PATH "/system/bin/ip6tables"
58#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090059#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080060#define RAW_TABLE "raw"
61#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080062#define FILTER_TABLE "filter"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090063
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090064namespace binder = android::binder;
65namespace netdutils = android::netdutils;
66
67using android::IBinder;
68using android::IServiceManager;
69using android::sp;
70using android::String16;
71using android::String8;
72using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080073using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090074using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090075using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080076using android::base::Trim;
Chenbo Feng837ddfc2018-05-08 13:45:08 -070077using android::bpf::hasBpfSupport;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090078using android::net::INetd;
Luke Huangcaebcbb2018-09-27 20:37:14 +080079using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090080using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090081using android::net::UidRangeParcel;
Nathan Harold21299f72018-03-16 20:13:03 -070082using android::net::XfrmController;
Robin Leeb8087362016-03-30 18:43:08 +010083
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090084#define SKIP_IF_BPF_SUPPORTED \
85 do { \
86 if (hasBpfSupport()) return; \
87 } while (0)
Chenbo Feng837ddfc2018-05-08 13:45:08 -070088
Robin Leeb8087362016-03-30 18:43:08 +010089static const char* IP_RULE_V4 = "-4";
90static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090091static const int TEST_NETID1 = 65501;
92static const int TEST_NETID2 = 65502;
93constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090094
Benedict Wongb2daefb2017-12-06 22:05:46 -080095static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
96static const std::string ESP_ALLOW_RULE("esp");
97
Lorenzo Colitti89faa342016-02-26 11:38:47 +090098class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090099 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900100 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900101 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900102 sp<IBinder> binder = sm->getService(String16("netd"));
103 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900104 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900105 }
106 }
107
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900108 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900109 ASSERT_NE(nullptr, mNetd.get());
110 }
111
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900112 void TearDown() override {
113 mNetd->networkDestroy(TEST_NETID1);
114 mNetd->networkDestroy(TEST_NETID2);
115 }
116
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900117 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700118
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900119 // Static because setting up the tun interface takes about 40ms.
120 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900121 ASSERT_EQ(0, sTun.init());
122 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900123 }
124
125 static void TearDownTestCase() {
126 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900127 sTun.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900128 }
129
130 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900131
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900132 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900133 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900134 static TunInterface sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900135};
136
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900137TunInterface BinderTest::sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900138
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900139class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900140 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700141 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900142 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900143 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900144 }
145
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900146 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900147 std::string mName;
148};
149
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900150TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900151 TimedOperation t("isAlive RPC");
152 bool isAlive = false;
153 mNetd->isAlive(&isAlive);
154 ASSERT_TRUE(isAlive);
155}
156
157static int randomUid() {
158 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
159}
160
Robin Leeb8087362016-03-30 18:43:08 +0100161static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900162 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900163 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
164 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900165 perror("popen");
166 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900167 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900168
169 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100170 size_t bufsize = 0;
171 ssize_t linelen = 0;
172 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900173 lines.push_back(std::string(line, linelen));
174 free(line);
175 line = nullptr;
176 }
177
178 pclose(f);
179 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900180}
181
Robin Leeb8087362016-03-30 18:43:08 +0100182static std::vector<std::string> listIpRules(const char *ipVersion) {
183 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
184 return runCommand(command);
185}
186
187static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900188 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100189 return runCommand(command);
190}
191
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900192static int iptablesRuleLineLength(const char *binary, const char *chainName) {
193 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900194}
195
Benedict Wongb2daefb2017-12-06 22:05:46 -0800196static bool iptablesRuleExists(const char *binary,
197 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900198 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800199 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900200 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800201 if(rule.find(expectedRule) != std::string::npos) {
202 return true;
203 }
204 }
205 return false;
206}
207
208static bool iptablesNoSocketAllowRuleExists(const char *chainName){
209 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
210 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
211}
212
213static bool iptablesEspAllowRuleExists(const char *chainName){
214 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
215 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
216}
217
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900218TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700219 SKIP_IF_BPF_SUPPORTED;
220
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900221 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
222 const int kNumUids = 500;
223 std::vector<int32_t> noUids(0);
224 std::vector<int32_t> uids(kNumUids);
225 for (int i = 0; i < kNumUids; i++) {
226 uids[i] = randomUid();
227 }
228
229 bool ret;
230 {
231 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900232 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900233 }
234 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800235 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
236 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
237 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
238 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900239 {
240 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900241 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900242 }
243 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900244 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
245 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900246
247 {
248 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900249 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900250 }
251 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900252 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
253 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800254 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
255 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900256
257 {
258 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900259 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900260 }
261 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900262 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
263 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900264
265 // Check that the call fails if iptables returns an error.
266 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900267 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900268 EXPECT_EQ(false, ret);
269}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900270
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900271TEST_F(BinderTest, VirtualTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700272 const struct TestData {
273 const std::string family;
274 const std::string deviceName;
275 const std::string localAddress;
276 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800277 int32_t iKey;
278 int32_t oKey;
279 } kTestData[] = {
Nathan Harold21299f72018-03-16 20:13:03 -0700280 {"IPV4", "test_vti", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53},
281 {"IPV6", "test_vti6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50},
manojboopathi8707f232018-01-02 14:45:47 -0800282 };
283
Luke Huangc3252cc2018-10-16 15:43:23 +0800284 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700285 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800286
287 binder::Status status;
288
289 // Create Virtual Tunnel Interface.
Nathan Harold21299f72018-03-16 20:13:03 -0700290 status = mNetd->addVirtualTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
291 td.iKey, td.oKey);
manojboopathi8707f232018-01-02 14:45:47 -0800292 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
293
294 // Update Virtual Tunnel Interface.
295 status = mNetd->updateVirtualTunnelInterface(td.deviceName, td.localAddress,
296 td.remoteAddress, td.iKey, td.oKey);
297 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
298
299 // Remove Virtual Tunnel Interface.
300 status = mNetd->removeVirtualTunnelInterface(td.deviceName);
301 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
302 }
303}
304
Nathan Harold2deff322018-05-10 14:03:48 -0700305// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
306// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
307#if INTPTR_MAX != INT32_MAX
Benedict Wonga04ffa72018-05-09 21:42:42 -0700308static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
309 static_cast<int>(android::net::XfrmDirection::OUT)};
310static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
311
Nathan Harold21299f72018-03-16 20:13:03 -0700312#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
313 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900314bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Nathan Harold21299f72018-03-16 20:13:03 -0700315 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
316 SCOPED_TRACE(status);
317 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
318
319 // Add a policy
Benedict Wonga04ffa72018-05-09 21:42:42 -0700320 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700321 SCOPED_TRACE(status);
322 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
323
324 // Add an ipsec interface
325 status = netdutils::statusFromErrno(
326 XfrmController::addVirtualTunnelInterface(
327 "ipsec_test", "::", "::1", 0xF00D, 0xD00D, false),
328 "addVirtualTunnelInterface");
329 return (status.ok() == expectOk);
330}
331
Benedict Wonga04ffa72018-05-09 21:42:42 -0700332TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
333 binder::Status status;
334
335 // Repeat to ensure cleanup and recreation works correctly
336 for (int i = 0; i < 2; i++) {
337 for (int direction : XFRM_DIRECTIONS) {
338 for (int addrFamily : ADDRESS_FAMILIES) {
339 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
340 "127.0.0.6", 123, 0, 0);
341 EXPECT_TRUE(status.isOk())
342 << " family: " << addrFamily << " direction: " << direction;
343 }
344 }
345
346 // Cleanup
347 for (int direction : XFRM_DIRECTIONS) {
348 for (int addrFamily : ADDRESS_FAMILIES) {
349 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0);
350 EXPECT_TRUE(status.isOk());
351 }
352 }
353 }
354}
355
356TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
357 binder::Status status;
358
359 // Repeat to ensure cleanup and recreation works correctly
360 for (int i = 0; i < 2; i++) {
361 for (int direction : XFRM_DIRECTIONS) {
362 for (int addrFamily : ADDRESS_FAMILIES) {
363 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
364 "2001:db8::d00d", 123, 0, 0);
365 EXPECT_TRUE(status.isOk())
366 << " family: " << addrFamily << " direction: " << direction;
367 }
368 }
369
370 // Cleanup
371 for (int direction : XFRM_DIRECTIONS) {
372 for (int addrFamily : ADDRESS_FAMILIES) {
373 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0);
374 EXPECT_TRUE(status.isOk());
375 }
376 }
377 }
378}
379
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900380TEST_F(BinderTest, XfrmControllerInit) {
Nathan Harold21299f72018-03-16 20:13:03 -0700381 netdutils::Status status;
382 status = XfrmController::Init();
383 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700384
385 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
386 // feature.
387 if (status.code() == EOPNOTSUPP) return;
388
Nathan Harold21299f72018-03-16 20:13:03 -0700389 ASSERT_TRUE(status.ok());
390
391 int32_t spi = 0;
392
393 ASSERT_TRUE(allocateIpSecResources(true, &spi));
394 ASSERT_TRUE(allocateIpSecResources(false, &spi));
395
396 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700397 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700398 ASSERT_TRUE(allocateIpSecResources(true, &spi));
399
400 // Clean up
401 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0);
402 SCOPED_TRACE(status);
403 ASSERT_TRUE(status.ok());
404
Benedict Wonga04ffa72018-05-09 21:42:42 -0700405 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700406 SCOPED_TRACE(status);
407 ASSERT_TRUE(status.ok());
408
409 // Remove Virtual Tunnel Interface.
410 status = netdutils::statusFromErrno(
411 XfrmController::removeVirtualTunnelInterface("ipsec_test"),
412 "removeVirtualTunnelInterface");
413
414 ASSERT_TRUE(status.ok());
415}
Nathan Harold2deff322018-05-10 14:03:48 -0700416#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700417
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900418static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900419 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900420
421 // Output looks like this:
422 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900423 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900424 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900425 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900426 //
427 // or:
428 //
429 // Chain bw_data_saver (1 references)
430 // target prot opt source destination
431 // ... possibly connectivity critical packet rules here ...
432 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900433
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900434 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900435
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900436 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
437 // Data saver disabled.
438 return 0;
439 }
440
441 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
442
443 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
444 // Data saver enabled.
445 return 1;
446 }
447
448 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900449}
450
451bool enableDataSaver(sp<INetd>& netd, bool enable) {
452 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
453 bool ret;
454 netd->bandwidthEnableDataSaver(enable, &ret);
455 return ret;
456}
457
458int getDataSaverState() {
459 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
460 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
461 EXPECT_EQ(enabled4, enabled6);
462 EXPECT_NE(-1, enabled4);
463 EXPECT_NE(-1, enabled6);
464 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
465 return -1;
466 }
467 return enabled6;
468}
469
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900470TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900471 const int wasEnabled = getDataSaverState();
472 ASSERT_NE(-1, wasEnabled);
473
474 if (wasEnabled) {
475 ASSERT_TRUE(enableDataSaver(mNetd, false));
476 EXPECT_EQ(0, getDataSaverState());
477 }
478
479 ASSERT_TRUE(enableDataSaver(mNetd, false));
480 EXPECT_EQ(0, getDataSaverState());
481
482 ASSERT_TRUE(enableDataSaver(mNetd, true));
483 EXPECT_EQ(1, getDataSaverState());
484
485 ASSERT_TRUE(enableDataSaver(mNetd, true));
486 EXPECT_EQ(1, getDataSaverState());
487
488 if (!wasEnabled) {
489 ASSERT_TRUE(enableDataSaver(mNetd, false));
490 EXPECT_EQ(0, getDataSaverState());
491 }
492}
Robin Leeb8087362016-03-30 18:43:08 +0100493
Luke Huang94658ac2018-10-18 19:35:12 +0900494static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
495 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100496 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100497 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100498 std::vector<std::string> rules = listIpRules(ipVersion);
499
500 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900501 std::string suffix =
502 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900503 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800504 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100505 return true;
506 }
507 }
508 return false;
509}
510
Luke Huang94658ac2018-10-18 19:35:12 +0900511static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
512 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100513 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
514 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
515 EXPECT_EQ(existsIp4, existsIp6);
516 return existsIp4;
517}
518
Luke Huang94658ac2018-10-18 19:35:12 +0900519namespace {
520
521UidRangeParcel makeUidRangeParcel(int start, int stop) {
522 UidRangeParcel res;
523 res.start = start;
524 res.stop = stop;
525
526 return res;
527}
528
529} // namespace
530
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900531TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800532 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
533 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
534 .serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900535 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
536 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
537
538 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
539 EXPECT_EQ(EBUSY,
540 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
541
542 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
543 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
544 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800545 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900546}
547
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900548TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900549 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
550
551 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
552 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
553 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
554
Luke Huang94658ac2018-10-18 19:35:12 +0900555 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
556 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
557 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900558 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
559
560 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
561
562 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
563 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
564 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
565 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
566
567 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
568 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
569 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
570 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
571
572 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
573}
574
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900575TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100576 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100577
Luke Huang94658ac2018-10-18 19:35:12 +0900578 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
579 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100580
581 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
582 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
583
584 // Create two valid rules.
585 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
586 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
587 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
588 for (auto const& range : uidRanges) {
589 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
590 }
591
592 // Remove the rules.
593 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
594 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
595 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
596 for (auto const& range : uidRanges) {
597 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
598 }
599
600 // Fail to remove the rules a second time after they are already deleted.
601 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
602 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
603 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
604
605 // All rules should be the same as before.
606 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
607 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
608}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900609
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900610// Create a socket pair that isLoopbackSocket won't think is local.
611void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900612 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900613 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900614 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
615
616 socklen_t addrlen = sizeof(server6);
617 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
618 ASSERT_EQ(0, listen(*serverSocket, 10));
619
Bernie Innocentif6918262018-06-11 17:37:35 +0900620 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900621 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900622 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900623 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
624 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
625
Bernie Innocentif6918262018-06-11 17:37:35 +0900626 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900627 ASSERT_NE(-1, *acceptedSocket);
628
629 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
630}
631
632void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
633 char buf[4096];
634 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
635 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
636 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
637}
638
639void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
640 // Check that the client socket was closed with ECONNABORTED.
641 int ret = write(clientSocket, "foo", sizeof("foo"));
642 int err = errno;
643 EXPECT_EQ(-1, ret);
644 EXPECT_EQ(ECONNABORTED, err);
645
646 // Check that it sent a RST to the server.
647 ret = write(acceptedSocket, "foo", sizeof("foo"));
648 err = errno;
649 EXPECT_EQ(-1, ret);
650 EXPECT_EQ(ECONNRESET, err);
651}
652
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900653TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900654 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900655 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900656
657 // Pick a random UID in the system UID range.
658 constexpr int baseUid = AID_APP - 2000;
659 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
660 int uid = baseUid + 500 + arc4random_uniform(1000);
661 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
662
663 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900664 std::vector<UidRangeParcel> uidRanges = {
665 makeUidRangeParcel(baseUid + 42, baseUid + 449),
666 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
667 makeUidRangeParcel(baseUid + 498, uid - 1),
668 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900669 };
670 // A skip list that doesn't contain UID.
671 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
672
673 // Close sockets. Our test socket should be intact.
674 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
675 checkSocketpairOpen(clientSocket, acceptedSocket);
676
677 // UID ranges that do contain uid.
678 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900679 makeUidRangeParcel(baseUid + 42, baseUid + 449),
680 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
681 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900682 };
683 // Add uid to the skip list.
684 skipUids.push_back(uid);
685
686 // Close sockets. Our test socket should still be intact because it's in the skip list.
687 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
688 checkSocketpairOpen(clientSocket, acceptedSocket);
689
690 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
691 skipUids.resize(skipUids.size() - 1);
692 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
693 checkSocketpairClosed(clientSocket, acceptedSocket);
694
695 close(clientSocket);
696 close(serverSocket);
697 close(acceptedSocket);
698}
Erik Klinecc4f2732016-08-03 11:24:27 +0900699
700namespace {
701
702int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
703 if (buf == nullptr) return -1;
704
705 int prefixLength = 0;
706 bool endOfContiguousBits = false;
707 for (unsigned int i = 0; i < buflen; i++) {
708 const uint8_t value = buf[i];
709
710 // Bad bit sequence: check for a contiguous set of bits from the high
711 // end by verifying that the inverted value + 1 is a power of 2
712 // (power of 2 iff. (v & (v - 1)) == 0).
713 const uint8_t inverse = ~value + 1;
714 if ((inverse & (inverse - 1)) != 0) return -1;
715
716 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
717
718 // Bogus netmask.
719 if (endOfContiguousBits && value != 0) return -1;
720
721 if (value != 0xff) endOfContiguousBits = true;
722 }
723
724 return prefixLength;
725}
726
727template<typename T>
728int netmaskToPrefixLength(const T *p) {
729 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
730}
731
732
733static bool interfaceHasAddress(
734 const std::string &ifname, const char *addrString, int prefixLength) {
735 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900736
737 const struct addrinfo hints = {
738 .ai_flags = AI_NUMERICHOST,
739 .ai_family = AF_UNSPEC,
740 .ai_socktype = SOCK_DGRAM,
741 };
742 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
743 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
744 return false;
745 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900746 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900747
748 struct ifaddrs *ifaddrsList = nullptr;
749 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
750
751 if (getifaddrs(&ifaddrsList) != 0) {
752 return false;
753 }
754
755 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
756 if (std::string(addr->ifa_name) != ifname ||
757 addr->ifa_addr == nullptr ||
758 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
759 continue;
760 }
761
762 switch (addr->ifa_addr->sa_family) {
763 case AF_INET: {
764 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
765 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
766 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
767 continue;
768 }
769
770 if (prefixLength < 0) return true; // not checking prefix lengths
771
772 if (addr->ifa_netmask == nullptr) return false;
773 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
774 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
775 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
776 }
777 case AF_INET6: {
778 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
779 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
780 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
781 continue;
782 }
783
784 if (prefixLength < 0) return true; // not checking prefix lengths
785
786 if (addr->ifa_netmask == nullptr) return false;
787 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
788 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
789 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
790 }
791 default:
792 // Cannot happen because we have already screened for matching
793 // address families at the top of each iteration.
794 continue;
795 }
796 }
797
798 return false;
799}
800
801} // namespace
802
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900803TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900804 static const struct TestData {
805 const char *addrString;
806 const int prefixLength;
807 const bool expectSuccess;
808 } kTestData[] = {
809 { "192.0.2.1", 24, true },
810 { "192.0.2.2", 25, true },
811 { "192.0.2.3", 32, true },
812 { "192.0.2.4", 33, false },
813 { "192.not.an.ip", 24, false },
814 { "2001:db8::1", 64, true },
815 { "2001:db8::2", 65, true },
816 { "2001:db8::3", 128, true },
817 { "2001:db8::4", 129, false },
818 { "foo:bar::bad", 64, false },
819 };
820
Luke Huangc3252cc2018-10-16 15:43:23 +0800821 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900822 const auto &td = kTestData[i];
823
824 // [1.a] Add the address.
825 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900826 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900827 if (td.expectSuccess) {
828 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
829 } else {
830 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
831 ASSERT_NE(0, status.serviceSpecificErrorCode());
832 }
833
834 // [1.b] Verify the addition meets the expectation.
835 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900836 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900837 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900838 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900839 }
840
841 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900842 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900843 if (td.expectSuccess) {
844 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
845 } else {
846 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
847 ASSERT_NE(0, status.serviceSpecificErrorCode());
848 }
849
850 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900851 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900852 }
853}
Erik Kline55b06f82016-07-04 09:57:18 +0900854
Erik Kline38e51f12018-09-06 20:14:44 +0900855TEST_F(BinderTest, GetProcSysNet) {
856 const char LOOPBACK[] = "lo";
857 static const struct {
858 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900859 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900860 const char* ifname;
861 const char* parameter;
862 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900863 const int expectedReturnCode;
864 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900865 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
866 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
867 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
868 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
869 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
870 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
871 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900872 };
873
Luke Huangc3252cc2018-10-16 15:43:23 +0800874 for (int i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900875 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900876
Erik Kline38e51f12018-09-06 20:14:44 +0900877 std::string value;
878 const binder::Status status =
879 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
880
881 if (td.expectedReturnCode == 0) {
882 SCOPED_TRACE(String8::format("test case %d should have passed", i));
883 EXPECT_EQ(0, status.exceptionCode());
884 EXPECT_EQ(0, status.serviceSpecificErrorCode());
885 EXPECT_EQ(td.expectedValue, value);
886 } else {
887 SCOPED_TRACE(String8::format("test case %d should have failed", i));
888 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
889 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
890 }
891 }
892}
893
894TEST_F(BinderTest, SetProcSysNet) {
895 static const struct {
896 const int ipversion;
897 const int which;
898 const char* ifname;
899 const char* parameter;
900 const char* value;
901 const int expectedReturnCode;
902 } kTestData[] = {
903 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
904 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
905 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
906 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
907 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
908 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
909 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
910 };
911
Luke Huangc3252cc2018-10-16 15:43:23 +0800912 for (int i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900913 const auto& td = kTestData[i];
914
915 const binder::Status status =
916 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900917
918 if (td.expectedReturnCode == 0) {
919 SCOPED_TRACE(String8::format("test case %d should have passed", i));
920 EXPECT_EQ(0, status.exceptionCode());
921 EXPECT_EQ(0, status.serviceSpecificErrorCode());
922 } else {
923 SCOPED_TRACE(String8::format("test case %d should have failed", i));
924 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
925 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
926 }
927 }
928}
Ben Schwartze7601812017-04-28 16:38:29 -0400929
Erik Kline38e51f12018-09-06 20:14:44 +0900930TEST_F(BinderTest, GetSetProcSysNet) {
931 const int ipversion = INetd::IPV6;
932 const int category = INetd::NEIGH;
933 const std::string& tun = sTun.name();
934 const std::string parameter("ucast_solicit");
935
936 std::string value{};
937 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
938 EXPECT_FALSE(value.empty());
939 const int ival = std::stoi(value);
940 EXPECT_GT(ival, 0);
941 // Try doubling the parameter value (always best!).
942 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
943 .isOk());
944 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
945 EXPECT_EQ(2 * ival, std::stoi(value));
946 // Try resetting the parameter.
947 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
948 .isOk());
949 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
950 EXPECT_EQ(ival, std::stoi(value));
951}
952
Ben Schwartze7601812017-04-28 16:38:29 -0400953static std::string base64Encode(const std::vector<uint8_t>& input) {
954 size_t out_len;
955 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
956 // out_len includes the trailing NULL.
957 uint8_t output_bytes[out_len];
958 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
959 return std::string(reinterpret_cast<char*>(output_bytes));
960}
961
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900962TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900963 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400964 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400965 std::vector<uint8_t> short_fp(1);
966 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
967 std::vector<std::string> test_domains;
968 std::vector<int> test_params = { 300, 25, 8, 8 };
969 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400970 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400971 const std::vector<std::string> servers;
972 const std::string tlsName;
973 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400974 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900975 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400976 { {"192.0.2.1"}, "", {}, 0 },
977 { {"2001:db8::2"}, "host.name", {}, 0 },
978 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
979 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900980 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400981 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900982 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400983 { {"2001:dg8::6"}, "", {}, EINVAL },
984 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
985 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
986 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
987 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400988 };
989
Luke Huangc3252cc2018-10-16 15:43:23 +0800990 for (unsigned int i = 0; i < std::size(kTlsTestData); i++) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900991 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -0400992
993 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400994 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400995 fingerprints.push_back(base64Encode(fingerprint));
996 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400997 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900998 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
999 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -04001000
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001001 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -04001002 SCOPED_TRACE(String8::format("test case %d should have passed", i));
1003 SCOPED_TRACE(status.toString8());
1004 EXPECT_EQ(0, status.exceptionCode());
1005 } else {
1006 SCOPED_TRACE(String8::format("test case %d should have failed", i));
1007 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001008 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -04001009 }
Ben Schwartze7601812017-04-28 16:38:29 -04001010 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001011 // Ensure TLS is disabled before the start of the next test.
1012 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001013 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1014 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001015}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001016
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001017namespace {
1018
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001019void expectNoTestCounterRules() {
1020 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1021 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1022 std::string allRules = Join(runCommand(command), "\n");
1023 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1024 }
1025}
1026
Bernie Innocentif6918262018-06-11 17:37:35 +09001027void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1028 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001029 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1030 path, if1.c_str(), if2.c_str(), pkt, byte));
1031}
1032
Bernie Innocentif6918262018-06-11 17:37:35 +09001033void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001034 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1035 path, if1.c_str(), if2.c_str()));
1036 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1037 path, if2.c_str(), if1.c_str()));
1038}
1039
Luke Huangcaebcbb2018-09-27 20:37:14 +08001040std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1041 const std::string& iface) {
1042 for (auto& stats : statsVec) {
1043 if (stats.iface == iface) {
1044 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1045 }
1046 }
1047 return {};
1048}
1049
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001050} // namespace
1051
1052TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001053 expectNoTestCounterRules();
1054
1055 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1056 // disabling tethering. We don't check the return value because these commands will fail if
1057 // tethering is already enabled.
1058 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1059 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1060
1061 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1062 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1063 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1064 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1065 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1066
1067 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1068 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1069 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1070 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1071 // RX is from external to internal, and TX is from internal to external.
1072 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1073 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1074
1075 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1076 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1077
1078 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1079 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1080
1081 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1082 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1083 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1084
Luke Huangcaebcbb2018-09-27 20:37:14 +08001085 std::vector<TetherStatsParcel> statsVec;
1086 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001087 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1088
Luke Huangcaebcbb2018-09-27 20:37:14 +08001089 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001090
Luke Huangcaebcbb2018-09-27 20:37:14 +08001091 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001092
1093 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1094 delTetherCounterValues(path, intIface1, extIface1);
1095 delTetherCounterValues(path, intIface2, extIface2);
1096 if (path == IP6TABLES_PATH) {
1097 delTetherCounterValues(path, intIface3, extIface2);
1098 }
1099 }
1100
1101 expectNoTestCounterRules();
1102}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001103
Luke Huang0051a622018-07-23 20:30:16 +08001104namespace {
1105
Luke Huanga5211072018-08-01 23:36:29 +08001106constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1107constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001108
1109static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1110 const char* chainName) {
1111 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1112 return runCommand(command);
1113}
1114
Luke Huanga5211072018-08-01 23:36:29 +08001115bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001116 const std::string& expectedInterface,
1117 const std::string& expectedRule, const char* table) {
1118 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1119 for (const auto& rule : rules) {
1120 if (rule.find(expectedInterface) != std::string::npos) {
1121 if (rule.find(expectedRule) != std::string::npos) {
1122 return true;
1123 }
1124 }
1125 }
1126 return false;
1127}
1128
1129void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001130 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001131 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001132 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001133 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001134 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1135 IdletimerRule, RAW_TABLE));
1136 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001137 ifname, IdletimerRule, MANGLE_TABLE));
1138 }
1139}
1140
1141void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001142 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001143 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001144 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001145 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001146 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1147 IdletimerRule, RAW_TABLE));
1148 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001149 ifname, IdletimerRule, MANGLE_TABLE));
1150 }
1151}
1152
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001153} // namespace
1154
1155TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001156 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1157 // rule in the table. Because we only check the result after calling remove function. We might
1158 // check the actual rule which is removed by our function (maybe compare the results between
1159 // calling function before and after)
1160 binder::Status status;
1161 const struct TestData {
1162 const std::string ifname;
1163 int32_t timeout;
1164 const std::string classLabel;
1165 } idleTestData[] = {
1166 {"wlan0", 1234, "happyday"},
1167 {"rmnet_data0", 4567, "friday"},
1168 };
1169 for (const auto& td : idleTestData) {
1170 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1171 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1172 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1173
1174 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1175 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1176 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1177 }
1178}
1179
Luke Huanga67dd562018-07-17 19:58:25 +08001180namespace {
1181
1182constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1183constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1184
1185void expectStrictSetUidAccept(const int uid) {
1186 std::string uidRule = StringPrintf("owner UID match %u", uid);
1187 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1188 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1189 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1190 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1191 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1192 }
1193}
1194
1195void expectStrictSetUidLog(const int uid) {
1196 static const char logRule[] = "st_penalty_log all";
1197 std::string uidRule = StringPrintf("owner UID match %u", uid);
1198 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1199 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1200 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1201 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1202 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1203 }
1204}
1205
1206void expectStrictSetUidReject(const int uid) {
1207 static const char rejectRule[] = "st_penalty_reject all";
1208 std::string uidRule = StringPrintf("owner UID match %u", uid);
1209 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1210 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1211 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1212 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1213 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1214 }
1215}
1216
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001217} // namespace
1218
1219TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001220 binder::Status status;
1221 int32_t uid = randomUid();
1222
1223 // setUidCleartextPenalty Policy:Log with randomUid
1224 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1225 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1226 expectStrictSetUidLog(uid);
1227
1228 // setUidCleartextPenalty Policy:Accept with randomUid
1229 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1230 expectStrictSetUidAccept(uid);
1231
1232 // setUidCleartextPenalty Policy:Reject with randomUid
1233 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1234 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1235 expectStrictSetUidReject(uid);
1236
1237 // setUidCleartextPenalty Policy:Accept with randomUid
1238 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1239 expectStrictSetUidAccept(uid);
1240
1241 // test wrong policy
1242 int32_t wrongPolicy = -123;
1243 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1244 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1245}
1246
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001247namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001248
Luke Huanga5211072018-08-01 23:36:29 +08001249bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001250 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1251 return (runCommand(cmd.c_str()).size()) ? true : false;
1252}
1253
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001254} // namespace
1255
1256TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001257 binder::Status status;
1258 // use dummy0 for test since it is set ready
1259 static const char testIf[] = "dummy0";
1260 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1261
1262 status = mNetd->clatdStart(testIf);
1263 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1264 EXPECT_TRUE(processExists(clatdName));
1265
1266 mNetd->clatdStop(testIf);
1267 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1268 EXPECT_FALSE(processExists(clatdName));
1269}
Luke Huang457d4702018-08-16 15:39:15 +08001270
1271namespace {
1272
1273bool getIpfwdV4Enable() {
1274 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1275 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1276 EXPECT_TRUE(!result.empty());
1277 int v4Enable = std::stoi(result[0]);
1278 return v4Enable;
1279}
1280
1281bool getIpfwdV6Enable() {
1282 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1283 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1284 EXPECT_TRUE(!result.empty());
1285 int v6Enable = std::stoi(result[0]);
1286 return v6Enable;
1287}
1288
1289void expectIpfwdEnable(bool enable) {
1290 int enableIPv4 = getIpfwdV4Enable();
1291 int enableIPv6 = getIpfwdV6Enable();
1292 EXPECT_EQ(enable, enableIPv4);
1293 EXPECT_EQ(enable, enableIPv6);
1294}
1295
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001296bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001297 std::vector<std::string> rules = listIpRules(ipVersion);
1298 for (const auto& rule : rules) {
1299 if (rule.find(ipfwdRule) != std::string::npos) {
1300 return true;
1301 }
1302 }
1303 return false;
1304}
1305
1306void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1307 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1308
1309 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1310 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1311 }
1312}
1313
1314void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1315 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1316
1317 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1318 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1319 }
1320}
1321
1322} // namespace
1323
1324TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1325 // Netd default enable Ipfwd with requester NetdHwService
1326 const std::string defaultRequester = "NetdHwService";
1327
1328 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1329 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1330 expectIpfwdEnable(false);
1331
1332 bool ipfwdEnabled;
1333 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1334 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1335 EXPECT_FALSE(ipfwdEnabled);
1336
1337 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1338 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1339 expectIpfwdEnable(true);
1340
1341 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1342 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1343 EXPECT_TRUE(ipfwdEnabled);
1344}
1345
1346TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1347 static const char testFromIf[] = "dummy0";
1348 static const char testToIf[] = "dummy0";
1349
1350 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1351 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1352 expectIpfwdRuleExists(testFromIf, testToIf);
1353
1354 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1355 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1356 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001357}
Luke Huang531f5d32018-08-03 15:19:05 +08001358
1359namespace {
1360
1361constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1362constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1363constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1364constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1365constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
1366
1367// TODO: move iptablesTargetsExists and listIptablesRuleByTable to the top.
1368bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1369 const char* chainName, const std::string& expectedTargetA,
1370 const std::string& expectedTargetB) {
1371 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1372 int matchCount = 0;
1373
1374 for (const auto& rule : rules) {
1375 if (rule.find(expectedTargetA) != std::string::npos) {
1376 if (rule.find(expectedTargetB) != std::string::npos) {
1377 matchCount++;
1378 }
1379 }
1380 }
1381 return matchCount == expectedCount;
1382}
1383
1384void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1385 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1386 std::string result = "";
1387
1388 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001389 // Quota value might be decreased while matching packets
1390 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001391}
1392
1393void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1394 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1395 std::string quotaRule = StringPrintf("quota %s", ifname);
1396
1397 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1398 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1399 BANDWIDTH_COSTLY_IF));
1400 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1401 BANDWIDTH_COSTLY_IF));
1402 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1403 BANDWIDTH_COSTLY_IF));
1404 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1405 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1406 }
1407 expectXtQuotaValueEqual(ifname, quotaBytes);
1408}
1409
1410void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1411 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1412 std::string quotaRule = StringPrintf("quota %s", ifname);
1413
1414 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1415 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1416 BANDWIDTH_COSTLY_IF));
1417 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1418 BANDWIDTH_COSTLY_IF));
1419 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1420 BANDWIDTH_COSTLY_IF));
1421 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1422 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1423 }
1424}
1425
1426void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1427 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1428 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1429 std::string alertName = StringPrintf("%sAlert", ifname);
1430
1431 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1432 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1433 }
1434 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1435}
1436
1437void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1438 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1439 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1440
1441 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1442 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1443 }
1444}
1445
1446void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1447 static const char globalAlertRule[] = "quota globalAlert";
1448 static const char globalAlertName[] = "globalAlert";
1449
1450 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1451 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_INPUT, globalAlertRule));
1452 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_OUTPUT, globalAlertRule));
1453 }
1454 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1455}
1456
1457void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1458 std::string uidRule = StringPrintf("owner UID match %u", uid);
1459
1460 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1461 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1462 }
1463}
1464
1465void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1466 std::string uidRule = StringPrintf("owner UID match %u", uid);
1467
1468 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1469 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1470 }
1471}
1472
1473} // namespace
1474
1475TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1476 long testQuotaBytes = 5550;
1477
1478 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001479 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001480 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1481
1482 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1483 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1484 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1485
1486 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1487 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1488 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1489
1490 // Remove test physical network
1491 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1492}
1493
1494TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1495 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001496 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001497 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001498 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001499 // Need to have a prior interface quota set to set an alert
1500 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1501 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1502 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1503 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1504
1505 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1506 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1507 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1508
1509 // Remove interface quota
1510 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1511 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1512 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1513
1514 // Remove test physical network
1515 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1516}
1517
1518TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1519 long testAlertBytes = 2097149;
1520
1521 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1522 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1523 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1524
1525 testAlertBytes = 2097152;
1526 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1527 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1528 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1529}
1530
1531TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1532 SKIP_IF_BPF_SUPPORTED;
1533
1534 int32_t uid = randomUid();
1535 static const char targetReject[] = "REJECT";
1536 static const char targetReturn[] = "RETURN";
1537
1538 // add NaughtyApp
1539 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1540 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1541 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1542
1543 // remove NaughtyApp
1544 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1545 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1546 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1547
1548 // add NiceApp
1549 status = mNetd->bandwidthAddNiceApp(uid);
1550 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1551 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1552
1553 // remove NiceApp
1554 status = mNetd->bandwidthRemoveNiceApp(uid);
1555 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1556 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1557}
Luke Huangb5733d72018-08-21 17:17:19 +08001558
1559namespace {
1560
Luke Huangb670d162018-08-23 20:01:13 +08001561std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1562 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1563 return runCommand(command);
1564}
1565
Luke Huangc3252cc2018-10-16 15:43:23 +08001566bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001567 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1568 for (const auto& route : routes) {
1569 if (route.find(ipRoute) != std::string::npos) {
1570 return true;
1571 }
1572 }
1573 return false;
1574}
1575
Luke Huangc3252cc2018-10-16 15:43:23 +08001576std::string ipRouteString(const std::string& ifName, const std::string& dst,
1577 const std::string& nextHop) {
1578 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1579
1580 if (!nextHop.empty()) {
1581 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001582 }
1583
Luke Huangc3252cc2018-10-16 15:43:23 +08001584 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001585}
1586
Luke Huangc3252cc2018-10-16 15:43:23 +08001587void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1588 const std::string& dst, const std::string& nextHop,
1589 const char* table) {
1590 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1591}
1592
1593void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001594 const std::string& dst, const std::string& nextHop,
1595 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001596 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001597}
1598
1599bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1600 std::vector<std::string> rules = listIpRules(ipVersion);
1601 for (const auto& rule : rules) {
1602 if (rule.find(ipRule) != std::string::npos) {
1603 return true;
1604 }
1605 }
1606 return false;
1607}
1608
1609void expectNetworkDefaultIpRuleExists(const char* ifName) {
1610 std::string networkDefaultRule =
1611 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1612
1613 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1614 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1615 }
1616}
1617
1618void expectNetworkDefaultIpRuleDoesNotExist() {
1619 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1620
1621 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1622 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1623 }
1624}
1625
1626void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1627 std::string networkPermissionRule = "";
1628 switch (permission) {
1629 case INetd::PERMISSION_NONE:
1630 networkPermissionRule = StringPrintf(
1631 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1632 break;
1633 case INetd::PERMISSION_NETWORK:
1634 networkPermissionRule = StringPrintf(
1635 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1636 break;
1637 case INetd::PERMISSION_SYSTEM:
1638 networkPermissionRule = StringPrintf(
1639 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1640 break;
1641 }
1642
1643 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1644 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1645 }
1646}
1647
1648// TODO: It is a duplicate function, need to remove it
1649bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1650 const std::string& expectedInterface,
1651 const std::string& expectedRule,
1652 const char* table) {
1653 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1654 for (const auto& rule : rules) {
1655 if (rule.find(expectedInterface) != std::string::npos) {
1656 if (rule.find(expectedRule) != std::string::npos) {
1657 return true;
1658 }
1659 }
1660 }
1661 return false;
1662}
1663
1664void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1665 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1666 std::string networkIncomingPacketMarkRule = "";
1667 switch (permission) {
1668 case INetd::PERMISSION_NONE:
1669 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1670 break;
1671 case INetd::PERMISSION_NETWORK:
1672 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1673 break;
1674 case INetd::PERMISSION_SYSTEM:
1675 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1676 break;
1677 }
1678
1679 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1680 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1681 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1682 }
1683}
1684
1685} // namespace
1686
1687TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001688 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001689 const char* ipVersion;
1690 const char* testDest;
1691 const char* testNextHop;
1692 const bool expectSuccess;
1693 } kTestData[] = {
1694 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001695 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1696 {IP_RULE_V4, "10.251.0.0/16", "", true},
1697 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1698 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001699 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001700 {IP_RULE_V6, "::/0", "2001:db8::", true},
1701 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001702 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1703 };
1704
Luke Huangc3252cc2018-10-16 15:43:23 +08001705 static const struct {
1706 const char* ipVersion;
1707 const char* testDest;
1708 const char* testNextHop;
1709 } kTestDataWithNextHop[] = {
1710 {IP_RULE_V4, "10.251.10.0/30", ""},
1711 {IP_RULE_V6, "2001:db8::/32", ""},
1712 };
1713
Luke Huangb670d162018-08-23 20:01:13 +08001714 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001715 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001716 const int testUid = randomUid();
1717 const std::vector<int32_t> testUids = {testUid};
1718
1719 // Add test physical network
1720 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1721 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1722
Luke Huangc3252cc2018-10-16 15:43:23 +08001723 // Setup route for testing nextHop
1724 for (unsigned int i = 0; i < std::size(kTestDataWithNextHop); i++) {
1725 const auto& td = kTestDataWithNextHop[i];
1726
1727 // All route for test tun will disappear once the tun interface is deleted.
1728 binder::Status status =
1729 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1730 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1731 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1732 sTun.name().c_str());
1733
1734 // Add system permission for test uid, setup route in legacy system table.
1735 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1736
1737 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1738 testUid);
1739 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1740 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1741 testTableLegacySystem);
1742
1743 // Remove system permission for test uid, setup route in legacy network table.
1744 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1745
1746 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1747 testUid);
1748 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1749 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1750 testTableLegacyNetwork);
1751 }
1752
1753 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001754 const auto& td = kTestData[i];
1755
1756 binder::Status status =
1757 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1758 if (td.expectSuccess) {
1759 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001760 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001761 sTun.name().c_str());
1762 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001763 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1764 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001765 }
1766
1767 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1768 if (td.expectSuccess) {
1769 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001770 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1771 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001772 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001773 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1774 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001775 }
1776
Luke Huangc3252cc2018-10-16 15:43:23 +08001777 // Add system permission for test uid, route will be added into legacy system table.
1778 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001779
1780 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1781 testUid);
1782 if (td.expectSuccess) {
1783 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001784 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001785 testTableLegacySystem);
1786 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001787 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1788 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001789 }
1790
1791 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1792 td.testNextHop, testUid);
1793 if (td.expectSuccess) {
1794 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001795 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1796 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001797 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001798 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1799 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001800 }
1801
Luke Huangc3252cc2018-10-16 15:43:23 +08001802 // Remove system permission for test uid, route will be added into legacy network table.
1803 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1804
1805 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1806 testUid);
1807 if (td.expectSuccess) {
1808 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1809 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1810 testTableLegacyNetwork);
1811 } else {
1812 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1813 EXPECT_NE(0, status.serviceSpecificErrorCode());
1814 }
1815
1816 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1817 td.testNextHop, testUid);
1818 if (td.expectSuccess) {
1819 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1820 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1821 testTableLegacyNetwork);
1822 } else {
1823 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1824 EXPECT_NE(0, status.serviceSpecificErrorCode());
1825 }
Luke Huangb670d162018-08-23 20:01:13 +08001826 }
1827
1828 // Remove test physical network
1829 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1830}
1831
1832TEST_F(BinderTest, NetworkPermissionDefault) {
1833 // Add test physical network
1834 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1835 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1836
Luke Huangc3252cc2018-10-16 15:43:23 +08001837 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001838 int currentNetid;
1839 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1840 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1841
1842 // Test SetDefault
1843 status = mNetd->networkSetDefault(TEST_NETID1);
1844 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1845 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1846
1847 status = mNetd->networkClearDefault();
1848 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1849 expectNetworkDefaultIpRuleDoesNotExist();
1850
1851 // Add default network back
1852 status = mNetd->networkSetDefault(currentNetid);
1853 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1854
1855 // Test SetPermission
1856 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1857 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1858 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1859 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1860
1861 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1862 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1863 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1864 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1865
1866 // Remove test physical network
1867 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1868}
1869
1870TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1871 const int testUid = randomUid();
1872 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1873 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1874 bool ret = false;
1875 status = mNetd->networkCanProtect(testUid, &ret);
1876 EXPECT_TRUE(ret);
1877
1878 status = mNetd->networkSetProtectDeny(testUid);
1879 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1880 status = mNetd->networkCanProtect(testUid, &ret);
1881 EXPECT_FALSE(ret);
1882}
1883
1884namespace {
1885
Luke Huangb5733d72018-08-21 17:17:19 +08001886int readIntFromPath(const std::string& path) {
1887 std::string result = "";
1888 EXPECT_TRUE(ReadFileToString(path, &result));
1889 return std::stoi(result);
1890}
1891
1892int getTetherAcceptIPv6Ra(const std::string& ifName) {
1893 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1894 return readIntFromPath(path);
1895}
1896
1897bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1898 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1899 return readIntFromPath(path);
1900}
1901
1902int getTetherIPv6DadTransmits(const std::string& ifName) {
1903 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1904 return readIntFromPath(path);
1905}
1906
1907bool getTetherEnableIPv6(const std::string& ifName) {
1908 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1909 int disableIPv6 = readIntFromPath(path);
1910 return !disableIPv6;
1911}
1912
1913bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1914 for (const auto& iface : ifList) {
1915 if (iface == ifName) {
1916 return true;
1917 }
1918 }
1919 return false;
1920}
1921
1922void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1923 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1924 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1925 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1926 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1927}
1928
1929void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1930 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1931 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1932 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1933 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1934}
1935
1936void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1937 const std::string& ifName) {
1938 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1939}
1940
1941void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1942 const std::string& ifName) {
1943 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1944}
1945
1946void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
1947 const std::vector<std::string>& testDnsAddrs) {
1948 EXPECT_TRUE(dnsList == testDnsAddrs);
1949}
1950
1951} // namespace
1952
1953TEST_F(BinderTest, TetherStartStopStatus) {
1954 std::vector<std::string> noDhcpRange = {};
1955 static const char dnsdName[] = "dnsmasq";
1956
1957 binder::Status status = mNetd->tetherStart(noDhcpRange);
1958 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1959 EXPECT_TRUE(processExists(dnsdName));
1960
1961 bool tetherEnabled;
1962 status = mNetd->tetherIsEnabled(&tetherEnabled);
1963 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1964 EXPECT_TRUE(tetherEnabled);
1965
1966 status = mNetd->tetherStop();
1967 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1968 EXPECT_FALSE(processExists(dnsdName));
1969
1970 status = mNetd->tetherIsEnabled(&tetherEnabled);
1971 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1972 EXPECT_FALSE(tetherEnabled);
1973}
1974
1975TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
1976 // TODO: verify if dnsmasq update interface successfully
1977
1978 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
1979 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1980 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
1981
1982 std::vector<std::string> ifList;
1983 status = mNetd->tetherInterfaceList(&ifList);
1984 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1985 expectTetherInterfaceExists(ifList, sTun.name());
1986
1987 status = mNetd->tetherInterfaceRemove(sTun.name());
1988 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1989 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
1990
1991 status = mNetd->tetherInterfaceList(&ifList);
1992 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1993 expectTetherInterfaceNotExists(ifList, sTun.name());
1994}
1995
1996TEST_F(BinderTest, TetherDnsSetList) {
1997 // TODO: verify if dnsmasq update dns successfully
1998 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
1999
2000 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2001 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2002
2003 std::vector<std::string> dnsList;
2004 status = mNetd->tetherDnsList(&dnsList);
2005 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2006 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002007}
2008
2009namespace {
2010
2011constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2012constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2013constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2014constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2015constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2016constexpr char FIREWALL_STANDBY[] = "fw_standby";
2017constexpr char targetReturn[] = "RETURN";
2018constexpr char targetDrop[] = "DROP";
2019
2020void expectFirewallWhitelistMode() {
2021 static const char dropRule[] = "DROP all";
2022 static const char rejectRule[] = "REJECT all";
2023 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2024 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2025 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2026 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2027 }
2028}
2029
2030void expectFirewallBlacklistMode() {
2031 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2032 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2033 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2034 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2035 }
2036}
2037
2038bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2039 const std::string& expectedInterface,
2040 const std::string& expectedRule) {
2041 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2042 // Expected rule:
2043 // Chain fw_INPUT (1 references)
2044 // pkts bytes target prot opt in out source destination
2045 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2046 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2047 int firstRuleIndex = 2;
2048 if (rules.size() < 4) return false;
2049 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2050 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2051 return true;
2052 }
2053 }
2054 return false;
2055}
2056
2057// TODO: It is a duplicate function, need to remove it
2058bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2059 const std::string& expectedInterface,
2060 const std::string& expectedRule) {
2061 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2062 for (const auto& rule : rules) {
2063 if (rule.find(expectedInterface) != std::string::npos) {
2064 if (rule.find(expectedRule) != std::string::npos) {
2065 return true;
2066 }
2067 }
2068 }
2069 return false;
2070}
2071
2072void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2073 static const char returnRule[] = "RETURN all";
2074 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2075 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2076 returnRule));
2077 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2078 returnRule));
2079 }
2080}
2081
2082void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2083 static const char returnRule[] = "RETURN all";
2084 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2085 EXPECT_FALSE(
2086 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2087 EXPECT_FALSE(
2088 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2089 }
2090}
2091
2092bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2093 const std::string& expectedTarget,
2094 const std::string& expectedRule) {
2095 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2096 int firstRuleIndex = 2;
2097 if (rules.size() < 4) return false;
2098 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2099 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2100 return true;
2101 }
2102 }
2103 return false;
2104}
2105
2106bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2107 const std::string& expectedTarget,
2108 const std::string& expectedRule) {
2109 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2110 int lastRuleIndex = rules.size() - 1;
2111 if (lastRuleIndex < 0) return false;
2112 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2113 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2114 return true;
2115 }
2116 }
2117 return false;
2118}
2119
2120void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2121 std::string uidRule = StringPrintf("owner UID match %u", uid);
2122 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2123 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2124}
2125
2126void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2127 std::string uidRule = StringPrintf("owner UID match %u", uid);
2128 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2129 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2130}
2131
2132void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2133 std::string uidRule = StringPrintf("owner UID match %u", uid);
2134 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2135 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2136}
2137
2138void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2139 std::string uidRule = StringPrintf("owner UID match %u", uid);
2140 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2141 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2142}
2143
2144bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2145 std::vector<std::string> inputRules =
2146 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2147 std::vector<std::string> outputRules =
2148 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2149 int inputLastRuleIndex = inputRules.size() - 1;
2150 int outputLastRuleIndex = outputRules.size() - 1;
2151
2152 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2153 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2154 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2155 return true;
2156 }
2157 }
2158 return false;
2159}
2160
2161void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2162 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2163 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2164}
2165
2166void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2167 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2168 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2169 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2170 }
2171}
2172
2173} // namespace
2174
2175TEST_F(BinderTest, FirewallSetFirewallType) {
2176 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2177 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2178 expectFirewallWhitelistMode();
2179
2180 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2181 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2182 expectFirewallBlacklistMode();
2183
2184 // set firewall type blacklist twice
2185 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2186 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2187 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2188 expectFirewallBlacklistMode();
2189
2190 // set firewall type whitelist twice
2191 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2192 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2193 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2194 expectFirewallWhitelistMode();
2195
2196 // reset firewall type to default
2197 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2198 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2199 expectFirewallBlacklistMode();
2200}
2201
2202TEST_F(BinderTest, FirewallSetInterfaceRule) {
2203 // setinterfaceRule is not supported in BLACKLIST MODE
2204 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2205 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2206
2207 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2208 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2209
2210 // set WHITELIST mode first
2211 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2212 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2213
2214 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2215 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2216 expectFirewallInterfaceRuleAllowExists(sTun.name());
2217
2218 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2219 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2220 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2221
2222 // reset firewall mode to default
2223 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2224 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2225 expectFirewallBlacklistMode();
2226}
2227
2228TEST_F(BinderTest, FirewallSetUidRule) {
2229 SKIP_IF_BPF_SUPPORTED;
2230
2231 int32_t uid = randomUid();
2232
2233 // Doze allow
2234 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2235 INetd::FIREWALL_RULE_ALLOW);
2236 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2237 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2238
2239 // Doze deny
2240 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2241 INetd::FIREWALL_RULE_DENY);
2242 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2243 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2244
2245 // Powersave allow
2246 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2247 INetd::FIREWALL_RULE_ALLOW);
2248 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2249 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2250
2251 // Powersave deny
2252 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2253 INetd::FIREWALL_RULE_DENY);
2254 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2255 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2256
2257 // Standby deny
2258 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2259 INetd::FIREWALL_RULE_DENY);
2260 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2261 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2262
2263 // Standby allow
2264 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2265 INetd::FIREWALL_RULE_ALLOW);
2266 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2267 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2268
2269 // None deny in BLACKLIST
2270 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2271 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2272 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2273 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2274
2275 // None allow in BLACKLIST
2276 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2277 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2278 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2279 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2280
2281 // set firewall type whitelist twice
2282 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2283 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2284 expectFirewallWhitelistMode();
2285
2286 // None allow in WHITELIST
2287 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2288 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2289 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2290 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2291
2292 // None deny in WHITELIST
2293 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2294 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2295 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2296 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2297
2298 // reset firewall mode to default
2299 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2300 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2301 expectFirewallBlacklistMode();
2302}
2303
2304TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2305 SKIP_IF_BPF_SUPPORTED;
2306
2307 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2308 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2309 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2310
2311 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2312 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2313 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2314
2315 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2316 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2317 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2318
2319 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2320 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2321 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2322
2323 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2324 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2325 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2326
2327 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2328 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2329 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2330}