blob: 689e2e60a32b6ce24fcfd30615de7e7f2966737d [file] [log] [blame]
Lorenzo Colitti89faa342016-02-26 11:38:47 +09001/*
2 * Copyright 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * binder_test.cpp - unit tests for netd binder RPCs.
17 */
18
Robin Leeb8087362016-03-30 18:43:08 +010019#include <cerrno>
20#include <cinttypes>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090021#include <cstdint>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090022#include <cstdio>
23#include <cstdlib>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090024#include <set>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090025#include <vector>
26
Lorenzo Colitti755faa92016-07-27 22:10:49 +090027#include <fcntl.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090028#include <ifaddrs.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090029#include <netdb.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090030#include <sys/socket.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090031#include <sys/types.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090032#include <netinet/in.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090033#include <linux/if.h>
34#include <linux/if_tun.h>
Ben Schwartze7601812017-04-28 16:38:29 -040035#include <openssl/base64.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090036
Erik Klinecc4f2732016-08-03 11:24:27 +090037#include <android-base/macros.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090038#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090039#include <android-base/strings.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070040#include <bpf/BpfUtils.h>
Robin Leeb8087362016-03-30 18:43:08 +010041#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090042#include <gtest/gtest.h>
43#include <logwrap/logwrap.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090044#include <netutils/ifc.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090045
Nathan Harold21299f72018-03-16 20:13:03 -070046#include "InterfaceController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090047#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090048#include "Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070049#include "XfrmController.h"
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090050#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090051#include "android/net/INetd.h"
Robin Leeb8087362016-03-30 18:43:08 +010052#include "android/net/UidRange.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090053#include "binder/IServiceManager.h"
Nathan Harold21299f72018-03-16 20:13:03 -070054#include "netdutils/Syscalls.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090055
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090056#define IP_PATH "/system/bin/ip"
57#define IP6TABLES_PATH "/system/bin/ip6tables"
58#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090059#define TUN_DEV "/dev/tun"
60
Lorenzo Colitti89faa342016-02-26 11:38:47 +090061using namespace android;
62using namespace android::base;
63using namespace android::binder;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090064using android::base::StartsWith;
Chenbo Feng837ddfc2018-05-08 13:45:08 -070065using android::bpf::hasBpfSupport;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090066using android::net::INetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090067using android::net::TunInterface;
Robin Leeb8087362016-03-30 18:43:08 +010068using android::net::UidRange;
Nathan Harold21299f72018-03-16 20:13:03 -070069using android::net::XfrmController;
70using android::netdutils::sSyscalls;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090071using android::os::PersistableBundle;
Robin Leeb8087362016-03-30 18:43:08 +010072
Chenbo Feng837ddfc2018-05-08 13:45:08 -070073#define SKIP_IF_BPF_SUPPORTED \
74 do { \
75 if (hasBpfSupport()) return; \
76 } while (0);
77
Robin Leeb8087362016-03-30 18:43:08 +010078static const char* IP_RULE_V4 = "-4";
79static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090080static const int TEST_NETID1 = 65501;
81static const int TEST_NETID2 = 65502;
82constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090083
Benedict Wongb2daefb2017-12-06 22:05:46 -080084static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
85static const std::string ESP_ALLOW_RULE("esp");
86
Lorenzo Colitti89faa342016-02-26 11:38:47 +090087class BinderTest : public ::testing::Test {
88
89public:
90 BinderTest() {
91 sp<IServiceManager> sm = defaultServiceManager();
92 sp<IBinder> binder = sm->getService(String16("netd"));
93 if (binder != nullptr) {
94 mNetd = interface_cast<INetd>(binder);
95 }
96 }
97
Lorenzo Colitti755faa92016-07-27 22:10:49 +090098 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +090099 ASSERT_NE(nullptr, mNetd.get());
100 }
101
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900102 void TearDown() override {
103 mNetd->networkDestroy(TEST_NETID1);
104 mNetd->networkDestroy(TEST_NETID2);
105 }
106
Nathan Harold21299f72018-03-16 20:13:03 -0700107 bool allocateIpSecResources(bool expectOk, int32_t *spi);
108
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900109 // Static because setting up the tun interface takes about 40ms.
110 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900111 ASSERT_EQ(0, sTun.init());
112 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900113 }
114
115 static void TearDownTestCase() {
116 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900117 sTun.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900118 }
119
120 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900121
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900122protected:
123 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900124 static TunInterface sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900125};
126
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900127TunInterface BinderTest::sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900128
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900129class TimedOperation : public Stopwatch {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900130public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700131 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900132 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900133 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900134 }
135
136private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900137 std::string mName;
138};
139
140TEST_F(BinderTest, TestIsAlive) {
141 TimedOperation t("isAlive RPC");
142 bool isAlive = false;
143 mNetd->isAlive(&isAlive);
144 ASSERT_TRUE(isAlive);
145}
146
147static int randomUid() {
148 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
149}
150
Robin Leeb8087362016-03-30 18:43:08 +0100151static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900152 std::vector<std::string> lines;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900153
Bernie Innocentif6918262018-06-11 17:37:35 +0900154 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
155 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900156 perror("popen");
157 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900158 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900159
160 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100161 size_t bufsize = 0;
162 ssize_t linelen = 0;
163 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900164 lines.push_back(std::string(line, linelen));
165 free(line);
166 line = nullptr;
167 }
168
169 pclose(f);
170 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900171}
172
Robin Leeb8087362016-03-30 18:43:08 +0100173static std::vector<std::string> listIpRules(const char *ipVersion) {
174 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
175 return runCommand(command);
176}
177
178static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900179 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100180 return runCommand(command);
181}
182
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900183static int iptablesRuleLineLength(const char *binary, const char *chainName) {
184 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900185}
186
Benedict Wongb2daefb2017-12-06 22:05:46 -0800187static bool iptablesRuleExists(const char *binary,
188 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900189 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800190 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900191 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800192 if(rule.find(expectedRule) != std::string::npos) {
193 return true;
194 }
195 }
196 return false;
197}
198
199static bool iptablesNoSocketAllowRuleExists(const char *chainName){
200 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
201 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
202}
203
204static bool iptablesEspAllowRuleExists(const char *chainName){
205 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
206 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
207}
208
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900209TEST_F(BinderTest, TestFirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700210 SKIP_IF_BPF_SUPPORTED;
211
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900212 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
213 const int kNumUids = 500;
214 std::vector<int32_t> noUids(0);
215 std::vector<int32_t> uids(kNumUids);
216 for (int i = 0; i < kNumUids; i++) {
217 uids[i] = randomUid();
218 }
219
220 bool ret;
221 {
222 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900223 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900224 }
225 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800226 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
227 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
228 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
229 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900230 {
231 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900232 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900233 }
234 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900235 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
236 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900237
238 {
239 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900240 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900241 }
242 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900243 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
244 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800245 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
246 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900247
248 {
249 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900250 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900251 }
252 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900253 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
254 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900255
256 // Check that the call fails if iptables returns an error.
257 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900258 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900259 EXPECT_EQ(false, ret);
260}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900261
manojboopathi8707f232018-01-02 14:45:47 -0800262TEST_F(BinderTest, TestVirtualTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700263 const struct TestData {
264 const std::string family;
265 const std::string deviceName;
266 const std::string localAddress;
267 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800268 int32_t iKey;
269 int32_t oKey;
270 } kTestData[] = {
Nathan Harold21299f72018-03-16 20:13:03 -0700271 {"IPV4", "test_vti", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53},
272 {"IPV6", "test_vti6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50},
manojboopathi8707f232018-01-02 14:45:47 -0800273 };
274
275 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700276 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800277
278 binder::Status status;
279
280 // Create Virtual Tunnel Interface.
Nathan Harold21299f72018-03-16 20:13:03 -0700281 status = mNetd->addVirtualTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
282 td.iKey, td.oKey);
manojboopathi8707f232018-01-02 14:45:47 -0800283 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
284
285 // Update Virtual Tunnel Interface.
286 status = mNetd->updateVirtualTunnelInterface(td.deviceName, td.localAddress,
287 td.remoteAddress, td.iKey, td.oKey);
288 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
289
290 // Remove Virtual Tunnel Interface.
291 status = mNetd->removeVirtualTunnelInterface(td.deviceName);
292 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
293 }
294}
295
Nathan Harold2deff322018-05-10 14:03:48 -0700296// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
297// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
298#if INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700299#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
300 do { if ((_expect_) != (_ret_)) return false; } while(false)
301bool BinderTest::allocateIpSecResources(bool expectOk, int32_t *spi) {
302 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
303 SCOPED_TRACE(status);
304 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
305
306 // Add a policy
307 status = XfrmController::ipSecAddSecurityPolicy(0, 0, "::", "::1", 123, 0, 0);
308 SCOPED_TRACE(status);
309 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
310
311 // Add an ipsec interface
312 status = netdutils::statusFromErrno(
313 XfrmController::addVirtualTunnelInterface(
314 "ipsec_test", "::", "::1", 0xF00D, 0xD00D, false),
315 "addVirtualTunnelInterface");
316 return (status.ok() == expectOk);
317}
318
Nathan Harold21299f72018-03-16 20:13:03 -0700319TEST_F(BinderTest, TestXfrmControllerInit) {
320 netdutils::Status status;
321 status = XfrmController::Init();
322 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700323
324 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
325 // feature.
326 if (status.code() == EOPNOTSUPP) return;
327
Nathan Harold21299f72018-03-16 20:13:03 -0700328 ASSERT_TRUE(status.ok());
329
330 int32_t spi = 0;
331
332 ASSERT_TRUE(allocateIpSecResources(true, &spi));
333 ASSERT_TRUE(allocateIpSecResources(false, &spi));
334
335 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700336 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700337 ASSERT_TRUE(allocateIpSecResources(true, &spi));
338
339 // Clean up
340 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0);
341 SCOPED_TRACE(status);
342 ASSERT_TRUE(status.ok());
343
344 status = XfrmController::ipSecDeleteSecurityPolicy(0, 0, "::", "::1", 0, 0);
345 SCOPED_TRACE(status);
346 ASSERT_TRUE(status.ok());
347
348 // Remove Virtual Tunnel Interface.
349 status = netdutils::statusFromErrno(
350 XfrmController::removeVirtualTunnelInterface("ipsec_test"),
351 "removeVirtualTunnelInterface");
352
353 ASSERT_TRUE(status.ok());
354}
Nathan Harold2deff322018-05-10 14:03:48 -0700355#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700356
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900357static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900358 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900359
360 // Output looks like this:
361 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900362 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900363 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900364 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900365 //
366 // or:
367 //
368 // Chain bw_data_saver (1 references)
369 // target prot opt source destination
370 // ... possibly connectivity critical packet rules here ...
371 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900372
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900373 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900374
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900375 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
376 // Data saver disabled.
377 return 0;
378 }
379
380 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
381
382 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
383 // Data saver enabled.
384 return 1;
385 }
386
387 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900388}
389
390bool enableDataSaver(sp<INetd>& netd, bool enable) {
391 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
392 bool ret;
393 netd->bandwidthEnableDataSaver(enable, &ret);
394 return ret;
395}
396
397int getDataSaverState() {
398 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
399 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
400 EXPECT_EQ(enabled4, enabled6);
401 EXPECT_NE(-1, enabled4);
402 EXPECT_NE(-1, enabled6);
403 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
404 return -1;
405 }
406 return enabled6;
407}
408
409TEST_F(BinderTest, TestBandwidthEnableDataSaver) {
410 const int wasEnabled = getDataSaverState();
411 ASSERT_NE(-1, wasEnabled);
412
413 if (wasEnabled) {
414 ASSERT_TRUE(enableDataSaver(mNetd, false));
415 EXPECT_EQ(0, getDataSaverState());
416 }
417
418 ASSERT_TRUE(enableDataSaver(mNetd, false));
419 EXPECT_EQ(0, getDataSaverState());
420
421 ASSERT_TRUE(enableDataSaver(mNetd, true));
422 EXPECT_EQ(1, getDataSaverState());
423
424 ASSERT_TRUE(enableDataSaver(mNetd, true));
425 EXPECT_EQ(1, getDataSaverState());
426
427 if (!wasEnabled) {
428 ASSERT_TRUE(enableDataSaver(mNetd, false));
429 EXPECT_EQ(0, getDataSaverState());
430 }
431}
Robin Leeb8087362016-03-30 18:43:08 +0100432
433static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
434 const std::string& action, const char* ipVersion) {
435 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100436 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100437 std::vector<std::string> rules = listIpRules(ipVersion);
438
439 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
440 std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
441 range.getStart(), range.getStop(), action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900442 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800443 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100444 return true;
445 }
446 }
447 return false;
448}
449
450static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
451 const std::string& action) {
452 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
453 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
454 EXPECT_EQ(existsIp4, existsIp6);
455 return existsIp4;
456}
457
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900458TEST_F(BinderTest, TestNetworkInterfaces) {
459 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, "").isOk());
460 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, "").serviceSpecificErrorCode());
461 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
462 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
463
464 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
465 EXPECT_EQ(EBUSY,
466 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
467
468 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
469 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
470 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
471}
472
473TEST_F(BinderTest, TestNetworkUidRules) {
474 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
475
476 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
477 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
478 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
479
480 std::vector<UidRange> uidRanges = {
481 {BASE_UID + 8005, BASE_UID + 8012},
482 {BASE_UID + 8090, BASE_UID + 8099}
483 };
484 UidRange otherRange(BASE_UID + 8190, BASE_UID + 8299);
485 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
486
487 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
488
489 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
490 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
491 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
492 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
493
494 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
495 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
496 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
497 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
498
499 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
500}
501
Robin Leeb8087362016-03-30 18:43:08 +0100502TEST_F(BinderTest, TestNetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100503 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100504
Robin Leeb8087362016-03-30 18:43:08 +0100505 std::vector<UidRange> uidRanges = {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900506 {BASE_UID + 150, BASE_UID + 224},
507 {BASE_UID + 226, BASE_UID + 300}
Robin Leeb8087362016-03-30 18:43:08 +0100508 };
509
510 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
511 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
512
513 // Create two valid rules.
514 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
515 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
516 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
517 for (auto const& range : uidRanges) {
518 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
519 }
520
521 // Remove the rules.
522 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
523 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
524 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
525 for (auto const& range : uidRanges) {
526 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
527 }
528
529 // Fail to remove the rules a second time after they are already deleted.
530 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
531 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
532 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
533
534 // All rules should be the same as before.
535 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
536 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
537}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900538
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900539// Create a socket pair that isLoopbackSocket won't think is local.
540void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900541 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900542 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900543 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
544
545 socklen_t addrlen = sizeof(server6);
546 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
547 ASSERT_EQ(0, listen(*serverSocket, 10));
548
Bernie Innocentif6918262018-06-11 17:37:35 +0900549 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900550 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900551 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900552 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
553 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
554
Bernie Innocentif6918262018-06-11 17:37:35 +0900555 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900556 ASSERT_NE(-1, *acceptedSocket);
557
558 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
559}
560
561void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
562 char buf[4096];
563 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
564 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
565 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
566}
567
568void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
569 // Check that the client socket was closed with ECONNABORTED.
570 int ret = write(clientSocket, "foo", sizeof("foo"));
571 int err = errno;
572 EXPECT_EQ(-1, ret);
573 EXPECT_EQ(ECONNABORTED, err);
574
575 // Check that it sent a RST to the server.
576 ret = write(acceptedSocket, "foo", sizeof("foo"));
577 err = errno;
578 EXPECT_EQ(-1, ret);
579 EXPECT_EQ(ECONNRESET, err);
580}
581
582TEST_F(BinderTest, TestSocketDestroy) {
583 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900584 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900585
586 // Pick a random UID in the system UID range.
587 constexpr int baseUid = AID_APP - 2000;
588 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
589 int uid = baseUid + 500 + arc4random_uniform(1000);
590 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
591
592 // UID ranges that don't contain uid.
593 std::vector<UidRange> uidRanges = {
594 {baseUid + 42, baseUid + 449},
595 {baseUid + 1536, AID_APP - 4},
596 {baseUid + 498, uid - 1},
597 {uid + 1, baseUid + 1520},
598 };
599 // A skip list that doesn't contain UID.
600 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
601
602 // Close sockets. Our test socket should be intact.
603 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
604 checkSocketpairOpen(clientSocket, acceptedSocket);
605
606 // UID ranges that do contain uid.
607 uidRanges = {
608 {baseUid + 42, baseUid + 449},
609 {baseUid + 1536, AID_APP - 4},
610 {baseUid + 498, baseUid + 1520},
611 };
612 // Add uid to the skip list.
613 skipUids.push_back(uid);
614
615 // Close sockets. Our test socket should still be intact because it's in the skip list.
616 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
617 checkSocketpairOpen(clientSocket, acceptedSocket);
618
619 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
620 skipUids.resize(skipUids.size() - 1);
621 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
622 checkSocketpairClosed(clientSocket, acceptedSocket);
623
624 close(clientSocket);
625 close(serverSocket);
626 close(acceptedSocket);
627}
Erik Klinecc4f2732016-08-03 11:24:27 +0900628
629namespace {
630
631int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
632 if (buf == nullptr) return -1;
633
634 int prefixLength = 0;
635 bool endOfContiguousBits = false;
636 for (unsigned int i = 0; i < buflen; i++) {
637 const uint8_t value = buf[i];
638
639 // Bad bit sequence: check for a contiguous set of bits from the high
640 // end by verifying that the inverted value + 1 is a power of 2
641 // (power of 2 iff. (v & (v - 1)) == 0).
642 const uint8_t inverse = ~value + 1;
643 if ((inverse & (inverse - 1)) != 0) return -1;
644
645 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
646
647 // Bogus netmask.
648 if (endOfContiguousBits && value != 0) return -1;
649
650 if (value != 0xff) endOfContiguousBits = true;
651 }
652
653 return prefixLength;
654}
655
656template<typename T>
657int netmaskToPrefixLength(const T *p) {
658 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
659}
660
661
662static bool interfaceHasAddress(
663 const std::string &ifname, const char *addrString, int prefixLength) {
664 struct addrinfo *addrinfoList = nullptr;
665 ScopedAddrinfo addrinfoCleanup(addrinfoList);
666
667 const struct addrinfo hints = {
668 .ai_flags = AI_NUMERICHOST,
669 .ai_family = AF_UNSPEC,
670 .ai_socktype = SOCK_DGRAM,
671 };
672 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
673 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
674 return false;
675 }
676
677 struct ifaddrs *ifaddrsList = nullptr;
678 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
679
680 if (getifaddrs(&ifaddrsList) != 0) {
681 return false;
682 }
683
684 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
685 if (std::string(addr->ifa_name) != ifname ||
686 addr->ifa_addr == nullptr ||
687 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
688 continue;
689 }
690
691 switch (addr->ifa_addr->sa_family) {
692 case AF_INET: {
693 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
694 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
695 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
696 continue;
697 }
698
699 if (prefixLength < 0) return true; // not checking prefix lengths
700
701 if (addr->ifa_netmask == nullptr) return false;
702 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
703 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
704 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
705 }
706 case AF_INET6: {
707 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
708 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
709 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
710 continue;
711 }
712
713 if (prefixLength < 0) return true; // not checking prefix lengths
714
715 if (addr->ifa_netmask == nullptr) return false;
716 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
717 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
718 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
719 }
720 default:
721 // Cannot happen because we have already screened for matching
722 // address families at the top of each iteration.
723 continue;
724 }
725 }
726
727 return false;
728}
729
730} // namespace
731
732TEST_F(BinderTest, TestInterfaceAddRemoveAddress) {
733 static const struct TestData {
734 const char *addrString;
735 const int prefixLength;
736 const bool expectSuccess;
737 } kTestData[] = {
738 { "192.0.2.1", 24, true },
739 { "192.0.2.2", 25, true },
740 { "192.0.2.3", 32, true },
741 { "192.0.2.4", 33, false },
742 { "192.not.an.ip", 24, false },
743 { "2001:db8::1", 64, true },
744 { "2001:db8::2", 65, true },
745 { "2001:db8::3", 128, true },
746 { "2001:db8::4", 129, false },
747 { "foo:bar::bad", 64, false },
748 };
749
750 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
751 const auto &td = kTestData[i];
752
753 // [1.a] Add the address.
754 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900755 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900756 if (td.expectSuccess) {
757 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
758 } else {
759 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
760 ASSERT_NE(0, status.serviceSpecificErrorCode());
761 }
762
763 // [1.b] Verify the addition meets the expectation.
764 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900765 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900766 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900767 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900768 }
769
770 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900771 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900772 if (td.expectSuccess) {
773 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
774 } else {
775 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
776 ASSERT_NE(0, status.serviceSpecificErrorCode());
777 }
778
779 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900780 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900781 }
782}
Erik Kline55b06f82016-07-04 09:57:18 +0900783
784TEST_F(BinderTest, TestSetProcSysNet) {
785 static const struct TestData {
786 const int family;
787 const int which;
788 const char *ifname;
789 const char *parameter;
790 const char *value;
791 const int expectedReturnCode;
792 } kTestData[] = {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900793 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0 },
794 { -1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT },
795 { INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL },
Erik Kline55b06f82016-07-04 09:57:18 +0900796 { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
797 { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900798 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL },
799 { INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0 },
Erik Kline55b06f82016-07-04 09:57:18 +0900800 };
801
802 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
803 const auto &td = kTestData[i];
804
805 const binder::Status status = mNetd->setProcSysNet(
806 td.family, td.which, td.ifname, td.parameter,
807 td.value);
808
809 if (td.expectedReturnCode == 0) {
810 SCOPED_TRACE(String8::format("test case %d should have passed", i));
811 EXPECT_EQ(0, status.exceptionCode());
812 EXPECT_EQ(0, status.serviceSpecificErrorCode());
813 } else {
814 SCOPED_TRACE(String8::format("test case %d should have failed", i));
815 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
816 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
817 }
818 }
819}
Ben Schwartze7601812017-04-28 16:38:29 -0400820
821static std::string base64Encode(const std::vector<uint8_t>& input) {
822 size_t out_len;
823 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
824 // out_len includes the trailing NULL.
825 uint8_t output_bytes[out_len];
826 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
827 return std::string(reinterpret_cast<char*>(output_bytes));
828}
829
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400830TEST_F(BinderTest, TestSetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900831 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400832 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400833 std::vector<uint8_t> short_fp(1);
834 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
835 std::vector<std::string> test_domains;
836 std::vector<int> test_params = { 300, 25, 8, 8 };
837 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400838 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400839 const std::vector<std::string> servers;
840 const std::string tlsName;
841 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400842 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900843 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400844 { {"192.0.2.1"}, "", {}, 0 },
845 { {"2001:db8::2"}, "host.name", {}, 0 },
846 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
847 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900848 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400849 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900850 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400851 { {"2001:dg8::6"}, "", {}, EINVAL },
852 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
853 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
854 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
855 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400856 };
857
Erik Klinea1476fb2018-03-04 21:01:56 +0900858 for (unsigned int i = 0; i < arraysize(kTlsTestData); i++) {
859 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -0400860
861 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400862 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400863 fingerprints.push_back(base64Encode(fingerprint));
864 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400865 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900866 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
867 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -0400868
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400869 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -0400870 SCOPED_TRACE(String8::format("test case %d should have passed", i));
871 SCOPED_TRACE(status.toString8());
872 EXPECT_EQ(0, status.exceptionCode());
873 } else {
874 SCOPED_TRACE(String8::format("test case %d should have failed", i));
875 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400876 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -0400877 }
Ben Schwartze7601812017-04-28 16:38:29 -0400878 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400879 // Ensure TLS is disabled before the start of the next test.
880 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900881 test_netid, kTlsTestData[0].servers, test_domains, test_params,
882 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -0400883}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900884
885void expectNoTestCounterRules() {
886 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
887 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
888 std::string allRules = Join(runCommand(command), "\n");
889 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
890 }
891}
892
Bernie Innocentif6918262018-06-11 17:37:35 +0900893void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
894 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900895 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
896 path, if1.c_str(), if2.c_str(), pkt, byte));
897}
898
Bernie Innocentif6918262018-06-11 17:37:35 +0900899void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900900 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
901 path, if1.c_str(), if2.c_str()));
902 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
903 path, if2.c_str(), if1.c_str()));
904}
905
906TEST_F(BinderTest, TestTetherGetStats) {
907 expectNoTestCounterRules();
908
909 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
910 // disabling tethering. We don't check the return value because these commands will fail if
911 // tethering is already enabled.
912 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
913 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
914
915 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
916 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
917 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
918 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
919 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
920
921 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
922 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
923 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
924 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
925 // RX is from external to internal, and TX is from internal to external.
926 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
927 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
928
929 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
930 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
931
932 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
933 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
934
935 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
936 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
937 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
938
939 PersistableBundle stats;
940 binder::Status status = mNetd->tetherGetStats(&stats);
941 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
942
943 std::vector<int64_t> actual1;
944 EXPECT_TRUE(stats.getLongVector(String16(extIface1.c_str()), &actual1));
945 EXPECT_EQ(expected1, actual1);
946
947 std::vector<int64_t> actual2;
948 EXPECT_TRUE(stats.getLongVector(String16(extIface2.c_str()), &actual2));
949 EXPECT_EQ(expected2, actual2);
950
951 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
952 delTetherCounterValues(path, intIface1, extIface1);
953 delTetherCounterValues(path, intIface2, extIface2);
954 if (path == IP6TABLES_PATH) {
955 delTetherCounterValues(path, intIface3, extIface2);
956 }
957 }
958
959 expectNoTestCounterRules();
960}