blob: b2f362eee92679fd2f461fce693cc9d5ce737974 [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>
Robin Leeb8087362016-03-30 18:43:08 +010040#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090041#include <gtest/gtest.h>
42#include <logwrap/logwrap.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090043#include <netutils/ifc.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090044
45#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090046#include "Stopwatch.h"
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090047#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090048#include "android/net/INetd.h"
Robin Leeb8087362016-03-30 18:43:08 +010049#include "android/net/UidRange.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090050#include "binder/IServiceManager.h"
51
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090052#define IP_PATH "/system/bin/ip"
53#define IP6TABLES_PATH "/system/bin/ip6tables"
54#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090055#define TUN_DEV "/dev/tun"
56
Lorenzo Colitti89faa342016-02-26 11:38:47 +090057using namespace android;
58using namespace android::base;
59using namespace android::binder;
60using android::net::INetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090061using android::net::TunInterface;
Robin Leeb8087362016-03-30 18:43:08 +010062using android::net::UidRange;
63
64static const char* IP_RULE_V4 = "-4";
65static const char* IP_RULE_V6 = "-6";
Lorenzo Colitti89faa342016-02-26 11:38:47 +090066
67class BinderTest : public ::testing::Test {
68
69public:
70 BinderTest() {
71 sp<IServiceManager> sm = defaultServiceManager();
72 sp<IBinder> binder = sm->getService(String16("netd"));
73 if (binder != nullptr) {
74 mNetd = interface_cast<INetd>(binder);
75 }
76 }
77
Lorenzo Colitti755faa92016-07-27 22:10:49 +090078 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +090079 ASSERT_NE(nullptr, mNetd.get());
80 }
81
Lorenzo Colitti755faa92016-07-27 22:10:49 +090082 // Static because setting up the tun interface takes about 40ms.
83 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090084 ASSERT_EQ(0, sTun.init());
85 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +090086 }
87
88 static void TearDownTestCase() {
89 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090090 sTun.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +090091 }
92
93 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +090094
Lorenzo Colitti89faa342016-02-26 11:38:47 +090095protected:
96 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090097 static TunInterface sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090098};
99
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900100TunInterface BinderTest::sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900101
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900102class TimedOperation : public Stopwatch {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900103public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700104 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900105 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900106 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900107 }
108
109private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900110 std::string mName;
111};
112
113TEST_F(BinderTest, TestIsAlive) {
114 TimedOperation t("isAlive RPC");
115 bool isAlive = false;
116 mNetd->isAlive(&isAlive);
117 ASSERT_TRUE(isAlive);
118}
119
120static int randomUid() {
121 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
122}
123
Robin Leeb8087362016-03-30 18:43:08 +0100124static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900125 std::vector<std::string> lines;
126 FILE *f;
127
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900128 if ((f = popen(command.c_str(), "r")) == nullptr) {
129 perror("popen");
130 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900131 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900132
133 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100134 size_t bufsize = 0;
135 ssize_t linelen = 0;
136 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900137 lines.push_back(std::string(line, linelen));
138 free(line);
139 line = nullptr;
140 }
141
142 pclose(f);
143 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900144}
145
Robin Leeb8087362016-03-30 18:43:08 +0100146static std::vector<std::string> listIpRules(const char *ipVersion) {
147 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
148 return runCommand(command);
149}
150
151static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900152 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100153 return runCommand(command);
154}
155
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900156static int iptablesRuleLineLength(const char *binary, const char *chainName) {
157 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900158}
159
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900160TEST_F(BinderTest, TestFirewallReplaceUidChain) {
161 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
162 const int kNumUids = 500;
163 std::vector<int32_t> noUids(0);
164 std::vector<int32_t> uids(kNumUids);
165 for (int i = 0; i < kNumUids; i++) {
166 uids[i] = randomUid();
167 }
168
169 bool ret;
170 {
171 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
172 mNetd->firewallReplaceUidChain(String16(chainName.c_str()), true, uids, &ret);
173 }
174 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900175 EXPECT_EQ((int) uids.size() + 7, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
176 EXPECT_EQ((int) uids.size() + 13, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900177 {
178 TimedOperation op("Clearing whitelist chain");
179 mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, noUids, &ret);
180 }
181 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900182 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
183 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900184
185 {
186 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
187 mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, uids, &ret);
188 }
189 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900190 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
191 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900192
193 {
194 TimedOperation op("Clearing blacklist chain");
195 mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, noUids, &ret);
196 }
197 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900198 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
199 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900200
201 // Check that the call fails if iptables returns an error.
202 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
203 mNetd->firewallReplaceUidChain(String16(veryLongStringName.c_str()), true, noUids, &ret);
204 EXPECT_EQ(false, ret);
205}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900206
207static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900208 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900209
210 // Output looks like this:
211 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900212 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900213 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900214 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900215 EXPECT_EQ(3U, lines.size());
216 if (lines.size() != 3) return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900217
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900218 EXPECT_TRUE(android::base::StartsWith(lines[2], "RETURN ") ||
219 android::base::StartsWith(lines[2], "REJECT "));
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900220
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900221 return android::base::StartsWith(lines[2], "REJECT");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900222}
223
224bool enableDataSaver(sp<INetd>& netd, bool enable) {
225 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
226 bool ret;
227 netd->bandwidthEnableDataSaver(enable, &ret);
228 return ret;
229}
230
231int getDataSaverState() {
232 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
233 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
234 EXPECT_EQ(enabled4, enabled6);
235 EXPECT_NE(-1, enabled4);
236 EXPECT_NE(-1, enabled6);
237 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
238 return -1;
239 }
240 return enabled6;
241}
242
243TEST_F(BinderTest, TestBandwidthEnableDataSaver) {
244 const int wasEnabled = getDataSaverState();
245 ASSERT_NE(-1, wasEnabled);
246
247 if (wasEnabled) {
248 ASSERT_TRUE(enableDataSaver(mNetd, false));
249 EXPECT_EQ(0, getDataSaverState());
250 }
251
252 ASSERT_TRUE(enableDataSaver(mNetd, false));
253 EXPECT_EQ(0, getDataSaverState());
254
255 ASSERT_TRUE(enableDataSaver(mNetd, true));
256 EXPECT_EQ(1, getDataSaverState());
257
258 ASSERT_TRUE(enableDataSaver(mNetd, true));
259 EXPECT_EQ(1, getDataSaverState());
260
261 if (!wasEnabled) {
262 ASSERT_TRUE(enableDataSaver(mNetd, false));
263 EXPECT_EQ(0, getDataSaverState());
264 }
265}
Robin Leeb8087362016-03-30 18:43:08 +0100266
267static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
268 const std::string& action, const char* ipVersion) {
269 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100270 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100271 std::vector<std::string> rules = listIpRules(ipVersion);
272
273 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
274 std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
275 range.getStart(), range.getStop(), action.c_str());
276 for (std::string line : rules) {
277 if (android::base::StartsWith(line, prefix.c_str())
278 && android::base::EndsWith(line, suffix.c_str())) {
279 return true;
280 }
281 }
282 return false;
283}
284
285static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
286 const std::string& action) {
287 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
288 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
289 EXPECT_EQ(existsIp4, existsIp6);
290 return existsIp4;
291}
292
293TEST_F(BinderTest, TestNetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100294 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100295
Jeff Sharkeyfe3cbd62016-12-13 13:26:47 -0700296 constexpr int baseUid = AID_USER_OFFSET * 5;
Robin Leeb8087362016-03-30 18:43:08 +0100297 std::vector<UidRange> uidRanges = {
298 {baseUid + 150, baseUid + 224},
299 {baseUid + 226, baseUid + 300}
300 };
301
302 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
303 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
304
305 // Create two valid rules.
306 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
307 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
308 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
309 for (auto const& range : uidRanges) {
310 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
311 }
312
313 // Remove the rules.
314 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
315 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
316 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
317 for (auto const& range : uidRanges) {
318 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
319 }
320
321 // Fail to remove the rules a second time after they are already deleted.
322 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
323 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
324 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
325
326 // All rules should be the same as before.
327 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
328 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
329}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900330
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900331// Create a socket pair that isLoopbackSocket won't think is local.
332void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900333 *serverSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900334 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900335 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
336
337 socklen_t addrlen = sizeof(server6);
338 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
339 ASSERT_EQ(0, listen(*serverSocket, 10));
340
341 *clientSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900342 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900343 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900344 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
345 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
346
347 *acceptedSocket = accept(*serverSocket, (struct sockaddr *) &server6, &addrlen);
348 ASSERT_NE(-1, *acceptedSocket);
349
350 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
351}
352
353void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
354 char buf[4096];
355 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
356 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
357 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
358}
359
360void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
361 // Check that the client socket was closed with ECONNABORTED.
362 int ret = write(clientSocket, "foo", sizeof("foo"));
363 int err = errno;
364 EXPECT_EQ(-1, ret);
365 EXPECT_EQ(ECONNABORTED, err);
366
367 // Check that it sent a RST to the server.
368 ret = write(acceptedSocket, "foo", sizeof("foo"));
369 err = errno;
370 EXPECT_EQ(-1, ret);
371 EXPECT_EQ(ECONNRESET, err);
372}
373
374TEST_F(BinderTest, TestSocketDestroy) {
375 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900376 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900377
378 // Pick a random UID in the system UID range.
379 constexpr int baseUid = AID_APP - 2000;
380 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
381 int uid = baseUid + 500 + arc4random_uniform(1000);
382 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
383
384 // UID ranges that don't contain uid.
385 std::vector<UidRange> uidRanges = {
386 {baseUid + 42, baseUid + 449},
387 {baseUid + 1536, AID_APP - 4},
388 {baseUid + 498, uid - 1},
389 {uid + 1, baseUid + 1520},
390 };
391 // A skip list that doesn't contain UID.
392 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
393
394 // Close sockets. Our test socket should be intact.
395 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
396 checkSocketpairOpen(clientSocket, acceptedSocket);
397
398 // UID ranges that do contain uid.
399 uidRanges = {
400 {baseUid + 42, baseUid + 449},
401 {baseUid + 1536, AID_APP - 4},
402 {baseUid + 498, baseUid + 1520},
403 };
404 // Add uid to the skip list.
405 skipUids.push_back(uid);
406
407 // Close sockets. Our test socket should still be intact because it's in the skip list.
408 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
409 checkSocketpairOpen(clientSocket, acceptedSocket);
410
411 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
412 skipUids.resize(skipUids.size() - 1);
413 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
414 checkSocketpairClosed(clientSocket, acceptedSocket);
415
416 close(clientSocket);
417 close(serverSocket);
418 close(acceptedSocket);
419}
Erik Klinecc4f2732016-08-03 11:24:27 +0900420
421namespace {
422
423int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
424 if (buf == nullptr) return -1;
425
426 int prefixLength = 0;
427 bool endOfContiguousBits = false;
428 for (unsigned int i = 0; i < buflen; i++) {
429 const uint8_t value = buf[i];
430
431 // Bad bit sequence: check for a contiguous set of bits from the high
432 // end by verifying that the inverted value + 1 is a power of 2
433 // (power of 2 iff. (v & (v - 1)) == 0).
434 const uint8_t inverse = ~value + 1;
435 if ((inverse & (inverse - 1)) != 0) return -1;
436
437 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
438
439 // Bogus netmask.
440 if (endOfContiguousBits && value != 0) return -1;
441
442 if (value != 0xff) endOfContiguousBits = true;
443 }
444
445 return prefixLength;
446}
447
448template<typename T>
449int netmaskToPrefixLength(const T *p) {
450 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
451}
452
453
454static bool interfaceHasAddress(
455 const std::string &ifname, const char *addrString, int prefixLength) {
456 struct addrinfo *addrinfoList = nullptr;
457 ScopedAddrinfo addrinfoCleanup(addrinfoList);
458
459 const struct addrinfo hints = {
460 .ai_flags = AI_NUMERICHOST,
461 .ai_family = AF_UNSPEC,
462 .ai_socktype = SOCK_DGRAM,
463 };
464 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
465 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
466 return false;
467 }
468
469 struct ifaddrs *ifaddrsList = nullptr;
470 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
471
472 if (getifaddrs(&ifaddrsList) != 0) {
473 return false;
474 }
475
476 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
477 if (std::string(addr->ifa_name) != ifname ||
478 addr->ifa_addr == nullptr ||
479 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
480 continue;
481 }
482
483 switch (addr->ifa_addr->sa_family) {
484 case AF_INET: {
485 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
486 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
487 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
488 continue;
489 }
490
491 if (prefixLength < 0) return true; // not checking prefix lengths
492
493 if (addr->ifa_netmask == nullptr) return false;
494 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
495 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
496 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
497 }
498 case AF_INET6: {
499 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
500 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
501 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
502 continue;
503 }
504
505 if (prefixLength < 0) return true; // not checking prefix lengths
506
507 if (addr->ifa_netmask == nullptr) return false;
508 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
509 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
510 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
511 }
512 default:
513 // Cannot happen because we have already screened for matching
514 // address families at the top of each iteration.
515 continue;
516 }
517 }
518
519 return false;
520}
521
522} // namespace
523
524TEST_F(BinderTest, TestInterfaceAddRemoveAddress) {
525 static const struct TestData {
526 const char *addrString;
527 const int prefixLength;
528 const bool expectSuccess;
529 } kTestData[] = {
530 { "192.0.2.1", 24, true },
531 { "192.0.2.2", 25, true },
532 { "192.0.2.3", 32, true },
533 { "192.0.2.4", 33, false },
534 { "192.not.an.ip", 24, false },
535 { "2001:db8::1", 64, true },
536 { "2001:db8::2", 65, true },
537 { "2001:db8::3", 128, true },
538 { "2001:db8::4", 129, false },
539 { "foo:bar::bad", 64, false },
540 };
541
542 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
543 const auto &td = kTestData[i];
544
545 // [1.a] Add the address.
546 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900547 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900548 if (td.expectSuccess) {
549 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
550 } else {
551 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
552 ASSERT_NE(0, status.serviceSpecificErrorCode());
553 }
554
555 // [1.b] Verify the addition meets the expectation.
556 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900557 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900558 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900559 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900560 }
561
562 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900563 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900564 if (td.expectSuccess) {
565 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
566 } else {
567 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
568 ASSERT_NE(0, status.serviceSpecificErrorCode());
569 }
570
571 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900572 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900573 }
574}
Erik Kline55b06f82016-07-04 09:57:18 +0900575
576TEST_F(BinderTest, TestSetProcSysNet) {
577 static const struct TestData {
578 const int family;
579 const int which;
580 const char *ifname;
581 const char *parameter;
582 const char *value;
583 const int expectedReturnCode;
584 } kTestData[] = {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900585 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0 },
586 { -1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT },
587 { INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL },
Erik Kline55b06f82016-07-04 09:57:18 +0900588 { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
589 { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900590 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL },
591 { INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0 },
Erik Kline55b06f82016-07-04 09:57:18 +0900592 };
593
594 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
595 const auto &td = kTestData[i];
596
597 const binder::Status status = mNetd->setProcSysNet(
598 td.family, td.which, td.ifname, td.parameter,
599 td.value);
600
601 if (td.expectedReturnCode == 0) {
602 SCOPED_TRACE(String8::format("test case %d should have passed", i));
603 EXPECT_EQ(0, status.exceptionCode());
604 EXPECT_EQ(0, status.serviceSpecificErrorCode());
605 } else {
606 SCOPED_TRACE(String8::format("test case %d should have failed", i));
607 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
608 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
609 }
610 }
611}
Ben Schwartze7601812017-04-28 16:38:29 -0400612
613static std::string base64Encode(const std::vector<uint8_t>& input) {
614 size_t out_len;
615 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
616 // out_len includes the trailing NULL.
617 uint8_t output_bytes[out_len];
618 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
619 return std::string(reinterpret_cast<char*>(output_bytes));
620}
621
622TEST_F(BinderTest, TestAddPrivateDnsServer) {
623 std::vector<uint8_t> fp(SHA256_SIZE);
624 static const struct TestData {
625 const std::string address;
626 const int port;
627 const std::string fingerprintAlgorithm;
628 const std::set<std::vector<uint8_t>> fingerprints;
629 const int expectedReturnCode;
630 } kTestData[] = {
631 { "192.0.2.1", 853, "", {}, INetd::PRIVATE_DNS_SUCCESS },
632 { "2001:db8::2", 65535, "", {}, INetd::PRIVATE_DNS_SUCCESS },
633 { "192.0.2.3", 443, "SHA-256", { fp }, INetd::PRIVATE_DNS_SUCCESS },
634 { "2001:db8::4", 1, "SHA-256", { fp }, INetd::PRIVATE_DNS_SUCCESS },
635 { "192.0.*.5", 853, "", {}, INetd::PRIVATE_DNS_BAD_ADDRESS },
636 { "", 853, "", {}, INetd::PRIVATE_DNS_BAD_ADDRESS },
637 { "2001:dg8::6", 65535, "", {}, INetd::PRIVATE_DNS_BAD_ADDRESS },
638 { "192.0.2.7", 0, "SHA-256", { fp }, INetd::PRIVATE_DNS_BAD_PORT },
639 { "2001:db8::8", 65536, "", {}, INetd::PRIVATE_DNS_BAD_PORT },
640 { "192.0.2.9", 50053, "SHA-512", { fp }, INetd::PRIVATE_DNS_UNKNOWN_ALGORITHM },
641 { "2001:db8::a", 853, "", { fp }, INetd::PRIVATE_DNS_BAD_FINGERPRINT },
642 { "192.0.2.11", 853, "SHA-256", {}, INetd::PRIVATE_DNS_BAD_FINGERPRINT },
643 { "2001:db8::c", 853, "SHA-256", { { 1 } }, INetd::PRIVATE_DNS_BAD_FINGERPRINT },
644 { "192.0.2.12", 853, "SHA-256", { std::vector<uint8_t>(SHA256_SIZE + 1) },
645 INetd::PRIVATE_DNS_BAD_FINGERPRINT },
646 { "2001:db8::e", 1, "SHA-256", { fp, fp, fp }, INetd::PRIVATE_DNS_SUCCESS },
647 { "192.0.2.14", 853, "SHA-256", { fp, { 1 } }, INetd::PRIVATE_DNS_BAD_FINGERPRINT },
648 };
649
650 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
651 const auto &td = kTestData[i];
652
653 std::vector<std::string> fingerprints;
654 for (const std::vector<uint8_t>& fingerprint : td.fingerprints) {
655 fingerprints.push_back(base64Encode(fingerprint));
656 }
657 const binder::Status status = mNetd->addPrivateDnsServer(
658 td.address, td.port, td.fingerprintAlgorithm, fingerprints);
659
660 if (td.expectedReturnCode == INetd::PRIVATE_DNS_SUCCESS) {
661 SCOPED_TRACE(String8::format("test case %d should have passed", i));
662 SCOPED_TRACE(status.toString8());
663 EXPECT_EQ(0, status.exceptionCode());
664 } else {
665 SCOPED_TRACE(String8::format("test case %d should have failed", i));
666 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
667 }
668 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
669 }
670}
671
672TEST_F(BinderTest, TestRemovePrivateDnsServer) {
673 static const struct TestData {
674 const std::string address;
675 const int expectedReturnCode;
676 } kTestData[] = {
677 { "192.0.2.1", INetd::PRIVATE_DNS_SUCCESS },
678 { "2001:db8::2", INetd::PRIVATE_DNS_SUCCESS },
679 { "192.0.*.3", INetd::PRIVATE_DNS_BAD_ADDRESS },
680 { "2001:dg8::4", INetd::PRIVATE_DNS_BAD_ADDRESS },
681 { "", INetd::PRIVATE_DNS_BAD_ADDRESS },
682 };
683
684 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
685 const auto &td = kTestData[i];
686
687 const binder::Status status = mNetd->removePrivateDnsServer(td.address);
688
689 if (td.expectedReturnCode == INetd::PRIVATE_DNS_SUCCESS) {
690 SCOPED_TRACE(String8::format("test case %d should have passed", i));
691 EXPECT_EQ(0, status.exceptionCode());
692 } else {
693 SCOPED_TRACE(String8::format("test case %d should have failed", i));
694 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
695 }
696 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
697 }
698}