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