blob: 458a0ed72a0d51fa04b7dc207aaa33b8356b96f7 [file] [log] [blame]
Lorenzo Colitti89faa342016-02-26 11:38:47 +09001/*
2 * Copyright 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * binder_test.cpp - unit tests for netd binder RPCs.
17 */
18
Robin Leeb8087362016-03-30 18:43:08 +010019#include <cerrno>
20#include <cinttypes>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090021#include <cstdint>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090022#include <cstdio>
23#include <cstdlib>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090024#include <set>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090025#include <vector>
26
Luke Huangf7782042018-08-08 13:13:04 +080027#include <dirent.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090028#include <fcntl.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090029#include <ifaddrs.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090030#include <linux/if.h>
31#include <linux/if_tun.h>
Luke Huangf7782042018-08-08 13:13:04 +080032#include <netdb.h>
33#include <netinet/in.h>
Ben Schwartze7601812017-04-28 16:38:29 -040034#include <openssl/base64.h>
Luke Huangf7782042018-08-08 13:13:04 +080035#include <sys/socket.h>
36#include <sys/types.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090037
Luke Huang531f5d32018-08-03 15:19:05 +080038#include <android-base/file.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090039#include <android-base/macros.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090040#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090041#include <android-base/strings.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070042#include <bpf/BpfUtils.h>
Robin Leeb8087362016-03-30 18:43:08 +010043#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090044#include <gtest/gtest.h>
45#include <logwrap/logwrap.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090046#include <netutils/ifc.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090047
Nathan Harold21299f72018-03-16 20:13:03 -070048#include "InterfaceController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090049#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090050#include "Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070051#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090052#include "android/net/INetd.h"
53#include "binder/IServiceManager.h"
Nathan Harold21299f72018-03-16 20:13:03 -070054#include "netdutils/Syscalls.h"
Mike Yu5ae61542018-10-19 22:11:43 +080055#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090056
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090057#define IP_PATH "/system/bin/ip"
58#define IP6TABLES_PATH "/system/bin/ip6tables"
59#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090060#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080061#define RAW_TABLE "raw"
62#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080063#define FILTER_TABLE "filter"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090064
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090065namespace binder = android::binder;
66namespace netdutils = android::netdutils;
67
68using android::IBinder;
69using android::IServiceManager;
70using android::sp;
71using android::String16;
72using android::String8;
73using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080074using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090075using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090076using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080077using android::base::Trim;
Chenbo Feng837ddfc2018-05-08 13:45:08 -070078using android::bpf::hasBpfSupport;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090079using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080080using android::net::InterfaceConfigurationParcel;
81using android::net::InterfaceController;
Luke Huangcaebcbb2018-09-27 20:37:14 +080082using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090083using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090084using android::net::UidRangeParcel;
Nathan Harold21299f72018-03-16 20:13:03 -070085using android::net::XfrmController;
Luke Huangf7782042018-08-08 13:13:04 +080086using android::netdutils::sSyscalls;
Robin Leeb8087362016-03-30 18:43:08 +010087
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090088#define SKIP_IF_BPF_SUPPORTED \
89 do { \
90 if (hasBpfSupport()) return; \
91 } while (0)
Chenbo Feng837ddfc2018-05-08 13:45:08 -070092
Robin Leeb8087362016-03-30 18:43:08 +010093static const char* IP_RULE_V4 = "-4";
94static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090095static const int TEST_NETID1 = 65501;
96static const int TEST_NETID2 = 65502;
97constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090098
Benedict Wongb2daefb2017-12-06 22:05:46 -080099static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
100static const std::string ESP_ALLOW_RULE("esp");
101
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900102class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900103 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900104 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900105 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900106 sp<IBinder> binder = sm->getService(String16("netd"));
107 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900108 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900109 }
110 }
111
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900112 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900113 ASSERT_NE(nullptr, mNetd.get());
114 }
115
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900116 void TearDown() override {
117 mNetd->networkDestroy(TEST_NETID1);
118 mNetd->networkDestroy(TEST_NETID2);
119 }
120
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900121 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700122
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900123 // Static because setting up the tun interface takes about 40ms.
124 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900125 ASSERT_EQ(0, sTun.init());
126 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900127 }
128
129 static void TearDownTestCase() {
130 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900131 sTun.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900132 }
133
134 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900135
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900136 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900137 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900138 static TunInterface sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900139};
140
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900141TunInterface BinderTest::sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900142
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900143class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900144 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700145 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900146 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900147 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900148 }
149
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900150 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900151 std::string mName;
152};
153
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900154TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900155 TimedOperation t("isAlive RPC");
156 bool isAlive = false;
157 mNetd->isAlive(&isAlive);
158 ASSERT_TRUE(isAlive);
159}
160
161static int randomUid() {
162 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
163}
164
Robin Leeb8087362016-03-30 18:43:08 +0100165static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900166 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900167 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
168 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900169 perror("popen");
170 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900171 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900172
173 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100174 size_t bufsize = 0;
175 ssize_t linelen = 0;
176 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900177 lines.push_back(std::string(line, linelen));
178 free(line);
179 line = nullptr;
180 }
181
182 pclose(f);
183 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900184}
185
Robin Leeb8087362016-03-30 18:43:08 +0100186static std::vector<std::string> listIpRules(const char *ipVersion) {
187 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
188 return runCommand(command);
189}
190
191static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900192 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100193 return runCommand(command);
194}
195
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900196static int iptablesRuleLineLength(const char *binary, const char *chainName) {
197 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900198}
199
Benedict Wongb2daefb2017-12-06 22:05:46 -0800200static bool iptablesRuleExists(const char *binary,
201 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900202 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800203 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900204 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800205 if(rule.find(expectedRule) != std::string::npos) {
206 return true;
207 }
208 }
209 return false;
210}
211
212static bool iptablesNoSocketAllowRuleExists(const char *chainName){
213 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
214 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
215}
216
217static bool iptablesEspAllowRuleExists(const char *chainName){
218 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
219 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
220}
221
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900222TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700223 SKIP_IF_BPF_SUPPORTED;
224
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900225 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
226 const int kNumUids = 500;
227 std::vector<int32_t> noUids(0);
228 std::vector<int32_t> uids(kNumUids);
229 for (int i = 0; i < kNumUids; i++) {
230 uids[i] = randomUid();
231 }
232
233 bool ret;
234 {
235 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900236 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900237 }
238 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800239 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
240 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
241 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
242 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900243 {
244 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900245 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900246 }
247 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900248 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
249 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900250
251 {
252 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900253 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900254 }
255 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900256 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
257 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800258 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
259 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900260
261 {
262 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900263 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900264 }
265 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900266 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
267 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900268
269 // Check that the call fails if iptables returns an error.
270 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900271 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900272 EXPECT_EQ(false, ret);
273}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900274
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900275TEST_F(BinderTest, VirtualTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700276 const struct TestData {
277 const std::string family;
278 const std::string deviceName;
279 const std::string localAddress;
280 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800281 int32_t iKey;
282 int32_t oKey;
283 } kTestData[] = {
Nathan Harold21299f72018-03-16 20:13:03 -0700284 {"IPV4", "test_vti", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53},
285 {"IPV6", "test_vti6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50},
manojboopathi8707f232018-01-02 14:45:47 -0800286 };
287
Luke Huangc3252cc2018-10-16 15:43:23 +0800288 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700289 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800290
291 binder::Status status;
292
293 // Create Virtual Tunnel Interface.
Nathan Harold21299f72018-03-16 20:13:03 -0700294 status = mNetd->addVirtualTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
295 td.iKey, td.oKey);
manojboopathi8707f232018-01-02 14:45:47 -0800296 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
297
298 // Update Virtual Tunnel Interface.
299 status = mNetd->updateVirtualTunnelInterface(td.deviceName, td.localAddress,
300 td.remoteAddress, td.iKey, td.oKey);
301 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
302
303 // Remove Virtual Tunnel Interface.
304 status = mNetd->removeVirtualTunnelInterface(td.deviceName);
305 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
306 }
307}
308
Nathan Harold2deff322018-05-10 14:03:48 -0700309// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
310// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
311#if INTPTR_MAX != INT32_MAX
Benedict Wonga04ffa72018-05-09 21:42:42 -0700312static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
313 static_cast<int>(android::net::XfrmDirection::OUT)};
314static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
315
Nathan Harold21299f72018-03-16 20:13:03 -0700316#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
317 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900318bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Nathan Harold21299f72018-03-16 20:13:03 -0700319 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
320 SCOPED_TRACE(status);
321 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
322
323 // Add a policy
Benedict Wonga04ffa72018-05-09 21:42:42 -0700324 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700325 SCOPED_TRACE(status);
326 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
327
328 // Add an ipsec interface
329 status = netdutils::statusFromErrno(
330 XfrmController::addVirtualTunnelInterface(
331 "ipsec_test", "::", "::1", 0xF00D, 0xD00D, false),
332 "addVirtualTunnelInterface");
333 return (status.ok() == expectOk);
334}
335
Benedict Wonga04ffa72018-05-09 21:42:42 -0700336TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
337 binder::Status status;
338
339 // Repeat to ensure cleanup and recreation works correctly
340 for (int i = 0; i < 2; i++) {
341 for (int direction : XFRM_DIRECTIONS) {
342 for (int addrFamily : ADDRESS_FAMILIES) {
343 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
344 "127.0.0.6", 123, 0, 0);
345 EXPECT_TRUE(status.isOk())
346 << " family: " << addrFamily << " direction: " << direction;
347 }
348 }
349
350 // Cleanup
351 for (int direction : XFRM_DIRECTIONS) {
352 for (int addrFamily : ADDRESS_FAMILIES) {
353 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0);
354 EXPECT_TRUE(status.isOk());
355 }
356 }
357 }
358}
359
360TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
361 binder::Status status;
362
363 // Repeat to ensure cleanup and recreation works correctly
364 for (int i = 0; i < 2; i++) {
365 for (int direction : XFRM_DIRECTIONS) {
366 for (int addrFamily : ADDRESS_FAMILIES) {
367 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
368 "2001:db8::d00d", 123, 0, 0);
369 EXPECT_TRUE(status.isOk())
370 << " family: " << addrFamily << " direction: " << direction;
371 }
372 }
373
374 // Cleanup
375 for (int direction : XFRM_DIRECTIONS) {
376 for (int addrFamily : ADDRESS_FAMILIES) {
377 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0);
378 EXPECT_TRUE(status.isOk());
379 }
380 }
381 }
382}
383
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900384TEST_F(BinderTest, XfrmControllerInit) {
Nathan Harold21299f72018-03-16 20:13:03 -0700385 netdutils::Status status;
386 status = XfrmController::Init();
387 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700388
389 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
390 // feature.
391 if (status.code() == EOPNOTSUPP) return;
392
Nathan Harold21299f72018-03-16 20:13:03 -0700393 ASSERT_TRUE(status.ok());
394
395 int32_t spi = 0;
396
397 ASSERT_TRUE(allocateIpSecResources(true, &spi));
398 ASSERT_TRUE(allocateIpSecResources(false, &spi));
399
400 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700401 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700402 ASSERT_TRUE(allocateIpSecResources(true, &spi));
403
404 // Clean up
405 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0);
406 SCOPED_TRACE(status);
407 ASSERT_TRUE(status.ok());
408
Benedict Wonga04ffa72018-05-09 21:42:42 -0700409 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700410 SCOPED_TRACE(status);
411 ASSERT_TRUE(status.ok());
412
413 // Remove Virtual Tunnel Interface.
414 status = netdutils::statusFromErrno(
415 XfrmController::removeVirtualTunnelInterface("ipsec_test"),
416 "removeVirtualTunnelInterface");
417
418 ASSERT_TRUE(status.ok());
419}
Nathan Harold2deff322018-05-10 14:03:48 -0700420#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700421
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900422static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900423 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900424
425 // Output looks like this:
426 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900427 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900428 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900429 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900430 //
431 // or:
432 //
433 // Chain bw_data_saver (1 references)
434 // target prot opt source destination
435 // ... possibly connectivity critical packet rules here ...
436 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900437
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900438 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900439
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900440 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
441 // Data saver disabled.
442 return 0;
443 }
444
445 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
446
447 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
448 // Data saver enabled.
449 return 1;
450 }
451
452 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900453}
454
455bool enableDataSaver(sp<INetd>& netd, bool enable) {
456 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
457 bool ret;
458 netd->bandwidthEnableDataSaver(enable, &ret);
459 return ret;
460}
461
462int getDataSaverState() {
463 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
464 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
465 EXPECT_EQ(enabled4, enabled6);
466 EXPECT_NE(-1, enabled4);
467 EXPECT_NE(-1, enabled6);
468 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
469 return -1;
470 }
471 return enabled6;
472}
473
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900474TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900475 const int wasEnabled = getDataSaverState();
476 ASSERT_NE(-1, wasEnabled);
477
478 if (wasEnabled) {
479 ASSERT_TRUE(enableDataSaver(mNetd, false));
480 EXPECT_EQ(0, getDataSaverState());
481 }
482
483 ASSERT_TRUE(enableDataSaver(mNetd, false));
484 EXPECT_EQ(0, getDataSaverState());
485
486 ASSERT_TRUE(enableDataSaver(mNetd, true));
487 EXPECT_EQ(1, getDataSaverState());
488
489 ASSERT_TRUE(enableDataSaver(mNetd, true));
490 EXPECT_EQ(1, getDataSaverState());
491
492 if (!wasEnabled) {
493 ASSERT_TRUE(enableDataSaver(mNetd, false));
494 EXPECT_EQ(0, getDataSaverState());
495 }
496}
Robin Leeb8087362016-03-30 18:43:08 +0100497
Luke Huang94658ac2018-10-18 19:35:12 +0900498static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
499 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100500 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100501 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100502 std::vector<std::string> rules = listIpRules(ipVersion);
503
504 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900505 std::string suffix =
506 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900507 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800508 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100509 return true;
510 }
511 }
512 return false;
513}
514
Luke Huang94658ac2018-10-18 19:35:12 +0900515static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
516 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100517 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
518 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
519 EXPECT_EQ(existsIp4, existsIp6);
520 return existsIp4;
521}
522
Luke Huang94658ac2018-10-18 19:35:12 +0900523namespace {
524
525UidRangeParcel makeUidRangeParcel(int start, int stop) {
526 UidRangeParcel res;
527 res.start = start;
528 res.stop = stop;
529
530 return res;
531}
532
533} // namespace
534
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900535TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800536 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
537 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
538 .serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900539 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
540 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
541
542 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
543 EXPECT_EQ(EBUSY,
544 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
545
546 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
547 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
548 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800549 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900550}
551
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900552TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900553 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
554
555 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
556 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
557 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
558
Luke Huang94658ac2018-10-18 19:35:12 +0900559 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
560 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
561 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900562 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
563
564 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
565
566 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
567 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
568 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
569 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
570
571 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
572 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
573 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
574 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
575
576 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
577}
578
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900579TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100580 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100581
Luke Huang94658ac2018-10-18 19:35:12 +0900582 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
583 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100584
585 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
586 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
587
588 // Create two valid rules.
589 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
590 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
591 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
592 for (auto const& range : uidRanges) {
593 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
594 }
595
596 // Remove the rules.
597 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
598 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
599 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
600 for (auto const& range : uidRanges) {
601 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
602 }
603
604 // Fail to remove the rules a second time after they are already deleted.
605 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
606 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
607 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
608
609 // All rules should be the same as before.
610 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
611 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
612}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900613
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900614// Create a socket pair that isLoopbackSocket won't think is local.
615void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900616 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900617 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900618 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
619
620 socklen_t addrlen = sizeof(server6);
621 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
622 ASSERT_EQ(0, listen(*serverSocket, 10));
623
Bernie Innocentif6918262018-06-11 17:37:35 +0900624 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900625 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900626 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900627 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
628 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
629
Bernie Innocentif6918262018-06-11 17:37:35 +0900630 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900631 ASSERT_NE(-1, *acceptedSocket);
632
633 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
634}
635
636void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
637 char buf[4096];
638 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
639 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
640 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
641}
642
643void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
644 // Check that the client socket was closed with ECONNABORTED.
645 int ret = write(clientSocket, "foo", sizeof("foo"));
646 int err = errno;
647 EXPECT_EQ(-1, ret);
648 EXPECT_EQ(ECONNABORTED, err);
649
650 // Check that it sent a RST to the server.
651 ret = write(acceptedSocket, "foo", sizeof("foo"));
652 err = errno;
653 EXPECT_EQ(-1, ret);
654 EXPECT_EQ(ECONNRESET, err);
655}
656
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900657TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900658 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900659 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900660
661 // Pick a random UID in the system UID range.
662 constexpr int baseUid = AID_APP - 2000;
663 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
664 int uid = baseUid + 500 + arc4random_uniform(1000);
665 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
666
667 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900668 std::vector<UidRangeParcel> uidRanges = {
669 makeUidRangeParcel(baseUid + 42, baseUid + 449),
670 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
671 makeUidRangeParcel(baseUid + 498, uid - 1),
672 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900673 };
674 // A skip list that doesn't contain UID.
675 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
676
677 // Close sockets. Our test socket should be intact.
678 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
679 checkSocketpairOpen(clientSocket, acceptedSocket);
680
681 // UID ranges that do contain uid.
682 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900683 makeUidRangeParcel(baseUid + 42, baseUid + 449),
684 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
685 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900686 };
687 // Add uid to the skip list.
688 skipUids.push_back(uid);
689
690 // Close sockets. Our test socket should still be intact because it's in the skip list.
691 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
692 checkSocketpairOpen(clientSocket, acceptedSocket);
693
694 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
695 skipUids.resize(skipUids.size() - 1);
696 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
697 checkSocketpairClosed(clientSocket, acceptedSocket);
698
699 close(clientSocket);
700 close(serverSocket);
701 close(acceptedSocket);
702}
Erik Klinecc4f2732016-08-03 11:24:27 +0900703
704namespace {
705
706int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
707 if (buf == nullptr) return -1;
708
709 int prefixLength = 0;
710 bool endOfContiguousBits = false;
711 for (unsigned int i = 0; i < buflen; i++) {
712 const uint8_t value = buf[i];
713
714 // Bad bit sequence: check for a contiguous set of bits from the high
715 // end by verifying that the inverted value + 1 is a power of 2
716 // (power of 2 iff. (v & (v - 1)) == 0).
717 const uint8_t inverse = ~value + 1;
718 if ((inverse & (inverse - 1)) != 0) return -1;
719
720 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
721
722 // Bogus netmask.
723 if (endOfContiguousBits && value != 0) return -1;
724
725 if (value != 0xff) endOfContiguousBits = true;
726 }
727
728 return prefixLength;
729}
730
731template<typename T>
732int netmaskToPrefixLength(const T *p) {
733 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
734}
735
736
737static bool interfaceHasAddress(
738 const std::string &ifname, const char *addrString, int prefixLength) {
739 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900740
741 const struct addrinfo hints = {
742 .ai_flags = AI_NUMERICHOST,
743 .ai_family = AF_UNSPEC,
744 .ai_socktype = SOCK_DGRAM,
745 };
746 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
747 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
748 return false;
749 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900750 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900751
752 struct ifaddrs *ifaddrsList = nullptr;
753 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
754
755 if (getifaddrs(&ifaddrsList) != 0) {
756 return false;
757 }
758
759 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
760 if (std::string(addr->ifa_name) != ifname ||
761 addr->ifa_addr == nullptr ||
762 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
763 continue;
764 }
765
766 switch (addr->ifa_addr->sa_family) {
767 case AF_INET: {
768 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
769 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
770 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
771 continue;
772 }
773
774 if (prefixLength < 0) return true; // not checking prefix lengths
775
776 if (addr->ifa_netmask == nullptr) return false;
777 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
778 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
779 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
780 }
781 case AF_INET6: {
782 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
783 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
784 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
785 continue;
786 }
787
788 if (prefixLength < 0) return true; // not checking prefix lengths
789
790 if (addr->ifa_netmask == nullptr) return false;
791 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
792 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
793 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
794 }
795 default:
796 // Cannot happen because we have already screened for matching
797 // address families at the top of each iteration.
798 continue;
799 }
800 }
801
802 return false;
803}
804
805} // namespace
806
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900807TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900808 static const struct TestData {
809 const char *addrString;
810 const int prefixLength;
811 const bool expectSuccess;
812 } kTestData[] = {
813 { "192.0.2.1", 24, true },
814 { "192.0.2.2", 25, true },
815 { "192.0.2.3", 32, true },
816 { "192.0.2.4", 33, false },
817 { "192.not.an.ip", 24, false },
818 { "2001:db8::1", 64, true },
819 { "2001:db8::2", 65, true },
820 { "2001:db8::3", 128, true },
821 { "2001:db8::4", 129, false },
822 { "foo:bar::bad", 64, false },
823 };
824
Luke Huangc3252cc2018-10-16 15:43:23 +0800825 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900826 const auto &td = kTestData[i];
827
828 // [1.a] Add the address.
829 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900830 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900831 if (td.expectSuccess) {
832 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
833 } else {
834 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
835 ASSERT_NE(0, status.serviceSpecificErrorCode());
836 }
837
838 // [1.b] Verify the addition meets the expectation.
839 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900840 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900841 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900842 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900843 }
844
845 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900846 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900847 if (td.expectSuccess) {
848 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
849 } else {
850 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
851 ASSERT_NE(0, status.serviceSpecificErrorCode());
852 }
853
854 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900855 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900856 }
857}
Erik Kline55b06f82016-07-04 09:57:18 +0900858
Erik Kline38e51f12018-09-06 20:14:44 +0900859TEST_F(BinderTest, GetProcSysNet) {
860 const char LOOPBACK[] = "lo";
861 static const struct {
862 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900863 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900864 const char* ifname;
865 const char* parameter;
866 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900867 const int expectedReturnCode;
868 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900869 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
870 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
871 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
872 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
873 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
874 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
875 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900876 };
877
Luke Huangc3252cc2018-10-16 15:43:23 +0800878 for (int i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900879 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900880
Erik Kline38e51f12018-09-06 20:14:44 +0900881 std::string value;
882 const binder::Status status =
883 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
884
885 if (td.expectedReturnCode == 0) {
886 SCOPED_TRACE(String8::format("test case %d should have passed", i));
887 EXPECT_EQ(0, status.exceptionCode());
888 EXPECT_EQ(0, status.serviceSpecificErrorCode());
889 EXPECT_EQ(td.expectedValue, value);
890 } else {
891 SCOPED_TRACE(String8::format("test case %d should have failed", i));
892 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
893 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
894 }
895 }
896}
897
898TEST_F(BinderTest, SetProcSysNet) {
899 static const struct {
900 const int ipversion;
901 const int which;
902 const char* ifname;
903 const char* parameter;
904 const char* value;
905 const int expectedReturnCode;
906 } kTestData[] = {
907 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
908 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
909 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
910 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
911 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
912 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
913 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
914 };
915
Luke Huangc3252cc2018-10-16 15:43:23 +0800916 for (int i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900917 const auto& td = kTestData[i];
918
919 const binder::Status status =
920 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900921
922 if (td.expectedReturnCode == 0) {
923 SCOPED_TRACE(String8::format("test case %d should have passed", i));
924 EXPECT_EQ(0, status.exceptionCode());
925 EXPECT_EQ(0, status.serviceSpecificErrorCode());
926 } else {
927 SCOPED_TRACE(String8::format("test case %d should have failed", i));
928 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
929 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
930 }
931 }
932}
Ben Schwartze7601812017-04-28 16:38:29 -0400933
Erik Kline38e51f12018-09-06 20:14:44 +0900934TEST_F(BinderTest, GetSetProcSysNet) {
935 const int ipversion = INetd::IPV6;
936 const int category = INetd::NEIGH;
937 const std::string& tun = sTun.name();
938 const std::string parameter("ucast_solicit");
939
940 std::string value{};
941 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
942 EXPECT_FALSE(value.empty());
943 const int ival = std::stoi(value);
944 EXPECT_GT(ival, 0);
945 // Try doubling the parameter value (always best!).
946 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
947 .isOk());
948 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
949 EXPECT_EQ(2 * ival, std::stoi(value));
950 // Try resetting the parameter.
951 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
952 .isOk());
953 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
954 EXPECT_EQ(ival, std::stoi(value));
955}
956
Ben Schwartze7601812017-04-28 16:38:29 -0400957static std::string base64Encode(const std::vector<uint8_t>& input) {
958 size_t out_len;
959 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
960 // out_len includes the trailing NULL.
961 uint8_t output_bytes[out_len];
962 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
963 return std::string(reinterpret_cast<char*>(output_bytes));
964}
965
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900966TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900967 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400968 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400969 std::vector<uint8_t> short_fp(1);
970 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
971 std::vector<std::string> test_domains;
972 std::vector<int> test_params = { 300, 25, 8, 8 };
973 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400974 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400975 const std::vector<std::string> servers;
976 const std::string tlsName;
977 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400978 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900979 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400980 { {"192.0.2.1"}, "", {}, 0 },
981 { {"2001:db8::2"}, "host.name", {}, 0 },
982 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
983 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900984 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400985 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900986 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400987 { {"2001:dg8::6"}, "", {}, EINVAL },
988 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
989 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
990 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
991 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400992 };
993
Luke Huangc3252cc2018-10-16 15:43:23 +0800994 for (unsigned int i = 0; i < std::size(kTlsTestData); i++) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900995 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -0400996
997 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400998 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400999 fingerprints.push_back(base64Encode(fingerprint));
1000 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001001 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001002 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
1003 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -04001004
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001005 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -04001006 SCOPED_TRACE(String8::format("test case %d should have passed", i));
1007 SCOPED_TRACE(status.toString8());
1008 EXPECT_EQ(0, status.exceptionCode());
1009 } else {
1010 SCOPED_TRACE(String8::format("test case %d should have failed", i));
1011 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001012 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -04001013 }
Ben Schwartze7601812017-04-28 16:38:29 -04001014 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001015 // Ensure TLS is disabled before the start of the next test.
1016 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001017 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1018 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001019}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001020
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001021namespace {
1022
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001023void expectNoTestCounterRules() {
1024 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1025 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1026 std::string allRules = Join(runCommand(command), "\n");
1027 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1028 }
1029}
1030
Bernie Innocentif6918262018-06-11 17:37:35 +09001031void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1032 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001033 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1034 path, if1.c_str(), if2.c_str(), pkt, byte));
1035}
1036
Bernie Innocentif6918262018-06-11 17:37:35 +09001037void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001038 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1039 path, if1.c_str(), if2.c_str()));
1040 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1041 path, if2.c_str(), if1.c_str()));
1042}
1043
Luke Huangcaebcbb2018-09-27 20:37:14 +08001044std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1045 const std::string& iface) {
1046 for (auto& stats : statsVec) {
1047 if (stats.iface == iface) {
1048 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1049 }
1050 }
1051 return {};
1052}
1053
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001054} // namespace
1055
1056TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001057 expectNoTestCounterRules();
1058
1059 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1060 // disabling tethering. We don't check the return value because these commands will fail if
1061 // tethering is already enabled.
1062 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1063 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1064
1065 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1066 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1067 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1068 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1069 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1070
1071 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1072 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1073 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1074 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1075 // RX is from external to internal, and TX is from internal to external.
1076 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1077 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1078
1079 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1080 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1081
1082 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1083 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1084
1085 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1086 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1087 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1088
Luke Huangcaebcbb2018-09-27 20:37:14 +08001089 std::vector<TetherStatsParcel> statsVec;
1090 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001091 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1092
Luke Huangcaebcbb2018-09-27 20:37:14 +08001093 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001094
Luke Huangcaebcbb2018-09-27 20:37:14 +08001095 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001096
1097 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1098 delTetherCounterValues(path, intIface1, extIface1);
1099 delTetherCounterValues(path, intIface2, extIface2);
1100 if (path == IP6TABLES_PATH) {
1101 delTetherCounterValues(path, intIface3, extIface2);
1102 }
1103 }
1104
1105 expectNoTestCounterRules();
1106}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001107
Luke Huang0051a622018-07-23 20:30:16 +08001108namespace {
1109
Luke Huanga5211072018-08-01 23:36:29 +08001110constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1111constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001112
1113static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1114 const char* chainName) {
1115 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1116 return runCommand(command);
1117}
1118
Luke Huanga5211072018-08-01 23:36:29 +08001119bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001120 const std::string& expectedInterface,
1121 const std::string& expectedRule, const char* table) {
1122 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1123 for (const auto& rule : rules) {
1124 if (rule.find(expectedInterface) != std::string::npos) {
1125 if (rule.find(expectedRule) != std::string::npos) {
1126 return true;
1127 }
1128 }
1129 }
1130 return false;
1131}
1132
1133void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001134 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001135 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001136 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001137 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001138 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1139 IdletimerRule, RAW_TABLE));
1140 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001141 ifname, IdletimerRule, MANGLE_TABLE));
1142 }
1143}
1144
1145void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001146 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001147 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001148 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001149 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001150 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1151 IdletimerRule, RAW_TABLE));
1152 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001153 ifname, IdletimerRule, MANGLE_TABLE));
1154 }
1155}
1156
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001157} // namespace
1158
1159TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001160 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1161 // rule in the table. Because we only check the result after calling remove function. We might
1162 // check the actual rule which is removed by our function (maybe compare the results between
1163 // calling function before and after)
1164 binder::Status status;
1165 const struct TestData {
1166 const std::string ifname;
1167 int32_t timeout;
1168 const std::string classLabel;
1169 } idleTestData[] = {
1170 {"wlan0", 1234, "happyday"},
1171 {"rmnet_data0", 4567, "friday"},
1172 };
1173 for (const auto& td : idleTestData) {
1174 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1175 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1176 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1177
1178 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1179 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1180 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1181 }
1182}
1183
Luke Huanga67dd562018-07-17 19:58:25 +08001184namespace {
1185
1186constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1187constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1188
1189void expectStrictSetUidAccept(const int uid) {
1190 std::string uidRule = StringPrintf("owner UID match %u", uid);
1191 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1192 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1193 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1194 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1195 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1196 }
1197}
1198
1199void expectStrictSetUidLog(const int uid) {
1200 static const char logRule[] = "st_penalty_log all";
1201 std::string uidRule = StringPrintf("owner UID match %u", uid);
1202 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1203 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1204 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1205 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1206 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1207 }
1208}
1209
1210void expectStrictSetUidReject(const int uid) {
1211 static const char rejectRule[] = "st_penalty_reject all";
1212 std::string uidRule = StringPrintf("owner UID match %u", uid);
1213 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1214 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1215 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1216 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1217 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1218 }
1219}
1220
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001221} // namespace
1222
1223TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001224 binder::Status status;
1225 int32_t uid = randomUid();
1226
1227 // setUidCleartextPenalty Policy:Log with randomUid
1228 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1229 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1230 expectStrictSetUidLog(uid);
1231
1232 // setUidCleartextPenalty Policy:Accept with randomUid
1233 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1234 expectStrictSetUidAccept(uid);
1235
1236 // setUidCleartextPenalty Policy:Reject with randomUid
1237 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1238 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1239 expectStrictSetUidReject(uid);
1240
1241 // setUidCleartextPenalty Policy:Accept with randomUid
1242 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1243 expectStrictSetUidAccept(uid);
1244
1245 // test wrong policy
1246 int32_t wrongPolicy = -123;
1247 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1248 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1249}
1250
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001251namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001252
Luke Huanga5211072018-08-01 23:36:29 +08001253bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001254 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1255 return (runCommand(cmd.c_str()).size()) ? true : false;
1256}
1257
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001258} // namespace
1259
1260TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001261 binder::Status status;
1262 // use dummy0 for test since it is set ready
1263 static const char testIf[] = "dummy0";
1264 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1265
1266 status = mNetd->clatdStart(testIf);
1267 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1268 EXPECT_TRUE(processExists(clatdName));
1269
1270 mNetd->clatdStop(testIf);
1271 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1272 EXPECT_FALSE(processExists(clatdName));
1273}
Luke Huang457d4702018-08-16 15:39:15 +08001274
1275namespace {
1276
1277bool getIpfwdV4Enable() {
1278 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1279 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1280 EXPECT_TRUE(!result.empty());
1281 int v4Enable = std::stoi(result[0]);
1282 return v4Enable;
1283}
1284
1285bool getIpfwdV6Enable() {
1286 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1287 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1288 EXPECT_TRUE(!result.empty());
1289 int v6Enable = std::stoi(result[0]);
1290 return v6Enable;
1291}
1292
1293void expectIpfwdEnable(bool enable) {
1294 int enableIPv4 = getIpfwdV4Enable();
1295 int enableIPv6 = getIpfwdV6Enable();
1296 EXPECT_EQ(enable, enableIPv4);
1297 EXPECT_EQ(enable, enableIPv6);
1298}
1299
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001300bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001301 std::vector<std::string> rules = listIpRules(ipVersion);
1302 for (const auto& rule : rules) {
1303 if (rule.find(ipfwdRule) != std::string::npos) {
1304 return true;
1305 }
1306 }
1307 return false;
1308}
1309
1310void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1311 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1312
1313 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1314 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1315 }
1316}
1317
1318void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1319 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1320
1321 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1322 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1323 }
1324}
1325
1326} // namespace
1327
1328TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1329 // Netd default enable Ipfwd with requester NetdHwService
1330 const std::string defaultRequester = "NetdHwService";
1331
1332 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1333 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1334 expectIpfwdEnable(false);
1335
1336 bool ipfwdEnabled;
1337 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1338 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1339 EXPECT_FALSE(ipfwdEnabled);
1340
1341 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1342 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1343 expectIpfwdEnable(true);
1344
1345 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1346 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1347 EXPECT_TRUE(ipfwdEnabled);
1348}
1349
1350TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1351 static const char testFromIf[] = "dummy0";
1352 static const char testToIf[] = "dummy0";
1353
1354 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1355 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1356 expectIpfwdRuleExists(testFromIf, testToIf);
1357
1358 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1359 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1360 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001361}
Luke Huang531f5d32018-08-03 15:19:05 +08001362
1363namespace {
1364
1365constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1366constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1367constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1368constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1369constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
1370
1371// TODO: move iptablesTargetsExists and listIptablesRuleByTable to the top.
1372bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1373 const char* chainName, const std::string& expectedTargetA,
1374 const std::string& expectedTargetB) {
1375 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1376 int matchCount = 0;
1377
1378 for (const auto& rule : rules) {
1379 if (rule.find(expectedTargetA) != std::string::npos) {
1380 if (rule.find(expectedTargetB) != std::string::npos) {
1381 matchCount++;
1382 }
1383 }
1384 }
1385 return matchCount == expectedCount;
1386}
1387
1388void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1389 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1390 std::string result = "";
1391
1392 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001393 // Quota value might be decreased while matching packets
1394 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001395}
1396
1397void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1398 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1399 std::string quotaRule = StringPrintf("quota %s", ifname);
1400
1401 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1402 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1403 BANDWIDTH_COSTLY_IF));
1404 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1405 BANDWIDTH_COSTLY_IF));
1406 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1407 BANDWIDTH_COSTLY_IF));
1408 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1409 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1410 }
1411 expectXtQuotaValueEqual(ifname, quotaBytes);
1412}
1413
1414void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1415 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1416 std::string quotaRule = StringPrintf("quota %s", ifname);
1417
1418 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1419 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1420 BANDWIDTH_COSTLY_IF));
1421 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1422 BANDWIDTH_COSTLY_IF));
1423 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1424 BANDWIDTH_COSTLY_IF));
1425 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1426 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1427 }
1428}
1429
1430void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1431 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1432 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1433 std::string alertName = StringPrintf("%sAlert", ifname);
1434
1435 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1436 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1437 }
1438 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1439}
1440
1441void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1442 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1443 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1444
1445 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1446 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1447 }
1448}
1449
1450void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1451 static const char globalAlertRule[] = "quota globalAlert";
1452 static const char globalAlertName[] = "globalAlert";
1453
1454 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1455 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_INPUT, globalAlertRule));
1456 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_OUTPUT, globalAlertRule));
1457 }
1458 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1459}
1460
1461void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1462 std::string uidRule = StringPrintf("owner UID match %u", uid);
1463
1464 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1465 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1466 }
1467}
1468
1469void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1470 std::string uidRule = StringPrintf("owner UID match %u", uid);
1471
1472 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1473 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1474 }
1475}
1476
1477} // namespace
1478
1479TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1480 long testQuotaBytes = 5550;
1481
1482 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001483 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001484 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1485
1486 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1487 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1488 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1489
1490 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1491 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1492 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1493
1494 // Remove test physical network
1495 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1496}
1497
1498TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1499 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001500 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001501 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001502 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001503 // Need to have a prior interface quota set to set an alert
1504 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1505 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1506 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1507 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1508
1509 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1510 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1511 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1512
1513 // Remove interface quota
1514 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1515 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1516 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1517
1518 // Remove test physical network
1519 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1520}
1521
1522TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1523 long testAlertBytes = 2097149;
1524
1525 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1526 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1527 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1528
1529 testAlertBytes = 2097152;
1530 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1531 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1532 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1533}
1534
1535TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1536 SKIP_IF_BPF_SUPPORTED;
1537
1538 int32_t uid = randomUid();
1539 static const char targetReject[] = "REJECT";
1540 static const char targetReturn[] = "RETURN";
1541
1542 // add NaughtyApp
1543 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1544 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1545 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1546
1547 // remove NaughtyApp
1548 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1549 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1550 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1551
1552 // add NiceApp
1553 status = mNetd->bandwidthAddNiceApp(uid);
1554 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1555 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1556
1557 // remove NiceApp
1558 status = mNetd->bandwidthRemoveNiceApp(uid);
1559 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1560 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1561}
Luke Huangb5733d72018-08-21 17:17:19 +08001562
1563namespace {
1564
Luke Huangb670d162018-08-23 20:01:13 +08001565std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1566 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1567 return runCommand(command);
1568}
1569
Luke Huangc3252cc2018-10-16 15:43:23 +08001570bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001571 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1572 for (const auto& route : routes) {
1573 if (route.find(ipRoute) != std::string::npos) {
1574 return true;
1575 }
1576 }
1577 return false;
1578}
1579
Luke Huangc3252cc2018-10-16 15:43:23 +08001580std::string ipRouteString(const std::string& ifName, const std::string& dst,
1581 const std::string& nextHop) {
1582 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1583
1584 if (!nextHop.empty()) {
1585 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001586 }
1587
Luke Huangc3252cc2018-10-16 15:43:23 +08001588 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001589}
1590
Luke Huangc3252cc2018-10-16 15:43:23 +08001591void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1592 const std::string& dst, const std::string& nextHop,
1593 const char* table) {
1594 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1595}
1596
1597void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001598 const std::string& dst, const std::string& nextHop,
1599 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001600 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001601}
1602
1603bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1604 std::vector<std::string> rules = listIpRules(ipVersion);
1605 for (const auto& rule : rules) {
1606 if (rule.find(ipRule) != std::string::npos) {
1607 return true;
1608 }
1609 }
1610 return false;
1611}
1612
1613void expectNetworkDefaultIpRuleExists(const char* ifName) {
1614 std::string networkDefaultRule =
1615 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1616
1617 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1618 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1619 }
1620}
1621
1622void expectNetworkDefaultIpRuleDoesNotExist() {
1623 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1624
1625 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1626 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1627 }
1628}
1629
1630void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1631 std::string networkPermissionRule = "";
1632 switch (permission) {
1633 case INetd::PERMISSION_NONE:
1634 networkPermissionRule = StringPrintf(
1635 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1636 break;
1637 case INetd::PERMISSION_NETWORK:
1638 networkPermissionRule = StringPrintf(
1639 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1640 break;
1641 case INetd::PERMISSION_SYSTEM:
1642 networkPermissionRule = StringPrintf(
1643 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1644 break;
1645 }
1646
1647 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1648 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1649 }
1650}
1651
1652// TODO: It is a duplicate function, need to remove it
1653bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1654 const std::string& expectedInterface,
1655 const std::string& expectedRule,
1656 const char* table) {
1657 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1658 for (const auto& rule : rules) {
1659 if (rule.find(expectedInterface) != std::string::npos) {
1660 if (rule.find(expectedRule) != std::string::npos) {
1661 return true;
1662 }
1663 }
1664 }
1665 return false;
1666}
1667
1668void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1669 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1670 std::string networkIncomingPacketMarkRule = "";
1671 switch (permission) {
1672 case INetd::PERMISSION_NONE:
1673 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1674 break;
1675 case INetd::PERMISSION_NETWORK:
1676 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1677 break;
1678 case INetd::PERMISSION_SYSTEM:
1679 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1680 break;
1681 }
1682
1683 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1684 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1685 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1686 }
1687}
1688
1689} // namespace
1690
1691TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001692 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001693 const char* ipVersion;
1694 const char* testDest;
1695 const char* testNextHop;
1696 const bool expectSuccess;
1697 } kTestData[] = {
1698 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001699 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1700 {IP_RULE_V4, "10.251.0.0/16", "", true},
1701 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1702 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001703 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001704 {IP_RULE_V6, "::/0", "2001:db8::", true},
1705 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001706 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1707 };
1708
Luke Huangc3252cc2018-10-16 15:43:23 +08001709 static const struct {
1710 const char* ipVersion;
1711 const char* testDest;
1712 const char* testNextHop;
1713 } kTestDataWithNextHop[] = {
1714 {IP_RULE_V4, "10.251.10.0/30", ""},
1715 {IP_RULE_V6, "2001:db8::/32", ""},
1716 };
1717
Luke Huangb670d162018-08-23 20:01:13 +08001718 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001719 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001720 const int testUid = randomUid();
1721 const std::vector<int32_t> testUids = {testUid};
1722
1723 // Add test physical network
1724 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1725 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1726
Luke Huangc3252cc2018-10-16 15:43:23 +08001727 // Setup route for testing nextHop
1728 for (unsigned int i = 0; i < std::size(kTestDataWithNextHop); i++) {
1729 const auto& td = kTestDataWithNextHop[i];
1730
1731 // All route for test tun will disappear once the tun interface is deleted.
1732 binder::Status status =
1733 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1734 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1735 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1736 sTun.name().c_str());
1737
1738 // Add system permission for test uid, setup route in legacy system table.
1739 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1740
1741 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1742 testUid);
1743 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1744 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1745 testTableLegacySystem);
1746
1747 // Remove system permission for test uid, setup route in legacy network table.
1748 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1749
1750 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1751 testUid);
1752 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1753 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1754 testTableLegacyNetwork);
1755 }
1756
1757 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001758 const auto& td = kTestData[i];
1759
1760 binder::Status status =
1761 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1762 if (td.expectSuccess) {
1763 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001764 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001765 sTun.name().c_str());
1766 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001767 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1768 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001769 }
1770
1771 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1772 if (td.expectSuccess) {
1773 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001774 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1775 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001776 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001777 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1778 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001779 }
1780
Luke Huangc3252cc2018-10-16 15:43:23 +08001781 // Add system permission for test uid, route will be added into legacy system table.
1782 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001783
1784 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1785 testUid);
1786 if (td.expectSuccess) {
1787 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001788 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001789 testTableLegacySystem);
1790 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001791 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1792 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001793 }
1794
1795 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1796 td.testNextHop, testUid);
1797 if (td.expectSuccess) {
1798 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001799 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1800 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001801 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001802 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1803 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001804 }
1805
Luke Huangc3252cc2018-10-16 15:43:23 +08001806 // Remove system permission for test uid, route will be added into legacy network table.
1807 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1808
1809 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1810 testUid);
1811 if (td.expectSuccess) {
1812 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1813 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1814 testTableLegacyNetwork);
1815 } else {
1816 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1817 EXPECT_NE(0, status.serviceSpecificErrorCode());
1818 }
1819
1820 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1821 td.testNextHop, testUid);
1822 if (td.expectSuccess) {
1823 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1824 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1825 testTableLegacyNetwork);
1826 } else {
1827 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1828 EXPECT_NE(0, status.serviceSpecificErrorCode());
1829 }
Luke Huangb670d162018-08-23 20:01:13 +08001830 }
1831
1832 // Remove test physical network
1833 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1834}
1835
1836TEST_F(BinderTest, NetworkPermissionDefault) {
1837 // Add test physical network
1838 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1839 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1840
Luke Huangc3252cc2018-10-16 15:43:23 +08001841 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001842 int currentNetid;
1843 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1844 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1845
1846 // Test SetDefault
1847 status = mNetd->networkSetDefault(TEST_NETID1);
1848 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1849 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1850
1851 status = mNetd->networkClearDefault();
1852 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1853 expectNetworkDefaultIpRuleDoesNotExist();
1854
1855 // Add default network back
1856 status = mNetd->networkSetDefault(currentNetid);
1857 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1858
1859 // Test SetPermission
1860 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1861 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1862 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1863 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1864
1865 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1866 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1867 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1868 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1869
1870 // Remove test physical network
1871 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1872}
1873
1874TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1875 const int testUid = randomUid();
1876 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1877 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1878 bool ret = false;
1879 status = mNetd->networkCanProtect(testUid, &ret);
1880 EXPECT_TRUE(ret);
1881
1882 status = mNetd->networkSetProtectDeny(testUid);
1883 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1884 status = mNetd->networkCanProtect(testUid, &ret);
1885 EXPECT_FALSE(ret);
1886}
1887
1888namespace {
1889
Luke Huangb5733d72018-08-21 17:17:19 +08001890int readIntFromPath(const std::string& path) {
1891 std::string result = "";
1892 EXPECT_TRUE(ReadFileToString(path, &result));
1893 return std::stoi(result);
1894}
1895
1896int getTetherAcceptIPv6Ra(const std::string& ifName) {
1897 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1898 return readIntFromPath(path);
1899}
1900
1901bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1902 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1903 return readIntFromPath(path);
1904}
1905
1906int getTetherIPv6DadTransmits(const std::string& ifName) {
1907 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1908 return readIntFromPath(path);
1909}
1910
1911bool getTetherEnableIPv6(const std::string& ifName) {
1912 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1913 int disableIPv6 = readIntFromPath(path);
1914 return !disableIPv6;
1915}
1916
1917bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1918 for (const auto& iface : ifList) {
1919 if (iface == ifName) {
1920 return true;
1921 }
1922 }
1923 return false;
1924}
1925
1926void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1927 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1928 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1929 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1930 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1931}
1932
1933void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1934 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1935 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1936 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1937 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1938}
1939
1940void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1941 const std::string& ifName) {
1942 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1943}
1944
1945void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1946 const std::string& ifName) {
1947 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1948}
1949
1950void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
1951 const std::vector<std::string>& testDnsAddrs) {
1952 EXPECT_TRUE(dnsList == testDnsAddrs);
1953}
1954
1955} // namespace
1956
1957TEST_F(BinderTest, TetherStartStopStatus) {
1958 std::vector<std::string> noDhcpRange = {};
1959 static const char dnsdName[] = "dnsmasq";
1960
1961 binder::Status status = mNetd->tetherStart(noDhcpRange);
1962 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1963 EXPECT_TRUE(processExists(dnsdName));
1964
1965 bool tetherEnabled;
1966 status = mNetd->tetherIsEnabled(&tetherEnabled);
1967 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1968 EXPECT_TRUE(tetherEnabled);
1969
1970 status = mNetd->tetherStop();
1971 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1972 EXPECT_FALSE(processExists(dnsdName));
1973
1974 status = mNetd->tetherIsEnabled(&tetherEnabled);
1975 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1976 EXPECT_FALSE(tetherEnabled);
1977}
1978
1979TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
1980 // TODO: verify if dnsmasq update interface successfully
1981
1982 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
1983 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1984 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
1985
1986 std::vector<std::string> ifList;
1987 status = mNetd->tetherInterfaceList(&ifList);
1988 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1989 expectTetherInterfaceExists(ifList, sTun.name());
1990
1991 status = mNetd->tetherInterfaceRemove(sTun.name());
1992 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1993 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
1994
1995 status = mNetd->tetherInterfaceList(&ifList);
1996 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1997 expectTetherInterfaceNotExists(ifList, sTun.name());
1998}
1999
2000TEST_F(BinderTest, TetherDnsSetList) {
2001 // TODO: verify if dnsmasq update dns successfully
2002 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
2003
2004 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2005 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2006
2007 std::vector<std::string> dnsList;
2008 status = mNetd->tetherDnsList(&dnsList);
2009 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2010 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002011}
2012
2013namespace {
2014
2015constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2016constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2017constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2018constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2019constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2020constexpr char FIREWALL_STANDBY[] = "fw_standby";
2021constexpr char targetReturn[] = "RETURN";
2022constexpr char targetDrop[] = "DROP";
2023
2024void expectFirewallWhitelistMode() {
2025 static const char dropRule[] = "DROP all";
2026 static const char rejectRule[] = "REJECT all";
2027 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2028 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2029 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2030 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2031 }
2032}
2033
2034void expectFirewallBlacklistMode() {
2035 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2036 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2037 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2038 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2039 }
2040}
2041
2042bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2043 const std::string& expectedInterface,
2044 const std::string& expectedRule) {
2045 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2046 // Expected rule:
2047 // Chain fw_INPUT (1 references)
2048 // pkts bytes target prot opt in out source destination
2049 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2050 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2051 int firstRuleIndex = 2;
2052 if (rules.size() < 4) return false;
2053 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2054 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2055 return true;
2056 }
2057 }
2058 return false;
2059}
2060
2061// TODO: It is a duplicate function, need to remove it
2062bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2063 const std::string& expectedInterface,
2064 const std::string& expectedRule) {
2065 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2066 for (const auto& rule : rules) {
2067 if (rule.find(expectedInterface) != std::string::npos) {
2068 if (rule.find(expectedRule) != std::string::npos) {
2069 return true;
2070 }
2071 }
2072 }
2073 return false;
2074}
2075
2076void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2077 static const char returnRule[] = "RETURN all";
2078 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2079 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2080 returnRule));
2081 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2082 returnRule));
2083 }
2084}
2085
2086void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2087 static const char returnRule[] = "RETURN all";
2088 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2089 EXPECT_FALSE(
2090 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2091 EXPECT_FALSE(
2092 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2093 }
2094}
2095
2096bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2097 const std::string& expectedTarget,
2098 const std::string& expectedRule) {
2099 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2100 int firstRuleIndex = 2;
2101 if (rules.size() < 4) return false;
2102 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2103 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2104 return true;
2105 }
2106 }
2107 return false;
2108}
2109
2110bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2111 const std::string& expectedTarget,
2112 const std::string& expectedRule) {
2113 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2114 int lastRuleIndex = rules.size() - 1;
2115 if (lastRuleIndex < 0) return false;
2116 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2117 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2118 return true;
2119 }
2120 }
2121 return false;
2122}
2123
2124void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2125 std::string uidRule = StringPrintf("owner UID match %u", uid);
2126 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2127 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2128}
2129
2130void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2131 std::string uidRule = StringPrintf("owner UID match %u", uid);
2132 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2133 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2134}
2135
2136void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2137 std::string uidRule = StringPrintf("owner UID match %u", uid);
2138 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2139 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2140}
2141
2142void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2143 std::string uidRule = StringPrintf("owner UID match %u", uid);
2144 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2145 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2146}
2147
2148bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2149 std::vector<std::string> inputRules =
2150 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2151 std::vector<std::string> outputRules =
2152 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2153 int inputLastRuleIndex = inputRules.size() - 1;
2154 int outputLastRuleIndex = outputRules.size() - 1;
2155
2156 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2157 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2158 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2159 return true;
2160 }
2161 }
2162 return false;
2163}
2164
2165void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2166 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2167 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2168}
2169
2170void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2171 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2172 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2173 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2174 }
2175}
2176
2177} // namespace
2178
2179TEST_F(BinderTest, FirewallSetFirewallType) {
2180 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2181 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2182 expectFirewallWhitelistMode();
2183
2184 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2185 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2186 expectFirewallBlacklistMode();
2187
2188 // set firewall type blacklist twice
2189 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2190 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2191 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2192 expectFirewallBlacklistMode();
2193
2194 // set firewall type whitelist twice
2195 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2196 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2197 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2198 expectFirewallWhitelistMode();
2199
2200 // reset firewall type to default
2201 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2202 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2203 expectFirewallBlacklistMode();
2204}
2205
2206TEST_F(BinderTest, FirewallSetInterfaceRule) {
2207 // setinterfaceRule is not supported in BLACKLIST MODE
2208 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2209 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2210
2211 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2212 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2213
2214 // set WHITELIST mode first
2215 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2216 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2217
2218 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2219 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2220 expectFirewallInterfaceRuleAllowExists(sTun.name());
2221
2222 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2223 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2224 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2225
2226 // reset firewall mode to default
2227 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2228 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2229 expectFirewallBlacklistMode();
2230}
2231
2232TEST_F(BinderTest, FirewallSetUidRule) {
2233 SKIP_IF_BPF_SUPPORTED;
2234
2235 int32_t uid = randomUid();
2236
2237 // Doze allow
2238 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2239 INetd::FIREWALL_RULE_ALLOW);
2240 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2241 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2242
2243 // Doze deny
2244 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2245 INetd::FIREWALL_RULE_DENY);
2246 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2247 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2248
2249 // Powersave allow
2250 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2251 INetd::FIREWALL_RULE_ALLOW);
2252 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2253 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2254
2255 // Powersave deny
2256 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2257 INetd::FIREWALL_RULE_DENY);
2258 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2259 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2260
2261 // Standby deny
2262 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2263 INetd::FIREWALL_RULE_DENY);
2264 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2265 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2266
2267 // Standby allow
2268 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2269 INetd::FIREWALL_RULE_ALLOW);
2270 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2271 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2272
2273 // None deny in BLACKLIST
2274 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2275 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2276 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2277 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2278
2279 // None allow in BLACKLIST
2280 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2281 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2282 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2283 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2284
2285 // set firewall type whitelist twice
2286 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2287 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2288 expectFirewallWhitelistMode();
2289
2290 // None allow in WHITELIST
2291 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2292 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2293 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2294 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2295
2296 // None deny in WHITELIST
2297 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2298 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2299 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2300 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2301
2302 // reset firewall mode to default
2303 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2304 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2305 expectFirewallBlacklistMode();
2306}
2307
2308TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2309 SKIP_IF_BPF_SUPPORTED;
2310
2311 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2312 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2313 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2314
2315 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2316 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2317 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2318
2319 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2320 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2321 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2322
2323 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2324 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2325 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2326
2327 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2328 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2329 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2330
2331 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2332 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2333 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2334}
Luke Huangf7782042018-08-08 13:13:04 +08002335
2336namespace {
2337
2338std::string hwAddrToStr(unsigned char* hwaddr) {
2339 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2340 hwaddr[4], hwaddr[5]);
2341}
2342
2343int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2344 int prefixLength = 0;
2345 uint32_t m = ntohl(mask);
2346 while (m & (1 << 31)) {
2347 prefixLength++;
2348 m = m << 1;
2349 }
2350 return prefixLength;
2351}
2352
2353std::string toStdString(const String16& s) {
2354 return std::string(String8(s.string()));
2355}
2356
2357android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2358 const auto& sys = sSyscalls.get();
2359 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2360 EXPECT_TRUE(isOk(fd.status()));
2361
2362 struct ifreq ifr = {};
2363 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2364
2365 return sys.ioctl(fd.value(), flag, &ifr);
2366}
2367
2368std::string getInterfaceHwAddr(const std::string& ifName) {
2369 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2370
2371 unsigned char hwaddr[ETH_ALEN] = {};
2372 if (isOk(res.status())) {
2373 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2374 }
2375
2376 return hwAddrToStr(hwaddr);
2377}
2378
2379int getInterfaceIPv4Prefix(const std::string& ifName) {
2380 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2381
2382 int prefixLength = 0;
2383 if (isOk(res.status())) {
2384 prefixLength = ipv4NetmaskToPrefixLength(
2385 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2386 }
2387
2388 return prefixLength;
2389}
2390
2391std::string getInterfaceIPv4Addr(const std::string& ifName) {
2392 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2393
2394 struct in_addr addr = {};
2395 if (isOk(res.status())) {
2396 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2397 }
2398
2399 return std::string(inet_ntoa(addr));
2400}
2401
2402std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2403 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2404
2405 unsigned flags = 0;
2406 if (isOk(res.status())) {
2407 flags = res.value().ifr_flags;
2408 }
2409
2410 std::vector<std::string> ifFlags;
2411 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2412 : toStdString(INetd::IF_STATE_DOWN()));
2413
2414 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2415 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2416 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2417 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2418 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2419
2420 return ifFlags;
2421}
2422
2423bool compareListInterface(const std::vector<std::string>& interfaceList) {
2424 const auto& res = InterfaceController::getIfaceNames();
2425 EXPECT_TRUE(isOk(res));
2426
2427 std::vector<std::string> resIfList;
2428 resIfList.reserve(res.value().size());
2429 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2430
2431 return resIfList == interfaceList;
2432}
2433
2434int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2435 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2436 return readIntFromPath(path);
2437}
2438
2439bool getInterfaceEnableIPv6(const std::string& ifName) {
2440 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2441
2442 int disableIPv6 = readIntFromPath(path);
2443 return !disableIPv6;
2444}
2445
2446int getInterfaceMtu(const std::string& ifName) {
2447 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2448 return readIntFromPath(path);
2449}
2450
2451void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2452 EXPECT_TRUE(compareListInterface(interfaceList));
2453}
2454
2455void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2456 const InterfaceConfigurationParcel& interfaceCfg) {
2457 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2458 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2459 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2460 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2461}
2462
2463void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2464 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2465 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2466
2467 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2468 for (const auto& flag : setCfg.flags) {
2469 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2470 }
2471}
2472
2473void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2474 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2475 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2476}
2477
2478void expectInterfaceNoAddr(const std::string& ifName) {
2479 // noAddr
2480 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2481 // noPrefix
2482 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2483}
2484
2485void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2486 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2487 EXPECT_EQ(enableIPv6, enable);
2488}
2489
2490void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2491 int mtuSize = getInterfaceMtu(ifName);
2492 EXPECT_EQ(mtu, mtuSize);
2493}
2494
2495InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2496 const std::string& addr, int prefixLength,
2497 const std::vector<std::string>& flags) {
2498 InterfaceConfigurationParcel cfg;
2499 cfg.ifName = ifName;
2500 cfg.hwAddr = "";
2501 cfg.ipv4Addr = addr;
2502 cfg.prefixLength = prefixLength;
2503 cfg.flags = flags;
2504 return cfg;
2505}
2506
2507void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2508 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2509 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2510
2511 for (const auto& flag : expectedFlags) {
2512 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2513 interfaceCfg.flags.end());
2514 }
2515
2516 for (const auto& flag : unexpectedFlags) {
2517 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2518 interfaceCfg.flags.end());
2519 }
2520}
2521
2522} // namespace
2523
2524TEST_F(BinderTest, InterfaceList) {
2525 std::vector<std::string> interfaceListResult;
2526
2527 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2528 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2529 expectInterfaceList(interfaceListResult);
2530}
2531
2532TEST_F(BinderTest, InterfaceGetCfg) {
2533 InterfaceConfigurationParcel interfaceCfgResult;
2534
2535 // Add test physical network
2536 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2537 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2538
2539 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2540 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2541 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2542 expectTunFlags(interfaceCfgResult);
2543
2544 // Remove test physical network
2545 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2546}
2547
2548TEST_F(BinderTest, InterfaceSetCfg) {
2549 const std::string testAddr = "192.0.2.3";
2550 const int testPrefixLength = 24;
2551 std::vector<std::string> upFlags = {"up"};
2552 std::vector<std::string> downFlags = {"down"};
2553
2554 // Add test physical network
2555 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2556 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2557
2558 // Set tun interface down.
2559 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2560 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2561 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2562 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2563
2564 // Set tun interface up again.
2565 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2566 status = mNetd->interfaceSetCfg(interfaceCfg);
2567 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2568 status = mNetd->interfaceClearAddrs(sTun.name());
2569 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2570
2571 // Remove test physical network
2572 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2573}
2574
2575TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2576 // enable
2577 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2578 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2579 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2580
2581 // disable
2582 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2583 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2584 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2585}
2586
2587TEST_F(BinderTest, InterfaceClearAddr) {
2588 const std::string testAddr = "192.0.2.3";
2589 const int testPrefixLength = 24;
2590 std::vector<std::string> noFlags{};
2591
2592 // Add test physical network
2593 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2594 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2595
2596 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2597 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2598 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2599 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2600
2601 status = mNetd->interfaceClearAddrs(sTun.name());
2602 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2603 expectInterfaceNoAddr(sTun.name());
2604
2605 // Remove test physical network
2606 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2607}
2608
2609TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2610 // Add test physical network
2611 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2612 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2613
2614 // disable
2615 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2616 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2617 expectInterfaceEnableIPv6(sTun.name(), false);
2618
2619 // enable
2620 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2621 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2622 expectInterfaceEnableIPv6(sTun.name(), true);
2623
2624 // Remove test physical network
2625 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2626}
2627
2628TEST_F(BinderTest, InterfaceSetMtu) {
2629 const int testMtu = 1200;
2630
2631 // Add test physical network
2632 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2633 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2634
2635 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2636 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2637 expectInterfaceMtu(sTun.name(), testMtu);
2638
2639 // Remove test physical network
2640 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2641}