blob: 4b95ed8401ddb924feb5f09e73be869110da0b80 [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"
Luke Huang19b49c52018-10-22 12:12:05 +090064#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090065
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090066namespace binder = android::binder;
67namespace netdutils = android::netdutils;
68
69using android::IBinder;
70using android::IServiceManager;
71using android::sp;
72using android::String16;
73using android::String8;
74using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080075using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090076using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090077using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080078using android::base::Trim;
Chenbo Feng837ddfc2018-05-08 13:45:08 -070079using android::bpf::hasBpfSupport;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090080using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080081using android::net::InterfaceConfigurationParcel;
82using android::net::InterfaceController;
Luke Huangcaebcbb2018-09-27 20:37:14 +080083using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090084using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090085using android::net::UidRangeParcel;
Nathan Harold21299f72018-03-16 20:13:03 -070086using android::net::XfrmController;
Luke Huangf7782042018-08-08 13:13:04 +080087using android::netdutils::sSyscalls;
Robin Leeb8087362016-03-30 18:43:08 +010088
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090089#define SKIP_IF_BPF_SUPPORTED \
90 do { \
91 if (hasBpfSupport()) return; \
92 } while (0)
Chenbo Feng837ddfc2018-05-08 13:45:08 -070093
Robin Leeb8087362016-03-30 18:43:08 +010094static const char* IP_RULE_V4 = "-4";
95static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090096static const int TEST_NETID1 = 65501;
97static const int TEST_NETID2 = 65502;
98constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090099
Benedict Wongb2daefb2017-12-06 22:05:46 -0800100static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
101static const std::string ESP_ALLOW_RULE("esp");
102
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900103class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900104 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900105 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900106 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900107 sp<IBinder> binder = sm->getService(String16("netd"));
108 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900109 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900110 }
111 }
112
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900113 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900114 ASSERT_NE(nullptr, mNetd.get());
115 }
116
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900117 void TearDown() override {
118 mNetd->networkDestroy(TEST_NETID1);
119 mNetd->networkDestroy(TEST_NETID2);
120 }
121
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900122 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700123
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900124 // Static because setting up the tun interface takes about 40ms.
125 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900126 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900127 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900128 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900129 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900130 }
131
132 static void TearDownTestCase() {
133 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900134 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900135 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900136 }
137
138 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900139
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900140 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900141 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900142 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900143 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900144};
145
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900146TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900147TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900148
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900149class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900150 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700151 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900152 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900153 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900154 }
155
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900156 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900157 std::string mName;
158};
159
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900160TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900161 TimedOperation t("isAlive RPC");
162 bool isAlive = false;
163 mNetd->isAlive(&isAlive);
164 ASSERT_TRUE(isAlive);
165}
166
167static int randomUid() {
168 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
169}
170
Robin Leeb8087362016-03-30 18:43:08 +0100171static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900172 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900173 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
174 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900175 perror("popen");
176 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900177 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900178
179 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100180 size_t bufsize = 0;
181 ssize_t linelen = 0;
182 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900183 lines.push_back(std::string(line, linelen));
184 free(line);
185 line = nullptr;
186 }
187
188 pclose(f);
189 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900190}
191
Robin Leeb8087362016-03-30 18:43:08 +0100192static std::vector<std::string> listIpRules(const char *ipVersion) {
193 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
194 return runCommand(command);
195}
196
197static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900198 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100199 return runCommand(command);
200}
201
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900202static int iptablesRuleLineLength(const char *binary, const char *chainName) {
203 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900204}
205
Benedict Wongb2daefb2017-12-06 22:05:46 -0800206static bool iptablesRuleExists(const char *binary,
207 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900208 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800209 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900210 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800211 if(rule.find(expectedRule) != std::string::npos) {
212 return true;
213 }
214 }
215 return false;
216}
217
218static bool iptablesNoSocketAllowRuleExists(const char *chainName){
219 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
220 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
221}
222
223static bool iptablesEspAllowRuleExists(const char *chainName){
224 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
225 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
226}
227
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900228TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700229 SKIP_IF_BPF_SUPPORTED;
230
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900231 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
232 const int kNumUids = 500;
233 std::vector<int32_t> noUids(0);
234 std::vector<int32_t> uids(kNumUids);
235 for (int i = 0; i < kNumUids; i++) {
236 uids[i] = randomUid();
237 }
238
239 bool ret;
240 {
241 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900242 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900243 }
244 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800245 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
246 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
247 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
248 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900249 {
250 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900251 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900252 }
253 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900254 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
255 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900256
257 {
258 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900259 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900260 }
261 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900262 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
263 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800264 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
265 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900266
267 {
268 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900269 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900270 }
271 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900272 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
273 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900274
275 // Check that the call fails if iptables returns an error.
276 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900277 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900278 EXPECT_EQ(false, ret);
279}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900280
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900281TEST_F(BinderTest, VirtualTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700282 const struct TestData {
283 const std::string family;
284 const std::string deviceName;
285 const std::string localAddress;
286 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800287 int32_t iKey;
288 int32_t oKey;
289 } kTestData[] = {
Nathan Harold21299f72018-03-16 20:13:03 -0700290 {"IPV4", "test_vti", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53},
291 {"IPV6", "test_vti6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50},
manojboopathi8707f232018-01-02 14:45:47 -0800292 };
293
Luke Huangc3252cc2018-10-16 15:43:23 +0800294 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700295 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800296
297 binder::Status status;
298
299 // Create Virtual Tunnel Interface.
Nathan Harold21299f72018-03-16 20:13:03 -0700300 status = mNetd->addVirtualTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
301 td.iKey, td.oKey);
manojboopathi8707f232018-01-02 14:45:47 -0800302 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
303
304 // Update Virtual Tunnel Interface.
305 status = mNetd->updateVirtualTunnelInterface(td.deviceName, td.localAddress,
306 td.remoteAddress, td.iKey, td.oKey);
307 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
308
309 // Remove Virtual Tunnel Interface.
310 status = mNetd->removeVirtualTunnelInterface(td.deviceName);
311 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
312 }
313}
314
Nathan Harold2deff322018-05-10 14:03:48 -0700315// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
316// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
317#if INTPTR_MAX != INT32_MAX
Benedict Wonga04ffa72018-05-09 21:42:42 -0700318static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
319 static_cast<int>(android::net::XfrmDirection::OUT)};
320static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
321
Nathan Harold21299f72018-03-16 20:13:03 -0700322#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
323 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900324bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Nathan Harold21299f72018-03-16 20:13:03 -0700325 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
326 SCOPED_TRACE(status);
327 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
328
329 // Add a policy
Benedict Wonga04ffa72018-05-09 21:42:42 -0700330 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700331 SCOPED_TRACE(status);
332 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
333
334 // Add an ipsec interface
335 status = netdutils::statusFromErrno(
336 XfrmController::addVirtualTunnelInterface(
337 "ipsec_test", "::", "::1", 0xF00D, 0xD00D, false),
338 "addVirtualTunnelInterface");
339 return (status.ok() == expectOk);
340}
341
Benedict Wonga04ffa72018-05-09 21:42:42 -0700342TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
343 binder::Status status;
344
345 // Repeat to ensure cleanup and recreation works correctly
346 for (int i = 0; i < 2; i++) {
347 for (int direction : XFRM_DIRECTIONS) {
348 for (int addrFamily : ADDRESS_FAMILIES) {
349 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
350 "127.0.0.6", 123, 0, 0);
351 EXPECT_TRUE(status.isOk())
352 << " family: " << addrFamily << " direction: " << direction;
353 }
354 }
355
356 // Cleanup
357 for (int direction : XFRM_DIRECTIONS) {
358 for (int addrFamily : ADDRESS_FAMILIES) {
359 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0);
360 EXPECT_TRUE(status.isOk());
361 }
362 }
363 }
364}
365
366TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
367 binder::Status status;
368
369 // Repeat to ensure cleanup and recreation works correctly
370 for (int i = 0; i < 2; i++) {
371 for (int direction : XFRM_DIRECTIONS) {
372 for (int addrFamily : ADDRESS_FAMILIES) {
373 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
374 "2001:db8::d00d", 123, 0, 0);
375 EXPECT_TRUE(status.isOk())
376 << " family: " << addrFamily << " direction: " << direction;
377 }
378 }
379
380 // Cleanup
381 for (int direction : XFRM_DIRECTIONS) {
382 for (int addrFamily : ADDRESS_FAMILIES) {
383 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0);
384 EXPECT_TRUE(status.isOk());
385 }
386 }
387 }
388}
389
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900390TEST_F(BinderTest, XfrmControllerInit) {
Nathan Harold21299f72018-03-16 20:13:03 -0700391 netdutils::Status status;
392 status = XfrmController::Init();
393 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700394
395 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
396 // feature.
397 if (status.code() == EOPNOTSUPP) return;
398
Nathan Harold21299f72018-03-16 20:13:03 -0700399 ASSERT_TRUE(status.ok());
400
401 int32_t spi = 0;
402
403 ASSERT_TRUE(allocateIpSecResources(true, &spi));
404 ASSERT_TRUE(allocateIpSecResources(false, &spi));
405
406 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700407 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700408 ASSERT_TRUE(allocateIpSecResources(true, &spi));
409
410 // Clean up
411 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0);
412 SCOPED_TRACE(status);
413 ASSERT_TRUE(status.ok());
414
Benedict Wonga04ffa72018-05-09 21:42:42 -0700415 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700416 SCOPED_TRACE(status);
417 ASSERT_TRUE(status.ok());
418
419 // Remove Virtual Tunnel Interface.
420 status = netdutils::statusFromErrno(
421 XfrmController::removeVirtualTunnelInterface("ipsec_test"),
422 "removeVirtualTunnelInterface");
423
424 ASSERT_TRUE(status.ok());
425}
Nathan Harold2deff322018-05-10 14:03:48 -0700426#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700427
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900428static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900429 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900430
431 // Output looks like this:
432 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900433 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900434 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900435 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900436 //
437 // or:
438 //
439 // Chain bw_data_saver (1 references)
440 // target prot opt source destination
441 // ... possibly connectivity critical packet rules here ...
442 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900443
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900444 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900445
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900446 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
447 // Data saver disabled.
448 return 0;
449 }
450
451 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
452
453 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
454 // Data saver enabled.
455 return 1;
456 }
457
458 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900459}
460
461bool enableDataSaver(sp<INetd>& netd, bool enable) {
462 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
463 bool ret;
464 netd->bandwidthEnableDataSaver(enable, &ret);
465 return ret;
466}
467
468int getDataSaverState() {
469 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
470 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
471 EXPECT_EQ(enabled4, enabled6);
472 EXPECT_NE(-1, enabled4);
473 EXPECT_NE(-1, enabled6);
474 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
475 return -1;
476 }
477 return enabled6;
478}
479
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900480TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900481 const int wasEnabled = getDataSaverState();
482 ASSERT_NE(-1, wasEnabled);
483
484 if (wasEnabled) {
485 ASSERT_TRUE(enableDataSaver(mNetd, false));
486 EXPECT_EQ(0, getDataSaverState());
487 }
488
489 ASSERT_TRUE(enableDataSaver(mNetd, false));
490 EXPECT_EQ(0, getDataSaverState());
491
492 ASSERT_TRUE(enableDataSaver(mNetd, true));
493 EXPECT_EQ(1, getDataSaverState());
494
495 ASSERT_TRUE(enableDataSaver(mNetd, true));
496 EXPECT_EQ(1, getDataSaverState());
497
498 if (!wasEnabled) {
499 ASSERT_TRUE(enableDataSaver(mNetd, false));
500 EXPECT_EQ(0, getDataSaverState());
501 }
502}
Robin Leeb8087362016-03-30 18:43:08 +0100503
Luke Huang94658ac2018-10-18 19:35:12 +0900504static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
505 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100506 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100507 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100508 std::vector<std::string> rules = listIpRules(ipVersion);
509
510 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900511 std::string suffix =
512 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900513 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800514 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100515 return true;
516 }
517 }
518 return false;
519}
520
Luke Huang94658ac2018-10-18 19:35:12 +0900521static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
522 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100523 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
524 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
525 EXPECT_EQ(existsIp4, existsIp6);
526 return existsIp4;
527}
528
Luke Huang94658ac2018-10-18 19:35:12 +0900529namespace {
530
531UidRangeParcel makeUidRangeParcel(int start, int stop) {
532 UidRangeParcel res;
533 res.start = start;
534 res.stop = stop;
535
536 return res;
537}
538
539} // namespace
540
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900541TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800542 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
543 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
544 .serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900545 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
546 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
547
548 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
549 EXPECT_EQ(EBUSY,
550 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
551
552 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
553 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
554 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800555 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900556}
557
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900558TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900559 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
560
561 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
562 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
563 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
564
Luke Huang94658ac2018-10-18 19:35:12 +0900565 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
566 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
567 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900568 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
569
570 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
571
572 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
573 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
574 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
575 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
576
577 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
578 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
579 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
580 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
581
582 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
583}
584
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900585TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100586 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100587
Luke Huang94658ac2018-10-18 19:35:12 +0900588 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
589 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100590
591 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
592 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
593
594 // Create two valid rules.
595 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
596 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
597 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
598 for (auto const& range : uidRanges) {
599 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
600 }
601
602 // Remove the rules.
603 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
604 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
605 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
606 for (auto const& range : uidRanges) {
607 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
608 }
609
610 // Fail to remove the rules a second time after they are already deleted.
611 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
612 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
613 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
614
615 // All rules should be the same as before.
616 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
617 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
618}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900619
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900620// Create a socket pair that isLoopbackSocket won't think is local.
621void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900622 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900623 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900624 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
625
626 socklen_t addrlen = sizeof(server6);
627 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
628 ASSERT_EQ(0, listen(*serverSocket, 10));
629
Bernie Innocentif6918262018-06-11 17:37:35 +0900630 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900631 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900632 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900633 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
634 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
635
Bernie Innocentif6918262018-06-11 17:37:35 +0900636 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900637 ASSERT_NE(-1, *acceptedSocket);
638
639 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
640}
641
642void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
643 char buf[4096];
644 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
645 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
646 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
647}
648
649void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
650 // Check that the client socket was closed with ECONNABORTED.
651 int ret = write(clientSocket, "foo", sizeof("foo"));
652 int err = errno;
653 EXPECT_EQ(-1, ret);
654 EXPECT_EQ(ECONNABORTED, err);
655
656 // Check that it sent a RST to the server.
657 ret = write(acceptedSocket, "foo", sizeof("foo"));
658 err = errno;
659 EXPECT_EQ(-1, ret);
660 EXPECT_EQ(ECONNRESET, err);
661}
662
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900663TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900664 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900665 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900666
667 // Pick a random UID in the system UID range.
668 constexpr int baseUid = AID_APP - 2000;
669 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
670 int uid = baseUid + 500 + arc4random_uniform(1000);
671 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
672
673 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900674 std::vector<UidRangeParcel> uidRanges = {
675 makeUidRangeParcel(baseUid + 42, baseUid + 449),
676 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
677 makeUidRangeParcel(baseUid + 498, uid - 1),
678 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900679 };
680 // A skip list that doesn't contain UID.
681 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
682
683 // Close sockets. Our test socket should be intact.
684 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
685 checkSocketpairOpen(clientSocket, acceptedSocket);
686
687 // UID ranges that do contain uid.
688 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900689 makeUidRangeParcel(baseUid + 42, baseUid + 449),
690 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
691 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900692 };
693 // Add uid to the skip list.
694 skipUids.push_back(uid);
695
696 // Close sockets. Our test socket should still be intact because it's in the skip list.
697 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
698 checkSocketpairOpen(clientSocket, acceptedSocket);
699
700 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
701 skipUids.resize(skipUids.size() - 1);
702 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
703 checkSocketpairClosed(clientSocket, acceptedSocket);
704
705 close(clientSocket);
706 close(serverSocket);
707 close(acceptedSocket);
708}
Erik Klinecc4f2732016-08-03 11:24:27 +0900709
710namespace {
711
712int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
713 if (buf == nullptr) return -1;
714
715 int prefixLength = 0;
716 bool endOfContiguousBits = false;
717 for (unsigned int i = 0; i < buflen; i++) {
718 const uint8_t value = buf[i];
719
720 // Bad bit sequence: check for a contiguous set of bits from the high
721 // end by verifying that the inverted value + 1 is a power of 2
722 // (power of 2 iff. (v & (v - 1)) == 0).
723 const uint8_t inverse = ~value + 1;
724 if ((inverse & (inverse - 1)) != 0) return -1;
725
726 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
727
728 // Bogus netmask.
729 if (endOfContiguousBits && value != 0) return -1;
730
731 if (value != 0xff) endOfContiguousBits = true;
732 }
733
734 return prefixLength;
735}
736
737template<typename T>
738int netmaskToPrefixLength(const T *p) {
739 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
740}
741
742
743static bool interfaceHasAddress(
744 const std::string &ifname, const char *addrString, int prefixLength) {
745 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900746
747 const struct addrinfo hints = {
748 .ai_flags = AI_NUMERICHOST,
749 .ai_family = AF_UNSPEC,
750 .ai_socktype = SOCK_DGRAM,
751 };
752 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
753 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
754 return false;
755 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900756 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900757
758 struct ifaddrs *ifaddrsList = nullptr;
759 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
760
761 if (getifaddrs(&ifaddrsList) != 0) {
762 return false;
763 }
764
765 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
766 if (std::string(addr->ifa_name) != ifname ||
767 addr->ifa_addr == nullptr ||
768 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
769 continue;
770 }
771
772 switch (addr->ifa_addr->sa_family) {
773 case AF_INET: {
774 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
775 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
776 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
777 continue;
778 }
779
780 if (prefixLength < 0) return true; // not checking prefix lengths
781
782 if (addr->ifa_netmask == nullptr) return false;
783 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
784 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
785 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
786 }
787 case AF_INET6: {
788 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
789 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
790 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
791 continue;
792 }
793
794 if (prefixLength < 0) return true; // not checking prefix lengths
795
796 if (addr->ifa_netmask == nullptr) return false;
797 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
798 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
799 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
800 }
801 default:
802 // Cannot happen because we have already screened for matching
803 // address families at the top of each iteration.
804 continue;
805 }
806 }
807
808 return false;
809}
810
811} // namespace
812
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900813TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900814 static const struct TestData {
815 const char *addrString;
816 const int prefixLength;
817 const bool expectSuccess;
818 } kTestData[] = {
819 { "192.0.2.1", 24, true },
820 { "192.0.2.2", 25, true },
821 { "192.0.2.3", 32, true },
822 { "192.0.2.4", 33, false },
823 { "192.not.an.ip", 24, false },
824 { "2001:db8::1", 64, true },
825 { "2001:db8::2", 65, true },
826 { "2001:db8::3", 128, true },
827 { "2001:db8::4", 129, false },
828 { "foo:bar::bad", 64, false },
829 };
830
Luke Huangc3252cc2018-10-16 15:43:23 +0800831 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900832 const auto &td = kTestData[i];
833
834 // [1.a] Add the address.
835 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900836 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900837 if (td.expectSuccess) {
838 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
839 } else {
840 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
841 ASSERT_NE(0, status.serviceSpecificErrorCode());
842 }
843
844 // [1.b] Verify the addition meets the expectation.
845 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900846 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900847 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900848 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900849 }
850
851 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900852 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900853 if (td.expectSuccess) {
854 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
855 } else {
856 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
857 ASSERT_NE(0, status.serviceSpecificErrorCode());
858 }
859
860 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900861 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900862 }
863}
Erik Kline55b06f82016-07-04 09:57:18 +0900864
Erik Kline38e51f12018-09-06 20:14:44 +0900865TEST_F(BinderTest, GetProcSysNet) {
866 const char LOOPBACK[] = "lo";
867 static const struct {
868 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900869 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900870 const char* ifname;
871 const char* parameter;
872 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900873 const int expectedReturnCode;
874 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900875 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
876 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
877 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
878 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
879 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
880 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
881 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900882 };
883
Luke Huangc3252cc2018-10-16 15:43:23 +0800884 for (int i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900885 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900886
Erik Kline38e51f12018-09-06 20:14:44 +0900887 std::string value;
888 const binder::Status status =
889 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
890
891 if (td.expectedReturnCode == 0) {
892 SCOPED_TRACE(String8::format("test case %d should have passed", i));
893 EXPECT_EQ(0, status.exceptionCode());
894 EXPECT_EQ(0, status.serviceSpecificErrorCode());
895 EXPECT_EQ(td.expectedValue, value);
896 } else {
897 SCOPED_TRACE(String8::format("test case %d should have failed", i));
898 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
899 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
900 }
901 }
902}
903
904TEST_F(BinderTest, SetProcSysNet) {
905 static const struct {
906 const int ipversion;
907 const int which;
908 const char* ifname;
909 const char* parameter;
910 const char* value;
911 const int expectedReturnCode;
912 } kTestData[] = {
913 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
914 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
915 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
916 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
917 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
918 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
919 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
920 };
921
Luke Huangc3252cc2018-10-16 15:43:23 +0800922 for (int i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900923 const auto& td = kTestData[i];
924
925 const binder::Status status =
926 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900927
928 if (td.expectedReturnCode == 0) {
929 SCOPED_TRACE(String8::format("test case %d should have passed", i));
930 EXPECT_EQ(0, status.exceptionCode());
931 EXPECT_EQ(0, status.serviceSpecificErrorCode());
932 } else {
933 SCOPED_TRACE(String8::format("test case %d should have failed", i));
934 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
935 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
936 }
937 }
938}
Ben Schwartze7601812017-04-28 16:38:29 -0400939
Erik Kline38e51f12018-09-06 20:14:44 +0900940TEST_F(BinderTest, GetSetProcSysNet) {
941 const int ipversion = INetd::IPV6;
942 const int category = INetd::NEIGH;
943 const std::string& tun = sTun.name();
944 const std::string parameter("ucast_solicit");
945
946 std::string value{};
947 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
948 EXPECT_FALSE(value.empty());
949 const int ival = std::stoi(value);
950 EXPECT_GT(ival, 0);
951 // Try doubling the parameter value (always best!).
952 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
953 .isOk());
954 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
955 EXPECT_EQ(2 * ival, std::stoi(value));
956 // Try resetting the parameter.
957 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
958 .isOk());
959 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
960 EXPECT_EQ(ival, std::stoi(value));
961}
962
Ben Schwartze7601812017-04-28 16:38:29 -0400963static std::string base64Encode(const std::vector<uint8_t>& input) {
964 size_t out_len;
965 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
966 // out_len includes the trailing NULL.
967 uint8_t output_bytes[out_len];
968 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
969 return std::string(reinterpret_cast<char*>(output_bytes));
970}
971
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900972TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900973 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400974 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400975 std::vector<uint8_t> short_fp(1);
976 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
977 std::vector<std::string> test_domains;
978 std::vector<int> test_params = { 300, 25, 8, 8 };
979 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400980 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400981 const std::vector<std::string> servers;
982 const std::string tlsName;
983 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400984 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900985 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400986 { {"192.0.2.1"}, "", {}, 0 },
987 { {"2001:db8::2"}, "host.name", {}, 0 },
988 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
989 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900990 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400991 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900992 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400993 { {"2001:dg8::6"}, "", {}, EINVAL },
994 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
995 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
996 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
997 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400998 };
999
Luke Huangc3252cc2018-10-16 15:43:23 +08001000 for (unsigned int i = 0; i < std::size(kTlsTestData); i++) {
Erik Klinea1476fb2018-03-04 21:01:56 +09001001 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -04001002
1003 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001004 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -04001005 fingerprints.push_back(base64Encode(fingerprint));
1006 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001007 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001008 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
1009 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -04001010
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001011 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -04001012 SCOPED_TRACE(String8::format("test case %d should have passed", i));
1013 SCOPED_TRACE(status.toString8());
1014 EXPECT_EQ(0, status.exceptionCode());
1015 } else {
1016 SCOPED_TRACE(String8::format("test case %d should have failed", i));
1017 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001018 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -04001019 }
Ben Schwartze7601812017-04-28 16:38:29 -04001020 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001021 // Ensure TLS is disabled before the start of the next test.
1022 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001023 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1024 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001025}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001026
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001027namespace {
1028
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001029void expectNoTestCounterRules() {
1030 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1031 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1032 std::string allRules = Join(runCommand(command), "\n");
1033 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1034 }
1035}
1036
Bernie Innocentif6918262018-06-11 17:37:35 +09001037void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1038 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001039 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1040 path, if1.c_str(), if2.c_str(), pkt, byte));
1041}
1042
Bernie Innocentif6918262018-06-11 17:37:35 +09001043void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001044 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1045 path, if1.c_str(), if2.c_str()));
1046 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1047 path, if2.c_str(), if1.c_str()));
1048}
1049
Luke Huangcaebcbb2018-09-27 20:37:14 +08001050std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1051 const std::string& iface) {
1052 for (auto& stats : statsVec) {
1053 if (stats.iface == iface) {
1054 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1055 }
1056 }
1057 return {};
1058}
1059
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001060} // namespace
1061
1062TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001063 expectNoTestCounterRules();
1064
1065 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1066 // disabling tethering. We don't check the return value because these commands will fail if
1067 // tethering is already enabled.
1068 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1069 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1070
1071 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1072 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1073 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1074 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1075 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1076
1077 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1078 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1079 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1080 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1081 // RX is from external to internal, and TX is from internal to external.
1082 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1083 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1084
1085 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1086 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1087
1088 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1089 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1090
1091 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1092 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1093 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1094
Luke Huangcaebcbb2018-09-27 20:37:14 +08001095 std::vector<TetherStatsParcel> statsVec;
1096 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001097 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1098
Luke Huangcaebcbb2018-09-27 20:37:14 +08001099 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001100
Luke Huangcaebcbb2018-09-27 20:37:14 +08001101 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001102
1103 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1104 delTetherCounterValues(path, intIface1, extIface1);
1105 delTetherCounterValues(path, intIface2, extIface2);
1106 if (path == IP6TABLES_PATH) {
1107 delTetherCounterValues(path, intIface3, extIface2);
1108 }
1109 }
1110
1111 expectNoTestCounterRules();
1112}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001113
Luke Huang0051a622018-07-23 20:30:16 +08001114namespace {
1115
Luke Huanga5211072018-08-01 23:36:29 +08001116constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1117constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001118
1119static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1120 const char* chainName) {
1121 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1122 return runCommand(command);
1123}
1124
Luke Huang19b49c52018-10-22 12:12:05 +09001125// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001126bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001127 const std::string& expectedInterface,
1128 const std::string& expectedRule, const char* table) {
1129 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1130 for (const auto& rule : rules) {
1131 if (rule.find(expectedInterface) != std::string::npos) {
1132 if (rule.find(expectedRule) != std::string::npos) {
1133 return true;
1134 }
1135 }
1136 }
1137 return false;
1138}
1139
1140void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001141 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001142 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001143 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001144 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001145 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1146 IdletimerRule, RAW_TABLE));
1147 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001148 ifname, IdletimerRule, MANGLE_TABLE));
1149 }
1150}
1151
1152void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001153 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001154 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001155 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001156 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001157 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1158 IdletimerRule, RAW_TABLE));
1159 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001160 ifname, IdletimerRule, MANGLE_TABLE));
1161 }
1162}
1163
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001164} // namespace
1165
1166TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001167 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1168 // rule in the table. Because we only check the result after calling remove function. We might
1169 // check the actual rule which is removed by our function (maybe compare the results between
1170 // calling function before and after)
1171 binder::Status status;
1172 const struct TestData {
1173 const std::string ifname;
1174 int32_t timeout;
1175 const std::string classLabel;
1176 } idleTestData[] = {
1177 {"wlan0", 1234, "happyday"},
1178 {"rmnet_data0", 4567, "friday"},
1179 };
1180 for (const auto& td : idleTestData) {
1181 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1182 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1183 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1184
1185 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1186 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1187 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1188 }
1189}
1190
Luke Huanga67dd562018-07-17 19:58:25 +08001191namespace {
1192
1193constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1194constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1195
1196void expectStrictSetUidAccept(const int uid) {
1197 std::string uidRule = StringPrintf("owner UID match %u", uid);
1198 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1199 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1200 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1201 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1202 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1203 }
1204}
1205
1206void expectStrictSetUidLog(const int uid) {
1207 static const char logRule[] = "st_penalty_log all";
1208 std::string uidRule = StringPrintf("owner UID match %u", uid);
1209 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1210 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1211 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1212 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1213 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1214 }
1215}
1216
1217void expectStrictSetUidReject(const int uid) {
1218 static const char rejectRule[] = "st_penalty_reject all";
1219 std::string uidRule = StringPrintf("owner UID match %u", uid);
1220 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1221 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1222 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1223 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1224 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1225 }
1226}
1227
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001228} // namespace
1229
1230TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001231 binder::Status status;
1232 int32_t uid = randomUid();
1233
1234 // setUidCleartextPenalty Policy:Log with randomUid
1235 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1236 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1237 expectStrictSetUidLog(uid);
1238
1239 // setUidCleartextPenalty Policy:Accept with randomUid
1240 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1241 expectStrictSetUidAccept(uid);
1242
1243 // setUidCleartextPenalty Policy:Reject with randomUid
1244 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1245 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1246 expectStrictSetUidReject(uid);
1247
1248 // setUidCleartextPenalty Policy:Accept with randomUid
1249 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1250 expectStrictSetUidAccept(uid);
1251
1252 // test wrong policy
1253 int32_t wrongPolicy = -123;
1254 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1255 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1256}
1257
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001258namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001259
Luke Huanga5211072018-08-01 23:36:29 +08001260bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001261 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1262 return (runCommand(cmd.c_str()).size()) ? true : false;
1263}
1264
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001265} // namespace
1266
1267TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001268 binder::Status status;
1269 // use dummy0 for test since it is set ready
1270 static const char testIf[] = "dummy0";
1271 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1272
1273 status = mNetd->clatdStart(testIf);
1274 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1275 EXPECT_TRUE(processExists(clatdName));
1276
1277 mNetd->clatdStop(testIf);
1278 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1279 EXPECT_FALSE(processExists(clatdName));
1280}
Luke Huang457d4702018-08-16 15:39:15 +08001281
1282namespace {
1283
1284bool getIpfwdV4Enable() {
1285 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1286 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1287 EXPECT_TRUE(!result.empty());
1288 int v4Enable = std::stoi(result[0]);
1289 return v4Enable;
1290}
1291
1292bool getIpfwdV6Enable() {
1293 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1294 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1295 EXPECT_TRUE(!result.empty());
1296 int v6Enable = std::stoi(result[0]);
1297 return v6Enable;
1298}
1299
1300void expectIpfwdEnable(bool enable) {
1301 int enableIPv4 = getIpfwdV4Enable();
1302 int enableIPv6 = getIpfwdV6Enable();
1303 EXPECT_EQ(enable, enableIPv4);
1304 EXPECT_EQ(enable, enableIPv6);
1305}
1306
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001307bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001308 std::vector<std::string> rules = listIpRules(ipVersion);
1309 for (const auto& rule : rules) {
1310 if (rule.find(ipfwdRule) != std::string::npos) {
1311 return true;
1312 }
1313 }
1314 return false;
1315}
1316
1317void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1318 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1319
1320 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1321 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1322 }
1323}
1324
1325void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1326 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1327
1328 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1329 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1330 }
1331}
1332
1333} // namespace
1334
1335TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1336 // Netd default enable Ipfwd with requester NetdHwService
1337 const std::string defaultRequester = "NetdHwService";
1338
1339 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1340 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1341 expectIpfwdEnable(false);
1342
1343 bool ipfwdEnabled;
1344 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1345 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1346 EXPECT_FALSE(ipfwdEnabled);
1347
1348 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1349 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1350 expectIpfwdEnable(true);
1351
1352 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1353 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1354 EXPECT_TRUE(ipfwdEnabled);
1355}
1356
1357TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1358 static const char testFromIf[] = "dummy0";
1359 static const char testToIf[] = "dummy0";
1360
1361 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1362 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1363 expectIpfwdRuleExists(testFromIf, testToIf);
1364
1365 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1366 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1367 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001368}
Luke Huang531f5d32018-08-03 15:19:05 +08001369
1370namespace {
1371
1372constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1373constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1374constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1375constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1376constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001377constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001378
Luke Huang19b49c52018-10-22 12:12:05 +09001379// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1380// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001381bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1382 const char* chainName, const std::string& expectedTargetA,
1383 const std::string& expectedTargetB) {
1384 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1385 int matchCount = 0;
1386
1387 for (const auto& rule : rules) {
1388 if (rule.find(expectedTargetA) != std::string::npos) {
1389 if (rule.find(expectedTargetB) != std::string::npos) {
1390 matchCount++;
1391 }
1392 }
1393 }
1394 return matchCount == expectedCount;
1395}
1396
1397void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1398 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1399 std::string result = "";
1400
1401 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001402 // Quota value might be decreased while matching packets
1403 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001404}
1405
1406void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1407 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1408 std::string quotaRule = StringPrintf("quota %s", ifname);
1409
1410 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1411 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1412 BANDWIDTH_COSTLY_IF));
1413 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1414 BANDWIDTH_COSTLY_IF));
1415 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1416 BANDWIDTH_COSTLY_IF));
1417 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1418 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1419 }
1420 expectXtQuotaValueEqual(ifname, quotaBytes);
1421}
1422
1423void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1424 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1425 std::string quotaRule = StringPrintf("quota %s", ifname);
1426
1427 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1428 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1429 BANDWIDTH_COSTLY_IF));
1430 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1431 BANDWIDTH_COSTLY_IF));
1432 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1433 BANDWIDTH_COSTLY_IF));
1434 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1435 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1436 }
1437}
1438
1439void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1440 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1441 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1442 std::string alertName = StringPrintf("%sAlert", ifname);
1443
1444 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1445 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1446 }
1447 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1448}
1449
1450void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1451 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1452 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1453
1454 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1455 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1456 }
1457}
1458
1459void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1460 static const char globalAlertRule[] = "quota globalAlert";
1461 static const char globalAlertName[] = "globalAlert";
1462
1463 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001464 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001465 }
1466 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1467}
1468
1469void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1470 std::string uidRule = StringPrintf("owner UID match %u", uid);
1471
1472 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1473 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1474 }
1475}
1476
1477void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1478 std::string uidRule = StringPrintf("owner UID match %u", uid);
1479
1480 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1481 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1482 }
1483}
1484
1485} // namespace
1486
1487TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1488 long testQuotaBytes = 5550;
1489
1490 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001491 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001492 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1493
1494 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1495 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1496 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1497
1498 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1499 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1500 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1501
1502 // Remove test physical network
1503 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1504}
1505
1506TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1507 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001508 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001509 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001510 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001511 // Need to have a prior interface quota set to set an alert
1512 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1513 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1514 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1515 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1516
1517 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1518 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1519 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1520
1521 // Remove interface quota
1522 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1523 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1524 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1525
1526 // Remove test physical network
1527 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1528}
1529
1530TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1531 long testAlertBytes = 2097149;
1532
1533 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1534 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1535 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1536
1537 testAlertBytes = 2097152;
1538 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1539 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1540 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1541}
1542
1543TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1544 SKIP_IF_BPF_SUPPORTED;
1545
1546 int32_t uid = randomUid();
1547 static const char targetReject[] = "REJECT";
1548 static const char targetReturn[] = "RETURN";
1549
1550 // add NaughtyApp
1551 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1552 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1553 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1554
1555 // remove NaughtyApp
1556 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1557 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1558 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1559
1560 // add NiceApp
1561 status = mNetd->bandwidthAddNiceApp(uid);
1562 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1563 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1564
1565 // remove NiceApp
1566 status = mNetd->bandwidthRemoveNiceApp(uid);
1567 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1568 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1569}
Luke Huangb5733d72018-08-21 17:17:19 +08001570
1571namespace {
1572
Luke Huangb670d162018-08-23 20:01:13 +08001573std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1574 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1575 return runCommand(command);
1576}
1577
Luke Huangc3252cc2018-10-16 15:43:23 +08001578bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001579 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1580 for (const auto& route : routes) {
1581 if (route.find(ipRoute) != std::string::npos) {
1582 return true;
1583 }
1584 }
1585 return false;
1586}
1587
Luke Huangc3252cc2018-10-16 15:43:23 +08001588std::string ipRouteString(const std::string& ifName, const std::string& dst,
1589 const std::string& nextHop) {
1590 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1591
1592 if (!nextHop.empty()) {
1593 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001594 }
1595
Luke Huangc3252cc2018-10-16 15:43:23 +08001596 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001597}
1598
Luke Huangc3252cc2018-10-16 15:43:23 +08001599void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1600 const std::string& dst, const std::string& nextHop,
1601 const char* table) {
1602 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1603}
1604
1605void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001606 const std::string& dst, const std::string& nextHop,
1607 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001608 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001609}
1610
1611bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1612 std::vector<std::string> rules = listIpRules(ipVersion);
1613 for (const auto& rule : rules) {
1614 if (rule.find(ipRule) != std::string::npos) {
1615 return true;
1616 }
1617 }
1618 return false;
1619}
1620
1621void expectNetworkDefaultIpRuleExists(const char* ifName) {
1622 std::string networkDefaultRule =
1623 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1624
1625 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1626 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1627 }
1628}
1629
1630void expectNetworkDefaultIpRuleDoesNotExist() {
1631 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1632
1633 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1634 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1635 }
1636}
1637
1638void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1639 std::string networkPermissionRule = "";
1640 switch (permission) {
1641 case INetd::PERMISSION_NONE:
1642 networkPermissionRule = StringPrintf(
1643 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1644 break;
1645 case INetd::PERMISSION_NETWORK:
1646 networkPermissionRule = StringPrintf(
1647 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1648 break;
1649 case INetd::PERMISSION_SYSTEM:
1650 networkPermissionRule = StringPrintf(
1651 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1652 break;
1653 }
1654
1655 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1656 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1657 }
1658}
1659
1660// TODO: It is a duplicate function, need to remove it
1661bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1662 const std::string& expectedInterface,
1663 const std::string& expectedRule,
1664 const char* table) {
1665 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1666 for (const auto& rule : rules) {
1667 if (rule.find(expectedInterface) != std::string::npos) {
1668 if (rule.find(expectedRule) != std::string::npos) {
1669 return true;
1670 }
1671 }
1672 }
1673 return false;
1674}
1675
1676void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1677 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1678 std::string networkIncomingPacketMarkRule = "";
1679 switch (permission) {
1680 case INetd::PERMISSION_NONE:
1681 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1682 break;
1683 case INetd::PERMISSION_NETWORK:
1684 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1685 break;
1686 case INetd::PERMISSION_SYSTEM:
1687 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1688 break;
1689 }
1690
1691 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1692 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1693 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1694 }
1695}
1696
1697} // namespace
1698
1699TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001700 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001701 const char* ipVersion;
1702 const char* testDest;
1703 const char* testNextHop;
1704 const bool expectSuccess;
1705 } kTestData[] = {
1706 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001707 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1708 {IP_RULE_V4, "10.251.0.0/16", "", true},
1709 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1710 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001711 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001712 {IP_RULE_V6, "::/0", "2001:db8::", true},
1713 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001714 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1715 };
1716
Luke Huangc3252cc2018-10-16 15:43:23 +08001717 static const struct {
1718 const char* ipVersion;
1719 const char* testDest;
1720 const char* testNextHop;
1721 } kTestDataWithNextHop[] = {
1722 {IP_RULE_V4, "10.251.10.0/30", ""},
1723 {IP_RULE_V6, "2001:db8::/32", ""},
1724 };
1725
Luke Huangb670d162018-08-23 20:01:13 +08001726 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001727 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001728 const int testUid = randomUid();
1729 const std::vector<int32_t> testUids = {testUid};
1730
1731 // Add test physical network
1732 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1733 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1734
Luke Huangc3252cc2018-10-16 15:43:23 +08001735 // Setup route for testing nextHop
1736 for (unsigned int i = 0; i < std::size(kTestDataWithNextHop); i++) {
1737 const auto& td = kTestDataWithNextHop[i];
1738
1739 // All route for test tun will disappear once the tun interface is deleted.
1740 binder::Status status =
1741 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1742 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1743 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1744 sTun.name().c_str());
1745
1746 // Add system permission for test uid, setup route in legacy system table.
1747 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1748
1749 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1750 testUid);
1751 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1752 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1753 testTableLegacySystem);
1754
1755 // Remove system permission for test uid, setup route in legacy network table.
1756 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1757
1758 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1759 testUid);
1760 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1761 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1762 testTableLegacyNetwork);
1763 }
1764
1765 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001766 const auto& td = kTestData[i];
1767
1768 binder::Status status =
1769 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1770 if (td.expectSuccess) {
1771 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001772 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001773 sTun.name().c_str());
1774 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001775 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1776 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001777 }
1778
1779 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1780 if (td.expectSuccess) {
1781 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001782 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1783 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001784 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001785 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1786 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001787 }
1788
Luke Huangc3252cc2018-10-16 15:43:23 +08001789 // Add system permission for test uid, route will be added into legacy system table.
1790 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001791
1792 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1793 testUid);
1794 if (td.expectSuccess) {
1795 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001796 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001797 testTableLegacySystem);
1798 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001799 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1800 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001801 }
1802
1803 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1804 td.testNextHop, testUid);
1805 if (td.expectSuccess) {
1806 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001807 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1808 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001809 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001810 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1811 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001812 }
1813
Luke Huangc3252cc2018-10-16 15:43:23 +08001814 // Remove system permission for test uid, route will be added into legacy network table.
1815 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1816
1817 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1818 testUid);
1819 if (td.expectSuccess) {
1820 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1821 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1822 testTableLegacyNetwork);
1823 } else {
1824 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1825 EXPECT_NE(0, status.serviceSpecificErrorCode());
1826 }
1827
1828 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1829 td.testNextHop, testUid);
1830 if (td.expectSuccess) {
1831 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1832 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1833 testTableLegacyNetwork);
1834 } else {
1835 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1836 EXPECT_NE(0, status.serviceSpecificErrorCode());
1837 }
Luke Huangb670d162018-08-23 20:01:13 +08001838 }
1839
1840 // Remove test physical network
1841 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1842}
1843
1844TEST_F(BinderTest, NetworkPermissionDefault) {
1845 // Add test physical network
1846 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1847 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1848
Luke Huangc3252cc2018-10-16 15:43:23 +08001849 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001850 int currentNetid;
1851 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1852 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1853
1854 // Test SetDefault
1855 status = mNetd->networkSetDefault(TEST_NETID1);
1856 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1857 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1858
1859 status = mNetd->networkClearDefault();
1860 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1861 expectNetworkDefaultIpRuleDoesNotExist();
1862
1863 // Add default network back
1864 status = mNetd->networkSetDefault(currentNetid);
1865 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1866
1867 // Test SetPermission
1868 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1869 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1870 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1871 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1872
1873 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1874 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1875 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1876 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1877
1878 // Remove test physical network
1879 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1880}
1881
1882TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1883 const int testUid = randomUid();
1884 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1885 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1886 bool ret = false;
1887 status = mNetd->networkCanProtect(testUid, &ret);
1888 EXPECT_TRUE(ret);
1889
1890 status = mNetd->networkSetProtectDeny(testUid);
1891 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1892 status = mNetd->networkCanProtect(testUid, &ret);
1893 EXPECT_FALSE(ret);
1894}
1895
1896namespace {
1897
Luke Huangb5733d72018-08-21 17:17:19 +08001898int readIntFromPath(const std::string& path) {
1899 std::string result = "";
1900 EXPECT_TRUE(ReadFileToString(path, &result));
1901 return std::stoi(result);
1902}
1903
1904int getTetherAcceptIPv6Ra(const std::string& ifName) {
1905 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1906 return readIntFromPath(path);
1907}
1908
1909bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1910 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1911 return readIntFromPath(path);
1912}
1913
1914int getTetherIPv6DadTransmits(const std::string& ifName) {
1915 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1916 return readIntFromPath(path);
1917}
1918
1919bool getTetherEnableIPv6(const std::string& ifName) {
1920 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1921 int disableIPv6 = readIntFromPath(path);
1922 return !disableIPv6;
1923}
1924
1925bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1926 for (const auto& iface : ifList) {
1927 if (iface == ifName) {
1928 return true;
1929 }
1930 }
1931 return false;
1932}
1933
1934void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1935 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1936 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1937 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1938 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1939}
1940
1941void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1942 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1943 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1944 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1945 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1946}
1947
1948void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1949 const std::string& ifName) {
1950 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1951}
1952
1953void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1954 const std::string& ifName) {
1955 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1956}
1957
1958void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
1959 const std::vector<std::string>& testDnsAddrs) {
1960 EXPECT_TRUE(dnsList == testDnsAddrs);
1961}
1962
1963} // namespace
1964
1965TEST_F(BinderTest, TetherStartStopStatus) {
1966 std::vector<std::string> noDhcpRange = {};
1967 static const char dnsdName[] = "dnsmasq";
1968
1969 binder::Status status = mNetd->tetherStart(noDhcpRange);
1970 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1971 EXPECT_TRUE(processExists(dnsdName));
1972
1973 bool tetherEnabled;
1974 status = mNetd->tetherIsEnabled(&tetherEnabled);
1975 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1976 EXPECT_TRUE(tetherEnabled);
1977
1978 status = mNetd->tetherStop();
1979 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1980 EXPECT_FALSE(processExists(dnsdName));
1981
1982 status = mNetd->tetherIsEnabled(&tetherEnabled);
1983 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1984 EXPECT_FALSE(tetherEnabled);
1985}
1986
1987TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
1988 // TODO: verify if dnsmasq update interface successfully
1989
1990 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
1991 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1992 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
1993
1994 std::vector<std::string> ifList;
1995 status = mNetd->tetherInterfaceList(&ifList);
1996 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1997 expectTetherInterfaceExists(ifList, sTun.name());
1998
1999 status = mNetd->tetherInterfaceRemove(sTun.name());
2000 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2001 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2002
2003 status = mNetd->tetherInterfaceList(&ifList);
2004 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2005 expectTetherInterfaceNotExists(ifList, sTun.name());
2006}
2007
2008TEST_F(BinderTest, TetherDnsSetList) {
2009 // TODO: verify if dnsmasq update dns successfully
2010 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
2011
2012 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2013 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2014
2015 std::vector<std::string> dnsList;
2016 status = mNetd->tetherDnsList(&dnsList);
2017 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2018 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002019}
2020
2021namespace {
2022
2023constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2024constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2025constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2026constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2027constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2028constexpr char FIREWALL_STANDBY[] = "fw_standby";
2029constexpr char targetReturn[] = "RETURN";
2030constexpr char targetDrop[] = "DROP";
2031
2032void expectFirewallWhitelistMode() {
2033 static const char dropRule[] = "DROP all";
2034 static const char rejectRule[] = "REJECT all";
2035 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2036 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2037 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2038 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2039 }
2040}
2041
2042void expectFirewallBlacklistMode() {
2043 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2044 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2045 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2046 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2047 }
2048}
2049
2050bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2051 const std::string& expectedInterface,
2052 const std::string& expectedRule) {
2053 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2054 // Expected rule:
2055 // Chain fw_INPUT (1 references)
2056 // pkts bytes target prot opt in out source destination
2057 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2058 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2059 int firstRuleIndex = 2;
2060 if (rules.size() < 4) return false;
2061 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2062 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2063 return true;
2064 }
2065 }
2066 return false;
2067}
2068
2069// TODO: It is a duplicate function, need to remove it
2070bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2071 const std::string& expectedInterface,
2072 const std::string& expectedRule) {
2073 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2074 for (const auto& rule : rules) {
2075 if (rule.find(expectedInterface) != std::string::npos) {
2076 if (rule.find(expectedRule) != std::string::npos) {
2077 return true;
2078 }
2079 }
2080 }
2081 return false;
2082}
2083
2084void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2085 static const char returnRule[] = "RETURN all";
2086 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2087 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2088 returnRule));
2089 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2090 returnRule));
2091 }
2092}
2093
2094void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2095 static const char returnRule[] = "RETURN all";
2096 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2097 EXPECT_FALSE(
2098 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2099 EXPECT_FALSE(
2100 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2101 }
2102}
2103
2104bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2105 const std::string& expectedTarget,
2106 const std::string& expectedRule) {
2107 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2108 int firstRuleIndex = 2;
2109 if (rules.size() < 4) return false;
2110 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2111 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2112 return true;
2113 }
2114 }
2115 return false;
2116}
2117
2118bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2119 const std::string& expectedTarget,
2120 const std::string& expectedRule) {
2121 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2122 int lastRuleIndex = rules.size() - 1;
2123 if (lastRuleIndex < 0) return false;
2124 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2125 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2126 return true;
2127 }
2128 }
2129 return false;
2130}
2131
2132void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2133 std::string uidRule = StringPrintf("owner UID match %u", uid);
2134 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2135 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2136}
2137
2138void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2139 std::string uidRule = StringPrintf("owner UID match %u", uid);
2140 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2141 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2142}
2143
2144void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2145 std::string uidRule = StringPrintf("owner UID match %u", uid);
2146 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2147 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2148}
2149
2150void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2151 std::string uidRule = StringPrintf("owner UID match %u", uid);
2152 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2153 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2154}
2155
2156bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2157 std::vector<std::string> inputRules =
2158 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2159 std::vector<std::string> outputRules =
2160 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2161 int inputLastRuleIndex = inputRules.size() - 1;
2162 int outputLastRuleIndex = outputRules.size() - 1;
2163
2164 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2165 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2166 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2167 return true;
2168 }
2169 }
2170 return false;
2171}
2172
2173void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2174 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2175 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2176}
2177
2178void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2179 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2180 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2181 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2182 }
2183}
2184
2185} // namespace
2186
2187TEST_F(BinderTest, FirewallSetFirewallType) {
2188 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2189 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2190 expectFirewallWhitelistMode();
2191
2192 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2193 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2194 expectFirewallBlacklistMode();
2195
2196 // set firewall type blacklist twice
2197 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2198 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2199 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2200 expectFirewallBlacklistMode();
2201
2202 // set firewall type whitelist twice
2203 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2204 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2205 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2206 expectFirewallWhitelistMode();
2207
2208 // reset firewall type to default
2209 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2210 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2211 expectFirewallBlacklistMode();
2212}
2213
2214TEST_F(BinderTest, FirewallSetInterfaceRule) {
2215 // setinterfaceRule is not supported in BLACKLIST MODE
2216 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2217 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2218
2219 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2220 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2221
2222 // set WHITELIST mode first
2223 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2224 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2225
2226 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2227 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2228 expectFirewallInterfaceRuleAllowExists(sTun.name());
2229
2230 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2231 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2232 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2233
2234 // reset firewall mode to default
2235 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2236 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2237 expectFirewallBlacklistMode();
2238}
2239
2240TEST_F(BinderTest, FirewallSetUidRule) {
2241 SKIP_IF_BPF_SUPPORTED;
2242
2243 int32_t uid = randomUid();
2244
2245 // Doze allow
2246 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2247 INetd::FIREWALL_RULE_ALLOW);
2248 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2249 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2250
2251 // Doze deny
2252 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2253 INetd::FIREWALL_RULE_DENY);
2254 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2255 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2256
2257 // Powersave allow
2258 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2259 INetd::FIREWALL_RULE_ALLOW);
2260 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2261 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2262
2263 // Powersave deny
2264 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2265 INetd::FIREWALL_RULE_DENY);
2266 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2267 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2268
2269 // Standby deny
2270 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2271 INetd::FIREWALL_RULE_DENY);
2272 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2273 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2274
2275 // Standby allow
2276 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2277 INetd::FIREWALL_RULE_ALLOW);
2278 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2279 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2280
2281 // None deny in BLACKLIST
2282 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2283 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2284 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2285 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2286
2287 // None allow in BLACKLIST
2288 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2289 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2290 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2291 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2292
2293 // set firewall type whitelist twice
2294 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2295 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2296 expectFirewallWhitelistMode();
2297
2298 // None allow in WHITELIST
2299 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2300 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2301 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2302 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2303
2304 // None deny in WHITELIST
2305 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2306 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2307 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2308 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2309
2310 // reset firewall mode to default
2311 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2312 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2313 expectFirewallBlacklistMode();
2314}
2315
2316TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2317 SKIP_IF_BPF_SUPPORTED;
2318
2319 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2320 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2321 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2322
2323 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2324 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2325 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2326
2327 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2328 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2329 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2330
2331 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2332 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2333 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2334
2335 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2336 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2337 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2338
2339 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2340 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2341 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2342}
Luke Huangf7782042018-08-08 13:13:04 +08002343
2344namespace {
2345
2346std::string hwAddrToStr(unsigned char* hwaddr) {
2347 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2348 hwaddr[4], hwaddr[5]);
2349}
2350
2351int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2352 int prefixLength = 0;
2353 uint32_t m = ntohl(mask);
2354 while (m & (1 << 31)) {
2355 prefixLength++;
2356 m = m << 1;
2357 }
2358 return prefixLength;
2359}
2360
2361std::string toStdString(const String16& s) {
2362 return std::string(String8(s.string()));
2363}
2364
2365android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2366 const auto& sys = sSyscalls.get();
2367 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2368 EXPECT_TRUE(isOk(fd.status()));
2369
2370 struct ifreq ifr = {};
2371 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2372
2373 return sys.ioctl(fd.value(), flag, &ifr);
2374}
2375
2376std::string getInterfaceHwAddr(const std::string& ifName) {
2377 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2378
2379 unsigned char hwaddr[ETH_ALEN] = {};
2380 if (isOk(res.status())) {
2381 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2382 }
2383
2384 return hwAddrToStr(hwaddr);
2385}
2386
2387int getInterfaceIPv4Prefix(const std::string& ifName) {
2388 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2389
2390 int prefixLength = 0;
2391 if (isOk(res.status())) {
2392 prefixLength = ipv4NetmaskToPrefixLength(
2393 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2394 }
2395
2396 return prefixLength;
2397}
2398
2399std::string getInterfaceIPv4Addr(const std::string& ifName) {
2400 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2401
2402 struct in_addr addr = {};
2403 if (isOk(res.status())) {
2404 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2405 }
2406
2407 return std::string(inet_ntoa(addr));
2408}
2409
2410std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2411 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2412
2413 unsigned flags = 0;
2414 if (isOk(res.status())) {
2415 flags = res.value().ifr_flags;
2416 }
2417
2418 std::vector<std::string> ifFlags;
2419 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2420 : toStdString(INetd::IF_STATE_DOWN()));
2421
2422 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2423 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2424 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2425 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2426 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2427
2428 return ifFlags;
2429}
2430
2431bool compareListInterface(const std::vector<std::string>& interfaceList) {
2432 const auto& res = InterfaceController::getIfaceNames();
2433 EXPECT_TRUE(isOk(res));
2434
2435 std::vector<std::string> resIfList;
2436 resIfList.reserve(res.value().size());
2437 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2438
2439 return resIfList == interfaceList;
2440}
2441
2442int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2443 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2444 return readIntFromPath(path);
2445}
2446
2447bool getInterfaceEnableIPv6(const std::string& ifName) {
2448 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2449
2450 int disableIPv6 = readIntFromPath(path);
2451 return !disableIPv6;
2452}
2453
2454int getInterfaceMtu(const std::string& ifName) {
2455 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2456 return readIntFromPath(path);
2457}
2458
2459void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2460 EXPECT_TRUE(compareListInterface(interfaceList));
2461}
2462
2463void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2464 const InterfaceConfigurationParcel& interfaceCfg) {
2465 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2466 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2467 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2468 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2469}
2470
2471void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2472 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2473 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2474
2475 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2476 for (const auto& flag : setCfg.flags) {
2477 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2478 }
2479}
2480
2481void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2482 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2483 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2484}
2485
2486void expectInterfaceNoAddr(const std::string& ifName) {
2487 // noAddr
2488 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2489 // noPrefix
2490 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2491}
2492
2493void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2494 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2495 EXPECT_EQ(enableIPv6, enable);
2496}
2497
2498void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2499 int mtuSize = getInterfaceMtu(ifName);
2500 EXPECT_EQ(mtu, mtuSize);
2501}
2502
2503InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2504 const std::string& addr, int prefixLength,
2505 const std::vector<std::string>& flags) {
2506 InterfaceConfigurationParcel cfg;
2507 cfg.ifName = ifName;
2508 cfg.hwAddr = "";
2509 cfg.ipv4Addr = addr;
2510 cfg.prefixLength = prefixLength;
2511 cfg.flags = flags;
2512 return cfg;
2513}
2514
2515void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2516 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2517 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2518
2519 for (const auto& flag : expectedFlags) {
2520 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2521 interfaceCfg.flags.end());
2522 }
2523
2524 for (const auto& flag : unexpectedFlags) {
2525 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2526 interfaceCfg.flags.end());
2527 }
2528}
2529
2530} // namespace
2531
2532TEST_F(BinderTest, InterfaceList) {
2533 std::vector<std::string> interfaceListResult;
2534
2535 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2536 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2537 expectInterfaceList(interfaceListResult);
2538}
2539
2540TEST_F(BinderTest, InterfaceGetCfg) {
2541 InterfaceConfigurationParcel interfaceCfgResult;
2542
2543 // Add test physical network
2544 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2545 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2546
2547 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2548 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2549 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2550 expectTunFlags(interfaceCfgResult);
2551
2552 // Remove test physical network
2553 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2554}
2555
2556TEST_F(BinderTest, InterfaceSetCfg) {
2557 const std::string testAddr = "192.0.2.3";
2558 const int testPrefixLength = 24;
2559 std::vector<std::string> upFlags = {"up"};
2560 std::vector<std::string> downFlags = {"down"};
2561
2562 // Add test physical network
2563 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2564 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2565
2566 // Set tun interface down.
2567 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2568 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2569 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2570 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2571
2572 // Set tun interface up again.
2573 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2574 status = mNetd->interfaceSetCfg(interfaceCfg);
2575 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2576 status = mNetd->interfaceClearAddrs(sTun.name());
2577 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2578
2579 // Remove test physical network
2580 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2581}
2582
2583TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2584 // enable
2585 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2586 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2587 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2588
2589 // disable
2590 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2591 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2592 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2593}
2594
2595TEST_F(BinderTest, InterfaceClearAddr) {
2596 const std::string testAddr = "192.0.2.3";
2597 const int testPrefixLength = 24;
2598 std::vector<std::string> noFlags{};
2599
2600 // Add test physical network
2601 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2602 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2603
2604 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2605 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2606 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2607 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2608
2609 status = mNetd->interfaceClearAddrs(sTun.name());
2610 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2611 expectInterfaceNoAddr(sTun.name());
2612
2613 // Remove test physical network
2614 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2615}
2616
2617TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2618 // Add test physical network
2619 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2620 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2621
2622 // disable
2623 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2624 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2625 expectInterfaceEnableIPv6(sTun.name(), false);
2626
2627 // enable
2628 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2629 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2630 expectInterfaceEnableIPv6(sTun.name(), true);
2631
2632 // Remove test physical network
2633 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2634}
2635
2636TEST_F(BinderTest, InterfaceSetMtu) {
2637 const int testMtu = 1200;
2638
2639 // Add test physical network
2640 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2641 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2642
2643 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2644 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2645 expectInterfaceMtu(sTun.name(), testMtu);
2646
2647 // Remove test physical network
2648 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2649}
Luke Huang19b49c52018-10-22 12:12:05 +09002650
2651namespace {
2652
2653constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2654constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002655constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002656constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2657
Luke Huangae038f82018-11-05 11:17:31 +09002658int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002659 return listIptablesRuleByTable(binary, table, chainName).size();
2660}
2661
2662bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2663 const std::vector<std::string>& targetVec) {
2664 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2665 if (targetVec.size() != rules.size() - 2) {
2666 return false;
2667 }
2668
2669 /*
Luke Huangae038f82018-11-05 11:17:31 +09002670 * Check that the rules match. Note that this function matches substrings, not entire rules,
2671 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002672 * Skip first two lines since rules start from third line.
2673 * Chain chainName (x references)
2674 * pkts bytes target prot opt in out source destination
2675 * ...
2676 */
2677 int rIndex = 2;
2678 for (const auto& target : targetVec) {
2679 if (rules[rIndex].find(target) == std::string::npos) {
2680 return false;
2681 }
2682 rIndex++;
2683 }
2684 return true;
2685}
2686
2687void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2688 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2689 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2690 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002691 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002692 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2693 "DROP"};
2694
2695 // V4
2696 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2697 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002698 EXPECT_TRUE(
2699 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002700 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2701
Luke Huangae038f82018-11-05 11:17:31 +09002702 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002703 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2704
2705 // V6
2706 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002707 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2708 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002709
2710 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2711 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2712 extIf));
2713 }
2714}
2715
2716void expectNatDisable() {
2717 // It is the default DROP rule with tethering disable.
2718 // Chain tetherctrl_FORWARD (1 references)
2719 // pkts bytes target prot opt in out source destination
2720 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2721 std::vector<std::string> forwardV4Match = {"DROP"};
2722 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2723
2724 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002725 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2726 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002727
Luke Huangae038f82018-11-05 11:17:31 +09002728 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2729 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002730
2731 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2732}
2733
2734} // namespace
2735
2736TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002737 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2738 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2739 expectNatEnable(sTun.name(), sTun2.name());
2740
2741 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2742 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2743 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002744}