blob: c805165507837f5be64f93559ee0d2ed617ad94b [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
Benedict Wong319f17e2018-05-15 17:06:44 -0700281TEST_F(BinderTest, IpSecTunnelInterface) {
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[] = {
Benedict Wong319f17e2018-05-15 17:06:44 -0700290 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53},
291 {"IPV6", "ipsec_test6", "::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
Benedict Wong319f17e2018-05-15 17:06:44 -0700299 // Create Tunnel Interface.
300 status = mNetd->ipSecAddTunnelInterface(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
Benedict Wong319f17e2018-05-15 17:06:44 -0700304 // Update Tunnel Interface.
305 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
306 td.iKey, td.oKey);
manojboopathi8707f232018-01-02 14:45:47 -0800307 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
308
Benedict Wong319f17e2018-05-15 17:06:44 -0700309 // Remove Tunnel Interface.
310 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800311 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
Benedict Wong319f17e2018-05-15 17:06:44 -0700335 return expectOk ==
336 XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D, 0xD00D, false)
337 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700338}
339
Benedict Wonga04ffa72018-05-09 21:42:42 -0700340TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
341 binder::Status status;
342
343 // Repeat to ensure cleanup and recreation works correctly
344 for (int i = 0; i < 2; i++) {
345 for (int direction : XFRM_DIRECTIONS) {
346 for (int addrFamily : ADDRESS_FAMILIES) {
347 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
348 "127.0.0.6", 123, 0, 0);
349 EXPECT_TRUE(status.isOk())
350 << " family: " << addrFamily << " direction: " << direction;
351 }
352 }
353
354 // Cleanup
355 for (int direction : XFRM_DIRECTIONS) {
356 for (int addrFamily : ADDRESS_FAMILIES) {
357 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0);
358 EXPECT_TRUE(status.isOk());
359 }
360 }
361 }
362}
363
364TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
365 binder::Status status;
366
367 // Repeat to ensure cleanup and recreation works correctly
368 for (int i = 0; i < 2; i++) {
369 for (int direction : XFRM_DIRECTIONS) {
370 for (int addrFamily : ADDRESS_FAMILIES) {
371 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
372 "2001:db8::d00d", 123, 0, 0);
373 EXPECT_TRUE(status.isOk())
374 << " family: " << addrFamily << " direction: " << direction;
375 }
376 }
377
378 // Cleanup
379 for (int direction : XFRM_DIRECTIONS) {
380 for (int addrFamily : ADDRESS_FAMILIES) {
381 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0);
382 EXPECT_TRUE(status.isOk());
383 }
384 }
385 }
386}
387
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900388TEST_F(BinderTest, XfrmControllerInit) {
Nathan Harold21299f72018-03-16 20:13:03 -0700389 netdutils::Status status;
390 status = XfrmController::Init();
391 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700392
393 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
394 // feature.
395 if (status.code() == EOPNOTSUPP) return;
396
Nathan Harold21299f72018-03-16 20:13:03 -0700397 ASSERT_TRUE(status.ok());
398
399 int32_t spi = 0;
400
401 ASSERT_TRUE(allocateIpSecResources(true, &spi));
402 ASSERT_TRUE(allocateIpSecResources(false, &spi));
403
404 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700405 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700406 ASSERT_TRUE(allocateIpSecResources(true, &spi));
407
408 // Clean up
409 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0);
410 SCOPED_TRACE(status);
411 ASSERT_TRUE(status.ok());
412
Benedict Wonga04ffa72018-05-09 21:42:42 -0700413 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700414 SCOPED_TRACE(status);
415 ASSERT_TRUE(status.ok());
416
417 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700418 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700419}
Nathan Harold2deff322018-05-10 14:03:48 -0700420#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700421
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900422static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900423 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900424
425 // Output looks like this:
426 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900427 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900428 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900429 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900430 //
431 // or:
432 //
433 // Chain bw_data_saver (1 references)
434 // target prot opt source destination
435 // ... possibly connectivity critical packet rules here ...
436 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900437
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900438 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900439
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900440 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
441 // Data saver disabled.
442 return 0;
443 }
444
445 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
446
447 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
448 // Data saver enabled.
449 return 1;
450 }
451
452 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900453}
454
455bool enableDataSaver(sp<INetd>& netd, bool enable) {
456 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
457 bool ret;
458 netd->bandwidthEnableDataSaver(enable, &ret);
459 return ret;
460}
461
462int getDataSaverState() {
463 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
464 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
465 EXPECT_EQ(enabled4, enabled6);
466 EXPECT_NE(-1, enabled4);
467 EXPECT_NE(-1, enabled6);
468 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
469 return -1;
470 }
471 return enabled6;
472}
473
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900474TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900475 const int wasEnabled = getDataSaverState();
476 ASSERT_NE(-1, wasEnabled);
477
478 if (wasEnabled) {
479 ASSERT_TRUE(enableDataSaver(mNetd, false));
480 EXPECT_EQ(0, getDataSaverState());
481 }
482
483 ASSERT_TRUE(enableDataSaver(mNetd, false));
484 EXPECT_EQ(0, getDataSaverState());
485
486 ASSERT_TRUE(enableDataSaver(mNetd, true));
487 EXPECT_EQ(1, getDataSaverState());
488
489 ASSERT_TRUE(enableDataSaver(mNetd, true));
490 EXPECT_EQ(1, getDataSaverState());
491
492 if (!wasEnabled) {
493 ASSERT_TRUE(enableDataSaver(mNetd, false));
494 EXPECT_EQ(0, getDataSaverState());
495 }
496}
Robin Leeb8087362016-03-30 18:43:08 +0100497
Luke Huang94658ac2018-10-18 19:35:12 +0900498static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
499 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100500 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100501 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100502 std::vector<std::string> rules = listIpRules(ipVersion);
503
504 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900505 std::string suffix =
506 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900507 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800508 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100509 return true;
510 }
511 }
512 return false;
513}
514
Luke Huang94658ac2018-10-18 19:35:12 +0900515static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
516 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100517 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
518 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
519 EXPECT_EQ(existsIp4, existsIp6);
520 return existsIp4;
521}
522
Luke Huang94658ac2018-10-18 19:35:12 +0900523namespace {
524
525UidRangeParcel makeUidRangeParcel(int start, int stop) {
526 UidRangeParcel res;
527 res.start = start;
528 res.stop = stop;
529
530 return res;
531}
532
533} // namespace
534
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900535TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800536 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
537 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
538 .serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900539 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
540 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
541
542 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
543 EXPECT_EQ(EBUSY,
544 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
545
546 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
547 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
548 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800549 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900550}
551
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900552TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900553 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
554
555 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
556 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
557 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
558
Luke Huang94658ac2018-10-18 19:35:12 +0900559 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
560 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
561 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900562 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
563
564 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
565
566 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
567 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
568 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
569 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
570
571 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
572 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
573 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
574 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
575
576 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
577}
578
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900579TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100580 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100581
Luke Huang94658ac2018-10-18 19:35:12 +0900582 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
583 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100584
585 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
586 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
587
588 // Create two valid rules.
589 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
590 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
591 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
592 for (auto const& range : uidRanges) {
593 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
594 }
595
596 // Remove the rules.
597 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
598 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
599 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
600 for (auto const& range : uidRanges) {
601 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
602 }
603
604 // Fail to remove the rules a second time after they are already deleted.
605 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
606 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
607 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
608
609 // All rules should be the same as before.
610 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
611 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
612}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900613
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900614// Create a socket pair that isLoopbackSocket won't think is local.
615void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900616 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900617 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900618 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
619
620 socklen_t addrlen = sizeof(server6);
621 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
622 ASSERT_EQ(0, listen(*serverSocket, 10));
623
Bernie Innocentif6918262018-06-11 17:37:35 +0900624 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900625 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900626 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900627 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
628 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
629
Bernie Innocentif6918262018-06-11 17:37:35 +0900630 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900631 ASSERT_NE(-1, *acceptedSocket);
632
633 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
634}
635
636void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
637 char buf[4096];
638 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
639 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
640 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
641}
642
643void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
644 // Check that the client socket was closed with ECONNABORTED.
645 int ret = write(clientSocket, "foo", sizeof("foo"));
646 int err = errno;
647 EXPECT_EQ(-1, ret);
648 EXPECT_EQ(ECONNABORTED, err);
649
650 // Check that it sent a RST to the server.
651 ret = write(acceptedSocket, "foo", sizeof("foo"));
652 err = errno;
653 EXPECT_EQ(-1, ret);
654 EXPECT_EQ(ECONNRESET, err);
655}
656
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900657TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900658 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900659 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900660
661 // Pick a random UID in the system UID range.
662 constexpr int baseUid = AID_APP - 2000;
663 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
664 int uid = baseUid + 500 + arc4random_uniform(1000);
665 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
666
667 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900668 std::vector<UidRangeParcel> uidRanges = {
669 makeUidRangeParcel(baseUid + 42, baseUid + 449),
670 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
671 makeUidRangeParcel(baseUid + 498, uid - 1),
672 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900673 };
674 // A skip list that doesn't contain UID.
675 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
676
677 // Close sockets. Our test socket should be intact.
678 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
679 checkSocketpairOpen(clientSocket, acceptedSocket);
680
681 // UID ranges that do contain uid.
682 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900683 makeUidRangeParcel(baseUid + 42, baseUid + 449),
684 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
685 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900686 };
687 // Add uid to the skip list.
688 skipUids.push_back(uid);
689
690 // Close sockets. Our test socket should still be intact because it's in the skip list.
691 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
692 checkSocketpairOpen(clientSocket, acceptedSocket);
693
694 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
695 skipUids.resize(skipUids.size() - 1);
696 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
697 checkSocketpairClosed(clientSocket, acceptedSocket);
698
699 close(clientSocket);
700 close(serverSocket);
701 close(acceptedSocket);
702}
Erik Klinecc4f2732016-08-03 11:24:27 +0900703
704namespace {
705
706int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
707 if (buf == nullptr) return -1;
708
709 int prefixLength = 0;
710 bool endOfContiguousBits = false;
711 for (unsigned int i = 0; i < buflen; i++) {
712 const uint8_t value = buf[i];
713
714 // Bad bit sequence: check for a contiguous set of bits from the high
715 // end by verifying that the inverted value + 1 is a power of 2
716 // (power of 2 iff. (v & (v - 1)) == 0).
717 const uint8_t inverse = ~value + 1;
718 if ((inverse & (inverse - 1)) != 0) return -1;
719
720 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
721
722 // Bogus netmask.
723 if (endOfContiguousBits && value != 0) return -1;
724
725 if (value != 0xff) endOfContiguousBits = true;
726 }
727
728 return prefixLength;
729}
730
731template<typename T>
732int netmaskToPrefixLength(const T *p) {
733 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
734}
735
736
737static bool interfaceHasAddress(
738 const std::string &ifname, const char *addrString, int prefixLength) {
739 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900740
741 const struct addrinfo hints = {
742 .ai_flags = AI_NUMERICHOST,
743 .ai_family = AF_UNSPEC,
744 .ai_socktype = SOCK_DGRAM,
745 };
746 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
747 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
748 return false;
749 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900750 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900751
752 struct ifaddrs *ifaddrsList = nullptr;
753 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
754
755 if (getifaddrs(&ifaddrsList) != 0) {
756 return false;
757 }
758
759 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
760 if (std::string(addr->ifa_name) != ifname ||
761 addr->ifa_addr == nullptr ||
762 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
763 continue;
764 }
765
766 switch (addr->ifa_addr->sa_family) {
767 case AF_INET: {
768 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
769 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
770 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
771 continue;
772 }
773
774 if (prefixLength < 0) return true; // not checking prefix lengths
775
776 if (addr->ifa_netmask == nullptr) return false;
777 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
778 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
779 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
780 }
781 case AF_INET6: {
782 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
783 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
784 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
785 continue;
786 }
787
788 if (prefixLength < 0) return true; // not checking prefix lengths
789
790 if (addr->ifa_netmask == nullptr) return false;
791 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
792 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
793 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
794 }
795 default:
796 // Cannot happen because we have already screened for matching
797 // address families at the top of each iteration.
798 continue;
799 }
800 }
801
802 return false;
803}
804
805} // namespace
806
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900807TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900808 static const struct TestData {
809 const char *addrString;
810 const int prefixLength;
811 const bool expectSuccess;
812 } kTestData[] = {
813 { "192.0.2.1", 24, true },
814 { "192.0.2.2", 25, true },
815 { "192.0.2.3", 32, true },
816 { "192.0.2.4", 33, false },
817 { "192.not.an.ip", 24, false },
818 { "2001:db8::1", 64, true },
819 { "2001:db8::2", 65, true },
820 { "2001:db8::3", 128, true },
821 { "2001:db8::4", 129, false },
822 { "foo:bar::bad", 64, false },
823 };
824
Luke Huangc3252cc2018-10-16 15:43:23 +0800825 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900826 const auto &td = kTestData[i];
827
828 // [1.a] Add the address.
829 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900830 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900831 if (td.expectSuccess) {
832 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
833 } else {
834 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
835 ASSERT_NE(0, status.serviceSpecificErrorCode());
836 }
837
838 // [1.b] Verify the addition meets the expectation.
839 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900840 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900841 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900842 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900843 }
844
845 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900846 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900847 if (td.expectSuccess) {
848 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
849 } else {
850 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
851 ASSERT_NE(0, status.serviceSpecificErrorCode());
852 }
853
854 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900855 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900856 }
857}
Erik Kline55b06f82016-07-04 09:57:18 +0900858
Erik Kline38e51f12018-09-06 20:14:44 +0900859TEST_F(BinderTest, GetProcSysNet) {
860 const char LOOPBACK[] = "lo";
861 static const struct {
862 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900863 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900864 const char* ifname;
865 const char* parameter;
866 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900867 const int expectedReturnCode;
868 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900869 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
870 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
871 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
872 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
873 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
874 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
875 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900876 };
877
Luke Huangc3252cc2018-10-16 15:43:23 +0800878 for (int i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900879 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900880
Erik Kline38e51f12018-09-06 20:14:44 +0900881 std::string value;
882 const binder::Status status =
883 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
884
885 if (td.expectedReturnCode == 0) {
886 SCOPED_TRACE(String8::format("test case %d should have passed", i));
887 EXPECT_EQ(0, status.exceptionCode());
888 EXPECT_EQ(0, status.serviceSpecificErrorCode());
889 EXPECT_EQ(td.expectedValue, value);
890 } else {
891 SCOPED_TRACE(String8::format("test case %d should have failed", i));
892 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
893 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
894 }
895 }
896}
897
898TEST_F(BinderTest, SetProcSysNet) {
899 static const struct {
900 const int ipversion;
901 const int which;
902 const char* ifname;
903 const char* parameter;
904 const char* value;
905 const int expectedReturnCode;
906 } kTestData[] = {
907 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
908 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
909 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
910 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
911 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
912 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
913 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
914 };
915
Luke Huangc3252cc2018-10-16 15:43:23 +0800916 for (int i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900917 const auto& td = kTestData[i];
918
919 const binder::Status status =
920 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900921
922 if (td.expectedReturnCode == 0) {
923 SCOPED_TRACE(String8::format("test case %d should have passed", i));
924 EXPECT_EQ(0, status.exceptionCode());
925 EXPECT_EQ(0, status.serviceSpecificErrorCode());
926 } else {
927 SCOPED_TRACE(String8::format("test case %d should have failed", i));
928 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
929 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
930 }
931 }
932}
Ben Schwartze7601812017-04-28 16:38:29 -0400933
Erik Kline38e51f12018-09-06 20:14:44 +0900934TEST_F(BinderTest, GetSetProcSysNet) {
935 const int ipversion = INetd::IPV6;
936 const int category = INetd::NEIGH;
937 const std::string& tun = sTun.name();
938 const std::string parameter("ucast_solicit");
939
940 std::string value{};
941 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
942 EXPECT_FALSE(value.empty());
943 const int ival = std::stoi(value);
944 EXPECT_GT(ival, 0);
945 // Try doubling the parameter value (always best!).
946 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
947 .isOk());
948 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
949 EXPECT_EQ(2 * ival, std::stoi(value));
950 // Try resetting the parameter.
951 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
952 .isOk());
953 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
954 EXPECT_EQ(ival, std::stoi(value));
955}
956
Ben Schwartze7601812017-04-28 16:38:29 -0400957static std::string base64Encode(const std::vector<uint8_t>& input) {
958 size_t out_len;
959 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
960 // out_len includes the trailing NULL.
961 uint8_t output_bytes[out_len];
962 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
963 return std::string(reinterpret_cast<char*>(output_bytes));
964}
965
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900966TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900967 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400968 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400969 std::vector<uint8_t> short_fp(1);
970 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
971 std::vector<std::string> test_domains;
972 std::vector<int> test_params = { 300, 25, 8, 8 };
973 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400974 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400975 const std::vector<std::string> servers;
976 const std::string tlsName;
977 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400978 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900979 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400980 { {"192.0.2.1"}, "", {}, 0 },
981 { {"2001:db8::2"}, "host.name", {}, 0 },
982 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
983 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900984 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400985 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900986 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400987 { {"2001:dg8::6"}, "", {}, EINVAL },
988 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
989 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
990 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
991 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400992 };
993
Luke Huangc3252cc2018-10-16 15:43:23 +0800994 for (unsigned int i = 0; i < std::size(kTlsTestData); i++) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900995 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -0400996
997 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400998 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400999 fingerprints.push_back(base64Encode(fingerprint));
1000 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001001 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001002 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
1003 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -04001004
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001005 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -04001006 SCOPED_TRACE(String8::format("test case %d should have passed", i));
1007 SCOPED_TRACE(status.toString8());
1008 EXPECT_EQ(0, status.exceptionCode());
1009 } else {
1010 SCOPED_TRACE(String8::format("test case %d should have failed", i));
1011 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001012 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -04001013 }
Ben Schwartze7601812017-04-28 16:38:29 -04001014 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001015 // Ensure TLS is disabled before the start of the next test.
1016 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001017 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1018 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001019}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001020
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001021namespace {
1022
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001023void expectNoTestCounterRules() {
1024 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1025 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1026 std::string allRules = Join(runCommand(command), "\n");
1027 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1028 }
1029}
1030
Bernie Innocentif6918262018-06-11 17:37:35 +09001031void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1032 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001033 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1034 path, if1.c_str(), if2.c_str(), pkt, byte));
1035}
1036
Bernie Innocentif6918262018-06-11 17:37:35 +09001037void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001038 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1039 path, if1.c_str(), if2.c_str()));
1040 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1041 path, if2.c_str(), if1.c_str()));
1042}
1043
Luke Huangcaebcbb2018-09-27 20:37:14 +08001044std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1045 const std::string& iface) {
1046 for (auto& stats : statsVec) {
1047 if (stats.iface == iface) {
1048 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1049 }
1050 }
1051 return {};
1052}
1053
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001054} // namespace
1055
1056TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001057 expectNoTestCounterRules();
1058
1059 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1060 // disabling tethering. We don't check the return value because these commands will fail if
1061 // tethering is already enabled.
1062 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1063 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1064
1065 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1066 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1067 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1068 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1069 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1070
1071 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1072 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1073 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1074 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1075 // RX is from external to internal, and TX is from internal to external.
1076 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1077 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1078
1079 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1080 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1081
1082 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1083 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1084
1085 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1086 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1087 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1088
Luke Huangcaebcbb2018-09-27 20:37:14 +08001089 std::vector<TetherStatsParcel> statsVec;
1090 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001091 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1092
Luke Huangcaebcbb2018-09-27 20:37:14 +08001093 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001094
Luke Huangcaebcbb2018-09-27 20:37:14 +08001095 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001096
1097 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1098 delTetherCounterValues(path, intIface1, extIface1);
1099 delTetherCounterValues(path, intIface2, extIface2);
1100 if (path == IP6TABLES_PATH) {
1101 delTetherCounterValues(path, intIface3, extIface2);
1102 }
1103 }
1104
1105 expectNoTestCounterRules();
1106}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001107
Luke Huang0051a622018-07-23 20:30:16 +08001108namespace {
1109
Luke Huanga5211072018-08-01 23:36:29 +08001110constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1111constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001112
1113static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1114 const char* chainName) {
1115 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1116 return runCommand(command);
1117}
1118
Luke Huang19b49c52018-10-22 12:12:05 +09001119// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001120bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001121 const std::string& expectedInterface,
1122 const std::string& expectedRule, const char* table) {
1123 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1124 for (const auto& rule : rules) {
1125 if (rule.find(expectedInterface) != std::string::npos) {
1126 if (rule.find(expectedRule) != std::string::npos) {
1127 return true;
1128 }
1129 }
1130 }
1131 return false;
1132}
1133
1134void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001135 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001136 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001137 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001138 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001139 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1140 IdletimerRule, RAW_TABLE));
1141 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001142 ifname, IdletimerRule, MANGLE_TABLE));
1143 }
1144}
1145
1146void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001147 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001148 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001149 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001150 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001151 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1152 IdletimerRule, RAW_TABLE));
1153 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001154 ifname, IdletimerRule, MANGLE_TABLE));
1155 }
1156}
1157
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001158} // namespace
1159
1160TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001161 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1162 // rule in the table. Because we only check the result after calling remove function. We might
1163 // check the actual rule which is removed by our function (maybe compare the results between
1164 // calling function before and after)
1165 binder::Status status;
1166 const struct TestData {
1167 const std::string ifname;
1168 int32_t timeout;
1169 const std::string classLabel;
1170 } idleTestData[] = {
1171 {"wlan0", 1234, "happyday"},
1172 {"rmnet_data0", 4567, "friday"},
1173 };
1174 for (const auto& td : idleTestData) {
1175 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1176 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1177 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1178
1179 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1180 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1181 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1182 }
1183}
1184
Luke Huanga67dd562018-07-17 19:58:25 +08001185namespace {
1186
1187constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1188constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1189
1190void expectStrictSetUidAccept(const int uid) {
1191 std::string uidRule = StringPrintf("owner UID match %u", uid);
1192 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1193 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1194 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1195 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1196 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1197 }
1198}
1199
1200void expectStrictSetUidLog(const int uid) {
1201 static const char logRule[] = "st_penalty_log all";
1202 std::string uidRule = StringPrintf("owner UID match %u", uid);
1203 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1204 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1205 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1206 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1207 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1208 }
1209}
1210
1211void expectStrictSetUidReject(const int uid) {
1212 static const char rejectRule[] = "st_penalty_reject all";
1213 std::string uidRule = StringPrintf("owner UID match %u", uid);
1214 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1215 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1216 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1217 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1218 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1219 }
1220}
1221
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001222} // namespace
1223
1224TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001225 binder::Status status;
1226 int32_t uid = randomUid();
1227
1228 // setUidCleartextPenalty Policy:Log with randomUid
1229 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1230 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1231 expectStrictSetUidLog(uid);
1232
1233 // setUidCleartextPenalty Policy:Accept with randomUid
1234 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1235 expectStrictSetUidAccept(uid);
1236
1237 // setUidCleartextPenalty Policy:Reject with randomUid
1238 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1239 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1240 expectStrictSetUidReject(uid);
1241
1242 // setUidCleartextPenalty Policy:Accept with randomUid
1243 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1244 expectStrictSetUidAccept(uid);
1245
1246 // test wrong policy
1247 int32_t wrongPolicy = -123;
1248 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1249 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1250}
1251
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001252namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001253
Luke Huanga5211072018-08-01 23:36:29 +08001254bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001255 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1256 return (runCommand(cmd.c_str()).size()) ? true : false;
1257}
1258
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001259} // namespace
1260
1261TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001262 binder::Status status;
1263 // use dummy0 for test since it is set ready
1264 static const char testIf[] = "dummy0";
1265 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1266
1267 status = mNetd->clatdStart(testIf);
1268 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1269 EXPECT_TRUE(processExists(clatdName));
1270
1271 mNetd->clatdStop(testIf);
1272 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1273 EXPECT_FALSE(processExists(clatdName));
1274}
Luke Huang457d4702018-08-16 15:39:15 +08001275
1276namespace {
1277
1278bool getIpfwdV4Enable() {
1279 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1280 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1281 EXPECT_TRUE(!result.empty());
1282 int v4Enable = std::stoi(result[0]);
1283 return v4Enable;
1284}
1285
1286bool getIpfwdV6Enable() {
1287 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1288 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1289 EXPECT_TRUE(!result.empty());
1290 int v6Enable = std::stoi(result[0]);
1291 return v6Enable;
1292}
1293
1294void expectIpfwdEnable(bool enable) {
1295 int enableIPv4 = getIpfwdV4Enable();
1296 int enableIPv6 = getIpfwdV6Enable();
1297 EXPECT_EQ(enable, enableIPv4);
1298 EXPECT_EQ(enable, enableIPv6);
1299}
1300
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001301bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001302 std::vector<std::string> rules = listIpRules(ipVersion);
1303 for (const auto& rule : rules) {
1304 if (rule.find(ipfwdRule) != std::string::npos) {
1305 return true;
1306 }
1307 }
1308 return false;
1309}
1310
1311void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1312 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1313
1314 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1315 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1316 }
1317}
1318
1319void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1320 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1321
1322 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1323 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1324 }
1325}
1326
1327} // namespace
1328
1329TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1330 // Netd default enable Ipfwd with requester NetdHwService
1331 const std::string defaultRequester = "NetdHwService";
1332
1333 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1334 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1335 expectIpfwdEnable(false);
1336
1337 bool ipfwdEnabled;
1338 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1339 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1340 EXPECT_FALSE(ipfwdEnabled);
1341
1342 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1343 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1344 expectIpfwdEnable(true);
1345
1346 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1347 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1348 EXPECT_TRUE(ipfwdEnabled);
1349}
1350
1351TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1352 static const char testFromIf[] = "dummy0";
1353 static const char testToIf[] = "dummy0";
1354
1355 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1356 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1357 expectIpfwdRuleExists(testFromIf, testToIf);
1358
1359 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1360 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1361 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001362}
Luke Huang531f5d32018-08-03 15:19:05 +08001363
1364namespace {
1365
1366constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1367constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1368constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1369constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1370constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001371constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001372
Luke Huang19b49c52018-10-22 12:12:05 +09001373// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1374// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001375bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1376 const char* chainName, const std::string& expectedTargetA,
1377 const std::string& expectedTargetB) {
1378 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1379 int matchCount = 0;
1380
1381 for (const auto& rule : rules) {
1382 if (rule.find(expectedTargetA) != std::string::npos) {
1383 if (rule.find(expectedTargetB) != std::string::npos) {
1384 matchCount++;
1385 }
1386 }
1387 }
1388 return matchCount == expectedCount;
1389}
1390
1391void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1392 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1393 std::string result = "";
1394
1395 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001396 // Quota value might be decreased while matching packets
1397 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001398}
1399
1400void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1401 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1402 std::string quotaRule = StringPrintf("quota %s", ifname);
1403
1404 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1405 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1406 BANDWIDTH_COSTLY_IF));
1407 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1408 BANDWIDTH_COSTLY_IF));
1409 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1410 BANDWIDTH_COSTLY_IF));
1411 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1412 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1413 }
1414 expectXtQuotaValueEqual(ifname, quotaBytes);
1415}
1416
1417void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1418 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1419 std::string quotaRule = StringPrintf("quota %s", ifname);
1420
1421 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1422 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1423 BANDWIDTH_COSTLY_IF));
1424 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1425 BANDWIDTH_COSTLY_IF));
1426 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1427 BANDWIDTH_COSTLY_IF));
1428 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1429 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1430 }
1431}
1432
1433void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1434 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1435 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1436 std::string alertName = StringPrintf("%sAlert", ifname);
1437
1438 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1439 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1440 }
1441 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1442}
1443
1444void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1445 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1446 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1447
1448 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1449 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1450 }
1451}
1452
1453void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1454 static const char globalAlertRule[] = "quota globalAlert";
1455 static const char globalAlertName[] = "globalAlert";
1456
1457 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001458 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001459 }
1460 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1461}
1462
1463void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1464 std::string uidRule = StringPrintf("owner UID match %u", uid);
1465
1466 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1467 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1468 }
1469}
1470
1471void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1472 std::string uidRule = StringPrintf("owner UID match %u", uid);
1473
1474 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1475 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1476 }
1477}
1478
1479} // namespace
1480
1481TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1482 long testQuotaBytes = 5550;
1483
1484 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001485 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001486 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1487
1488 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1489 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1490 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1491
1492 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1493 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1494 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1495
1496 // Remove test physical network
1497 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1498}
1499
1500TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1501 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001502 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001503 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001504 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001505 // Need to have a prior interface quota set to set an alert
1506 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1507 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1508 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1509 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1510
1511 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1512 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1513 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1514
1515 // Remove interface quota
1516 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1517 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1518 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1519
1520 // Remove test physical network
1521 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1522}
1523
1524TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1525 long testAlertBytes = 2097149;
1526
1527 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1528 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1529 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1530
1531 testAlertBytes = 2097152;
1532 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1533 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1534 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1535}
1536
1537TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1538 SKIP_IF_BPF_SUPPORTED;
1539
1540 int32_t uid = randomUid();
1541 static const char targetReject[] = "REJECT";
1542 static const char targetReturn[] = "RETURN";
1543
1544 // add NaughtyApp
1545 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1546 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1547 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1548
1549 // remove NaughtyApp
1550 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1551 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1552 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1553
1554 // add NiceApp
1555 status = mNetd->bandwidthAddNiceApp(uid);
1556 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1557 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1558
1559 // remove NiceApp
1560 status = mNetd->bandwidthRemoveNiceApp(uid);
1561 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1562 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1563}
Luke Huangb5733d72018-08-21 17:17:19 +08001564
1565namespace {
1566
Luke Huangb670d162018-08-23 20:01:13 +08001567std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1568 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1569 return runCommand(command);
1570}
1571
Luke Huangc3252cc2018-10-16 15:43:23 +08001572bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001573 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1574 for (const auto& route : routes) {
1575 if (route.find(ipRoute) != std::string::npos) {
1576 return true;
1577 }
1578 }
1579 return false;
1580}
1581
Luke Huangc3252cc2018-10-16 15:43:23 +08001582std::string ipRouteString(const std::string& ifName, const std::string& dst,
1583 const std::string& nextHop) {
1584 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1585
1586 if (!nextHop.empty()) {
1587 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001588 }
1589
Luke Huangc3252cc2018-10-16 15:43:23 +08001590 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001591}
1592
Luke Huangc3252cc2018-10-16 15:43:23 +08001593void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1594 const std::string& dst, const std::string& nextHop,
1595 const char* table) {
1596 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1597}
1598
1599void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001600 const std::string& dst, const std::string& nextHop,
1601 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001602 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001603}
1604
1605bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1606 std::vector<std::string> rules = listIpRules(ipVersion);
1607 for (const auto& rule : rules) {
1608 if (rule.find(ipRule) != std::string::npos) {
1609 return true;
1610 }
1611 }
1612 return false;
1613}
1614
1615void expectNetworkDefaultIpRuleExists(const char* ifName) {
1616 std::string networkDefaultRule =
1617 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1618
1619 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1620 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1621 }
1622}
1623
1624void expectNetworkDefaultIpRuleDoesNotExist() {
1625 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1626
1627 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1628 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1629 }
1630}
1631
1632void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1633 std::string networkPermissionRule = "";
1634 switch (permission) {
1635 case INetd::PERMISSION_NONE:
1636 networkPermissionRule = StringPrintf(
1637 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1638 break;
1639 case INetd::PERMISSION_NETWORK:
1640 networkPermissionRule = StringPrintf(
1641 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1642 break;
1643 case INetd::PERMISSION_SYSTEM:
1644 networkPermissionRule = StringPrintf(
1645 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1646 break;
1647 }
1648
1649 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1650 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1651 }
1652}
1653
1654// TODO: It is a duplicate function, need to remove it
1655bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1656 const std::string& expectedInterface,
1657 const std::string& expectedRule,
1658 const char* table) {
1659 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1660 for (const auto& rule : rules) {
1661 if (rule.find(expectedInterface) != std::string::npos) {
1662 if (rule.find(expectedRule) != std::string::npos) {
1663 return true;
1664 }
1665 }
1666 }
1667 return false;
1668}
1669
1670void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1671 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1672 std::string networkIncomingPacketMarkRule = "";
1673 switch (permission) {
1674 case INetd::PERMISSION_NONE:
1675 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1676 break;
1677 case INetd::PERMISSION_NETWORK:
1678 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1679 break;
1680 case INetd::PERMISSION_SYSTEM:
1681 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1682 break;
1683 }
1684
1685 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1686 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1687 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1688 }
1689}
1690
1691} // namespace
1692
1693TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001694 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001695 const char* ipVersion;
1696 const char* testDest;
1697 const char* testNextHop;
1698 const bool expectSuccess;
1699 } kTestData[] = {
1700 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001701 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1702 {IP_RULE_V4, "10.251.0.0/16", "", true},
1703 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1704 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001705 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001706 {IP_RULE_V6, "::/0", "2001:db8::", true},
1707 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001708 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1709 };
1710
Luke Huangc3252cc2018-10-16 15:43:23 +08001711 static const struct {
1712 const char* ipVersion;
1713 const char* testDest;
1714 const char* testNextHop;
1715 } kTestDataWithNextHop[] = {
1716 {IP_RULE_V4, "10.251.10.0/30", ""},
1717 {IP_RULE_V6, "2001:db8::/32", ""},
1718 };
1719
Luke Huangb670d162018-08-23 20:01:13 +08001720 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001721 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001722 const int testUid = randomUid();
1723 const std::vector<int32_t> testUids = {testUid};
1724
1725 // Add test physical network
1726 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1727 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1728
Luke Huangc3252cc2018-10-16 15:43:23 +08001729 // Setup route for testing nextHop
1730 for (unsigned int i = 0; i < std::size(kTestDataWithNextHop); i++) {
1731 const auto& td = kTestDataWithNextHop[i];
1732
1733 // All route for test tun will disappear once the tun interface is deleted.
1734 binder::Status status =
1735 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1736 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1737 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1738 sTun.name().c_str());
1739
1740 // Add system permission for test uid, setup route in legacy system table.
1741 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1742
1743 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1744 testUid);
1745 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1746 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1747 testTableLegacySystem);
1748
1749 // Remove system permission for test uid, setup route in legacy network table.
1750 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1751
1752 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1753 testUid);
1754 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1755 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1756 testTableLegacyNetwork);
1757 }
1758
1759 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001760 const auto& td = kTestData[i];
1761
1762 binder::Status status =
1763 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1764 if (td.expectSuccess) {
1765 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001766 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001767 sTun.name().c_str());
1768 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001769 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1770 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001771 }
1772
1773 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1774 if (td.expectSuccess) {
1775 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001776 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1777 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001778 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001779 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1780 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001781 }
1782
Luke Huangc3252cc2018-10-16 15:43:23 +08001783 // Add system permission for test uid, route will be added into legacy system table.
1784 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001785
1786 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1787 testUid);
1788 if (td.expectSuccess) {
1789 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001790 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001791 testTableLegacySystem);
1792 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001793 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1794 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001795 }
1796
1797 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1798 td.testNextHop, testUid);
1799 if (td.expectSuccess) {
1800 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001801 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1802 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001803 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001804 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1805 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001806 }
1807
Luke Huangc3252cc2018-10-16 15:43:23 +08001808 // Remove system permission for test uid, route will be added into legacy network table.
1809 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1810
1811 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1812 testUid);
1813 if (td.expectSuccess) {
1814 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1815 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1816 testTableLegacyNetwork);
1817 } else {
1818 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1819 EXPECT_NE(0, status.serviceSpecificErrorCode());
1820 }
1821
1822 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1823 td.testNextHop, testUid);
1824 if (td.expectSuccess) {
1825 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1826 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1827 testTableLegacyNetwork);
1828 } else {
1829 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1830 EXPECT_NE(0, status.serviceSpecificErrorCode());
1831 }
Luke Huangb670d162018-08-23 20:01:13 +08001832 }
1833
1834 // Remove test physical network
1835 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1836}
1837
1838TEST_F(BinderTest, NetworkPermissionDefault) {
1839 // Add test physical network
1840 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1841 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1842
Luke Huangc3252cc2018-10-16 15:43:23 +08001843 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001844 int currentNetid;
1845 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1846 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1847
1848 // Test SetDefault
1849 status = mNetd->networkSetDefault(TEST_NETID1);
1850 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1851 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1852
1853 status = mNetd->networkClearDefault();
1854 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1855 expectNetworkDefaultIpRuleDoesNotExist();
1856
1857 // Add default network back
1858 status = mNetd->networkSetDefault(currentNetid);
1859 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1860
1861 // Test SetPermission
1862 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1863 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1864 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1865 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1866
1867 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1868 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1869 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1870 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1871
1872 // Remove test physical network
1873 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1874}
1875
1876TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1877 const int testUid = randomUid();
1878 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1879 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1880 bool ret = false;
1881 status = mNetd->networkCanProtect(testUid, &ret);
1882 EXPECT_TRUE(ret);
1883
1884 status = mNetd->networkSetProtectDeny(testUid);
1885 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1886 status = mNetd->networkCanProtect(testUid, &ret);
1887 EXPECT_FALSE(ret);
1888}
1889
1890namespace {
1891
Luke Huangb5733d72018-08-21 17:17:19 +08001892int readIntFromPath(const std::string& path) {
1893 std::string result = "";
1894 EXPECT_TRUE(ReadFileToString(path, &result));
1895 return std::stoi(result);
1896}
1897
1898int getTetherAcceptIPv6Ra(const std::string& ifName) {
1899 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1900 return readIntFromPath(path);
1901}
1902
1903bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1904 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1905 return readIntFromPath(path);
1906}
1907
1908int getTetherIPv6DadTransmits(const std::string& ifName) {
1909 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1910 return readIntFromPath(path);
1911}
1912
1913bool getTetherEnableIPv6(const std::string& ifName) {
1914 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1915 int disableIPv6 = readIntFromPath(path);
1916 return !disableIPv6;
1917}
1918
1919bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1920 for (const auto& iface : ifList) {
1921 if (iface == ifName) {
1922 return true;
1923 }
1924 }
1925 return false;
1926}
1927
1928void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1929 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1930 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1931 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1932 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1933}
1934
1935void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1936 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1937 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1938 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1939 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1940}
1941
1942void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1943 const std::string& ifName) {
1944 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1945}
1946
1947void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1948 const std::string& ifName) {
1949 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1950}
1951
1952void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
1953 const std::vector<std::string>& testDnsAddrs) {
1954 EXPECT_TRUE(dnsList == testDnsAddrs);
1955}
1956
1957} // namespace
1958
1959TEST_F(BinderTest, TetherStartStopStatus) {
1960 std::vector<std::string> noDhcpRange = {};
1961 static const char dnsdName[] = "dnsmasq";
1962
1963 binder::Status status = mNetd->tetherStart(noDhcpRange);
1964 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1965 EXPECT_TRUE(processExists(dnsdName));
1966
1967 bool tetherEnabled;
1968 status = mNetd->tetherIsEnabled(&tetherEnabled);
1969 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1970 EXPECT_TRUE(tetherEnabled);
1971
1972 status = mNetd->tetherStop();
1973 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1974 EXPECT_FALSE(processExists(dnsdName));
1975
1976 status = mNetd->tetherIsEnabled(&tetherEnabled);
1977 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1978 EXPECT_FALSE(tetherEnabled);
1979}
1980
1981TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
1982 // TODO: verify if dnsmasq update interface successfully
1983
1984 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
1985 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1986 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
1987
1988 std::vector<std::string> ifList;
1989 status = mNetd->tetherInterfaceList(&ifList);
1990 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1991 expectTetherInterfaceExists(ifList, sTun.name());
1992
1993 status = mNetd->tetherInterfaceRemove(sTun.name());
1994 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1995 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
1996
1997 status = mNetd->tetherInterfaceList(&ifList);
1998 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1999 expectTetherInterfaceNotExists(ifList, sTun.name());
2000}
2001
2002TEST_F(BinderTest, TetherDnsSetList) {
2003 // TODO: verify if dnsmasq update dns successfully
2004 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
2005
2006 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2007 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2008
2009 std::vector<std::string> dnsList;
2010 status = mNetd->tetherDnsList(&dnsList);
2011 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2012 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002013}
2014
2015namespace {
2016
2017constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2018constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2019constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2020constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2021constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2022constexpr char FIREWALL_STANDBY[] = "fw_standby";
2023constexpr char targetReturn[] = "RETURN";
2024constexpr char targetDrop[] = "DROP";
2025
2026void expectFirewallWhitelistMode() {
2027 static const char dropRule[] = "DROP all";
2028 static const char rejectRule[] = "REJECT all";
2029 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2030 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2031 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2032 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2033 }
2034}
2035
2036void expectFirewallBlacklistMode() {
2037 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2038 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2039 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2040 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2041 }
2042}
2043
2044bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2045 const std::string& expectedInterface,
2046 const std::string& expectedRule) {
2047 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2048 // Expected rule:
2049 // Chain fw_INPUT (1 references)
2050 // pkts bytes target prot opt in out source destination
2051 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2052 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2053 int firstRuleIndex = 2;
2054 if (rules.size() < 4) return false;
2055 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2056 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2057 return true;
2058 }
2059 }
2060 return false;
2061}
2062
2063// TODO: It is a duplicate function, need to remove it
2064bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2065 const std::string& expectedInterface,
2066 const std::string& expectedRule) {
2067 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2068 for (const auto& rule : rules) {
2069 if (rule.find(expectedInterface) != std::string::npos) {
2070 if (rule.find(expectedRule) != std::string::npos) {
2071 return true;
2072 }
2073 }
2074 }
2075 return false;
2076}
2077
2078void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2079 static const char returnRule[] = "RETURN all";
2080 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2081 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2082 returnRule));
2083 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2084 returnRule));
2085 }
2086}
2087
2088void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2089 static const char returnRule[] = "RETURN all";
2090 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2091 EXPECT_FALSE(
2092 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2093 EXPECT_FALSE(
2094 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2095 }
2096}
2097
2098bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2099 const std::string& expectedTarget,
2100 const std::string& expectedRule) {
2101 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2102 int firstRuleIndex = 2;
2103 if (rules.size() < 4) return false;
2104 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2105 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2106 return true;
2107 }
2108 }
2109 return false;
2110}
2111
2112bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2113 const std::string& expectedTarget,
2114 const std::string& expectedRule) {
2115 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2116 int lastRuleIndex = rules.size() - 1;
2117 if (lastRuleIndex < 0) return false;
2118 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2119 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2120 return true;
2121 }
2122 }
2123 return false;
2124}
2125
2126void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2127 std::string uidRule = StringPrintf("owner UID match %u", uid);
2128 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2129 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2130}
2131
2132void expectFirewallUidFirstRuleDoesNotExist(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_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2136}
2137
2138void expectFirewallUidLastRuleExists(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_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2142}
2143
2144void expectFirewallUidLastRuleDoesNotExist(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_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2148}
2149
2150bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2151 std::vector<std::string> inputRules =
2152 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2153 std::vector<std::string> outputRules =
2154 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2155 int inputLastRuleIndex = inputRules.size() - 1;
2156 int outputLastRuleIndex = outputRules.size() - 1;
2157
2158 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2159 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2160 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2161 return true;
2162 }
2163 }
2164 return false;
2165}
2166
2167void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2168 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2169 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2170}
2171
2172void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2173 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2174 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2175 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2176 }
2177}
2178
2179} // namespace
2180
2181TEST_F(BinderTest, FirewallSetFirewallType) {
2182 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2183 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2184 expectFirewallWhitelistMode();
2185
2186 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2187 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2188 expectFirewallBlacklistMode();
2189
2190 // set firewall type blacklist twice
2191 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2192 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2193 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2194 expectFirewallBlacklistMode();
2195
2196 // set firewall type whitelist twice
2197 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2198 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2199 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2200 expectFirewallWhitelistMode();
2201
2202 // reset firewall type to default
2203 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2204 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2205 expectFirewallBlacklistMode();
2206}
2207
2208TEST_F(BinderTest, FirewallSetInterfaceRule) {
2209 // setinterfaceRule is not supported in BLACKLIST MODE
2210 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2211 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2212
2213 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2214 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2215
2216 // set WHITELIST mode first
2217 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2218 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2219
2220 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2221 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2222 expectFirewallInterfaceRuleAllowExists(sTun.name());
2223
2224 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2225 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2226 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2227
2228 // reset firewall mode to default
2229 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2230 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2231 expectFirewallBlacklistMode();
2232}
2233
2234TEST_F(BinderTest, FirewallSetUidRule) {
2235 SKIP_IF_BPF_SUPPORTED;
2236
2237 int32_t uid = randomUid();
2238
2239 // Doze allow
2240 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2241 INetd::FIREWALL_RULE_ALLOW);
2242 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2243 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2244
2245 // Doze deny
2246 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2247 INetd::FIREWALL_RULE_DENY);
2248 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2249 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2250
2251 // Powersave allow
2252 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2253 INetd::FIREWALL_RULE_ALLOW);
2254 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2255 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2256
2257 // Powersave deny
2258 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2259 INetd::FIREWALL_RULE_DENY);
2260 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2261 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2262
2263 // Standby deny
2264 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2265 INetd::FIREWALL_RULE_DENY);
2266 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2267 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2268
2269 // Standby allow
2270 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2271 INetd::FIREWALL_RULE_ALLOW);
2272 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2273 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2274
2275 // None deny in BLACKLIST
2276 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2277 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2278 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2279 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2280
2281 // None allow in BLACKLIST
2282 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2283 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2284 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2285 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2286
2287 // set firewall type whitelist twice
2288 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2289 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2290 expectFirewallWhitelistMode();
2291
2292 // None allow in WHITELIST
2293 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2294 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2295 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2296 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2297
2298 // None deny in WHITELIST
2299 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2300 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2301 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2302 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2303
2304 // reset firewall mode to default
2305 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2306 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2307 expectFirewallBlacklistMode();
2308}
2309
2310TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2311 SKIP_IF_BPF_SUPPORTED;
2312
2313 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2314 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2315 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2316
2317 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2318 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2319 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2320
2321 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2322 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2323 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2324
2325 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2326 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2327 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2328
2329 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2330 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2331 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2332
2333 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2334 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2335 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2336}
Luke Huangf7782042018-08-08 13:13:04 +08002337
2338namespace {
2339
2340std::string hwAddrToStr(unsigned char* hwaddr) {
2341 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2342 hwaddr[4], hwaddr[5]);
2343}
2344
2345int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2346 int prefixLength = 0;
2347 uint32_t m = ntohl(mask);
2348 while (m & (1 << 31)) {
2349 prefixLength++;
2350 m = m << 1;
2351 }
2352 return prefixLength;
2353}
2354
2355std::string toStdString(const String16& s) {
2356 return std::string(String8(s.string()));
2357}
2358
2359android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2360 const auto& sys = sSyscalls.get();
2361 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2362 EXPECT_TRUE(isOk(fd.status()));
2363
2364 struct ifreq ifr = {};
2365 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2366
2367 return sys.ioctl(fd.value(), flag, &ifr);
2368}
2369
2370std::string getInterfaceHwAddr(const std::string& ifName) {
2371 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2372
2373 unsigned char hwaddr[ETH_ALEN] = {};
2374 if (isOk(res.status())) {
2375 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2376 }
2377
2378 return hwAddrToStr(hwaddr);
2379}
2380
2381int getInterfaceIPv4Prefix(const std::string& ifName) {
2382 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2383
2384 int prefixLength = 0;
2385 if (isOk(res.status())) {
2386 prefixLength = ipv4NetmaskToPrefixLength(
2387 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2388 }
2389
2390 return prefixLength;
2391}
2392
2393std::string getInterfaceIPv4Addr(const std::string& ifName) {
2394 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2395
2396 struct in_addr addr = {};
2397 if (isOk(res.status())) {
2398 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2399 }
2400
2401 return std::string(inet_ntoa(addr));
2402}
2403
2404std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2405 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2406
2407 unsigned flags = 0;
2408 if (isOk(res.status())) {
2409 flags = res.value().ifr_flags;
2410 }
2411
2412 std::vector<std::string> ifFlags;
2413 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2414 : toStdString(INetd::IF_STATE_DOWN()));
2415
2416 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2417 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2418 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2419 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2420 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2421
2422 return ifFlags;
2423}
2424
2425bool compareListInterface(const std::vector<std::string>& interfaceList) {
2426 const auto& res = InterfaceController::getIfaceNames();
2427 EXPECT_TRUE(isOk(res));
2428
2429 std::vector<std::string> resIfList;
2430 resIfList.reserve(res.value().size());
2431 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2432
2433 return resIfList == interfaceList;
2434}
2435
2436int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2437 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2438 return readIntFromPath(path);
2439}
2440
2441bool getInterfaceEnableIPv6(const std::string& ifName) {
2442 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2443
2444 int disableIPv6 = readIntFromPath(path);
2445 return !disableIPv6;
2446}
2447
2448int getInterfaceMtu(const std::string& ifName) {
2449 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2450 return readIntFromPath(path);
2451}
2452
2453void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2454 EXPECT_TRUE(compareListInterface(interfaceList));
2455}
2456
2457void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2458 const InterfaceConfigurationParcel& interfaceCfg) {
2459 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2460 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2461 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2462 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2463}
2464
2465void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2466 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2467 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2468
2469 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2470 for (const auto& flag : setCfg.flags) {
2471 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2472 }
2473}
2474
2475void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2476 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2477 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2478}
2479
2480void expectInterfaceNoAddr(const std::string& ifName) {
2481 // noAddr
2482 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2483 // noPrefix
2484 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2485}
2486
2487void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2488 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2489 EXPECT_EQ(enableIPv6, enable);
2490}
2491
2492void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2493 int mtuSize = getInterfaceMtu(ifName);
2494 EXPECT_EQ(mtu, mtuSize);
2495}
2496
2497InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2498 const std::string& addr, int prefixLength,
2499 const std::vector<std::string>& flags) {
2500 InterfaceConfigurationParcel cfg;
2501 cfg.ifName = ifName;
2502 cfg.hwAddr = "";
2503 cfg.ipv4Addr = addr;
2504 cfg.prefixLength = prefixLength;
2505 cfg.flags = flags;
2506 return cfg;
2507}
2508
2509void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2510 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2511 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2512
2513 for (const auto& flag : expectedFlags) {
2514 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2515 interfaceCfg.flags.end());
2516 }
2517
2518 for (const auto& flag : unexpectedFlags) {
2519 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2520 interfaceCfg.flags.end());
2521 }
2522}
2523
2524} // namespace
2525
2526TEST_F(BinderTest, InterfaceList) {
2527 std::vector<std::string> interfaceListResult;
2528
2529 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2530 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2531 expectInterfaceList(interfaceListResult);
2532}
2533
2534TEST_F(BinderTest, InterfaceGetCfg) {
2535 InterfaceConfigurationParcel interfaceCfgResult;
2536
2537 // Add test physical network
2538 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2539 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2540
2541 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2542 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2543 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2544 expectTunFlags(interfaceCfgResult);
2545
2546 // Remove test physical network
2547 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2548}
2549
2550TEST_F(BinderTest, InterfaceSetCfg) {
2551 const std::string testAddr = "192.0.2.3";
2552 const int testPrefixLength = 24;
2553 std::vector<std::string> upFlags = {"up"};
2554 std::vector<std::string> downFlags = {"down"};
2555
2556 // Add test physical network
2557 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2558 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2559
2560 // Set tun interface down.
2561 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2562 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2563 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2564 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2565
2566 // Set tun interface up again.
2567 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2568 status = mNetd->interfaceSetCfg(interfaceCfg);
2569 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2570 status = mNetd->interfaceClearAddrs(sTun.name());
2571 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2572
2573 // Remove test physical network
2574 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2575}
2576
2577TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2578 // enable
2579 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2580 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2581 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2582
2583 // disable
2584 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2585 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2586 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2587}
2588
2589TEST_F(BinderTest, InterfaceClearAddr) {
2590 const std::string testAddr = "192.0.2.3";
2591 const int testPrefixLength = 24;
2592 std::vector<std::string> noFlags{};
2593
2594 // Add test physical network
2595 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2596 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2597
2598 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2599 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2600 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2601 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2602
2603 status = mNetd->interfaceClearAddrs(sTun.name());
2604 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2605 expectInterfaceNoAddr(sTun.name());
2606
2607 // Remove test physical network
2608 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2609}
2610
2611TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2612 // Add test physical network
2613 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2614 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2615
2616 // disable
2617 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2618 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2619 expectInterfaceEnableIPv6(sTun.name(), false);
2620
2621 // enable
2622 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2623 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2624 expectInterfaceEnableIPv6(sTun.name(), true);
2625
2626 // Remove test physical network
2627 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2628}
2629
2630TEST_F(BinderTest, InterfaceSetMtu) {
2631 const int testMtu = 1200;
2632
2633 // Add test physical network
2634 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2635 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2636
2637 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2638 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2639 expectInterfaceMtu(sTun.name(), testMtu);
2640
2641 // Remove test physical network
2642 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2643}
Luke Huang19b49c52018-10-22 12:12:05 +09002644
2645namespace {
2646
2647constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2648constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002649constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002650constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2651
Luke Huangae038f82018-11-05 11:17:31 +09002652int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002653 return listIptablesRuleByTable(binary, table, chainName).size();
2654}
2655
2656bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2657 const std::vector<std::string>& targetVec) {
2658 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2659 if (targetVec.size() != rules.size() - 2) {
2660 return false;
2661 }
2662
2663 /*
Luke Huangae038f82018-11-05 11:17:31 +09002664 * Check that the rules match. Note that this function matches substrings, not entire rules,
2665 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002666 * Skip first two lines since rules start from third line.
2667 * Chain chainName (x references)
2668 * pkts bytes target prot opt in out source destination
2669 * ...
2670 */
2671 int rIndex = 2;
2672 for (const auto& target : targetVec) {
2673 if (rules[rIndex].find(target) == std::string::npos) {
2674 return false;
2675 }
2676 rIndex++;
2677 }
2678 return true;
2679}
2680
2681void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2682 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2683 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2684 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002685 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002686 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2687 "DROP"};
2688
2689 // V4
2690 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2691 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002692 EXPECT_TRUE(
2693 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002694 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2695
Luke Huangae038f82018-11-05 11:17:31 +09002696 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002697 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2698
2699 // V6
2700 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002701 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2702 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002703
2704 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2705 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2706 extIf));
2707 }
2708}
2709
2710void expectNatDisable() {
2711 // It is the default DROP rule with tethering disable.
2712 // Chain tetherctrl_FORWARD (1 references)
2713 // pkts bytes target prot opt in out source destination
2714 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2715 std::vector<std::string> forwardV4Match = {"DROP"};
2716 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2717
2718 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002719 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2720 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002721
Luke Huangae038f82018-11-05 11:17:31 +09002722 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2723 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002724
2725 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2726}
2727
2728} // namespace
2729
2730TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002731 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2732 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2733 expectNatEnable(sTun.name(), sTun2.name());
2734
2735 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2736 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2737 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002738}