blob: 041053205e88261923a327d18fa849ae700c6103 [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"
Luke Huang0051a622018-07-23 20:30:16 +080060#define RAW_TABLE "raw"
61#define MANGLE_TABLE "mangle"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090062
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090063namespace binder = android::binder;
64namespace netdutils = android::netdutils;
65
66using android::IBinder;
67using android::IServiceManager;
68using android::sp;
69using android::String16;
70using android::String8;
71using android::base::Join;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090072using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090073using android::base::StringPrintf;
Chenbo Feng837ddfc2018-05-08 13:45:08 -070074using android::bpf::hasBpfSupport;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090075using android::net::INetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090076using android::net::TunInterface;
Robin Leeb8087362016-03-30 18:43:08 +010077using android::net::UidRange;
Nathan Harold21299f72018-03-16 20:13:03 -070078using android::net::XfrmController;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090079using android::os::PersistableBundle;
Robin Leeb8087362016-03-30 18:43:08 +010080
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090081#define SKIP_IF_BPF_SUPPORTED \
82 do { \
83 if (hasBpfSupport()) return; \
84 } while (0)
Chenbo Feng837ddfc2018-05-08 13:45:08 -070085
Robin Leeb8087362016-03-30 18:43:08 +010086static const char* IP_RULE_V4 = "-4";
87static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090088static const int TEST_NETID1 = 65501;
89static const int TEST_NETID2 = 65502;
90constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090091
Benedict Wongb2daefb2017-12-06 22:05:46 -080092static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
93static const std::string ESP_ALLOW_RULE("esp");
94
Lorenzo Colitti89faa342016-02-26 11:38:47 +090095class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090096 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +090097 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090098 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +090099 sp<IBinder> binder = sm->getService(String16("netd"));
100 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900101 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900102 }
103 }
104
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900105 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900106 ASSERT_NE(nullptr, mNetd.get());
107 }
108
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900109 void TearDown() override {
110 mNetd->networkDestroy(TEST_NETID1);
111 mNetd->networkDestroy(TEST_NETID2);
112 }
113
Nathan Harold21299f72018-03-16 20:13:03 -0700114 bool allocateIpSecResources(bool expectOk, int32_t *spi);
115
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900116 // Static because setting up the tun interface takes about 40ms.
117 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900118 ASSERT_EQ(0, sTun.init());
119 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900120 }
121
122 static void TearDownTestCase() {
123 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900124 sTun.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900125 }
126
127 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900128
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900129 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900130 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900131 static TunInterface sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900132};
133
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900134TunInterface BinderTest::sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900135
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900136class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900137 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700138 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900139 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900140 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900141 }
142
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900143 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900144 std::string mName;
145};
146
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900147TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900148 TimedOperation t("isAlive RPC");
149 bool isAlive = false;
150 mNetd->isAlive(&isAlive);
151 ASSERT_TRUE(isAlive);
152}
153
154static int randomUid() {
155 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
156}
157
Robin Leeb8087362016-03-30 18:43:08 +0100158static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900159 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900160 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
161 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900162 perror("popen");
163 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900164 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900165
166 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100167 size_t bufsize = 0;
168 ssize_t linelen = 0;
169 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900170 lines.push_back(std::string(line, linelen));
171 free(line);
172 line = nullptr;
173 }
174
175 pclose(f);
176 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900177}
178
Robin Leeb8087362016-03-30 18:43:08 +0100179static std::vector<std::string> listIpRules(const char *ipVersion) {
180 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
181 return runCommand(command);
182}
183
184static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900185 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100186 return runCommand(command);
187}
188
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900189static int iptablesRuleLineLength(const char *binary, const char *chainName) {
190 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900191}
192
Benedict Wongb2daefb2017-12-06 22:05:46 -0800193static bool iptablesRuleExists(const char *binary,
194 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900195 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800196 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900197 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800198 if(rule.find(expectedRule) != std::string::npos) {
199 return true;
200 }
201 }
202 return false;
203}
204
205static bool iptablesNoSocketAllowRuleExists(const char *chainName){
206 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
207 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
208}
209
210static bool iptablesEspAllowRuleExists(const char *chainName){
211 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
212 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
213}
214
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900215TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700216 SKIP_IF_BPF_SUPPORTED;
217
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900218 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
219 const int kNumUids = 500;
220 std::vector<int32_t> noUids(0);
221 std::vector<int32_t> uids(kNumUids);
222 for (int i = 0; i < kNumUids; i++) {
223 uids[i] = randomUid();
224 }
225
226 bool ret;
227 {
228 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900229 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900230 }
231 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800232 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
233 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
234 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
235 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900236 {
237 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900238 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900239 }
240 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900241 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
242 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900243
244 {
245 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900246 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900247 }
248 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900249 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
250 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800251 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
252 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900253
254 {
255 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900256 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900257 }
258 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900259 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
260 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900261
262 // Check that the call fails if iptables returns an error.
263 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900264 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900265 EXPECT_EQ(false, ret);
266}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900267
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900268TEST_F(BinderTest, VirtualTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700269 const struct TestData {
270 const std::string family;
271 const std::string deviceName;
272 const std::string localAddress;
273 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800274 int32_t iKey;
275 int32_t oKey;
276 } kTestData[] = {
Nathan Harold21299f72018-03-16 20:13:03 -0700277 {"IPV4", "test_vti", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53},
278 {"IPV6", "test_vti6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50},
manojboopathi8707f232018-01-02 14:45:47 -0800279 };
280
281 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700282 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800283
284 binder::Status status;
285
286 // Create Virtual Tunnel Interface.
Nathan Harold21299f72018-03-16 20:13:03 -0700287 status = mNetd->addVirtualTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
288 td.iKey, td.oKey);
manojboopathi8707f232018-01-02 14:45:47 -0800289 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
290
291 // Update Virtual Tunnel Interface.
292 status = mNetd->updateVirtualTunnelInterface(td.deviceName, td.localAddress,
293 td.remoteAddress, td.iKey, td.oKey);
294 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
295
296 // Remove Virtual Tunnel Interface.
297 status = mNetd->removeVirtualTunnelInterface(td.deviceName);
298 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
299 }
300}
301
Nathan Harold2deff322018-05-10 14:03:48 -0700302// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
303// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
304#if INTPTR_MAX != INT32_MAX
Benedict Wonga04ffa72018-05-09 21:42:42 -0700305static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
306 static_cast<int>(android::net::XfrmDirection::OUT)};
307static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
308
Nathan Harold21299f72018-03-16 20:13:03 -0700309#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
310 do { if ((_expect_) != (_ret_)) return false; } while(false)
311bool BinderTest::allocateIpSecResources(bool expectOk, int32_t *spi) {
312 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
313 SCOPED_TRACE(status);
314 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
315
316 // Add a policy
Benedict Wonga04ffa72018-05-09 21:42:42 -0700317 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700318 SCOPED_TRACE(status);
319 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
320
321 // Add an ipsec interface
322 status = netdutils::statusFromErrno(
323 XfrmController::addVirtualTunnelInterface(
324 "ipsec_test", "::", "::1", 0xF00D, 0xD00D, false),
325 "addVirtualTunnelInterface");
326 return (status.ok() == expectOk);
327}
328
Benedict Wonga04ffa72018-05-09 21:42:42 -0700329TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
330 binder::Status status;
331
332 // Repeat to ensure cleanup and recreation works correctly
333 for (int i = 0; i < 2; i++) {
334 for (int direction : XFRM_DIRECTIONS) {
335 for (int addrFamily : ADDRESS_FAMILIES) {
336 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
337 "127.0.0.6", 123, 0, 0);
338 EXPECT_TRUE(status.isOk())
339 << " family: " << addrFamily << " direction: " << direction;
340 }
341 }
342
343 // Cleanup
344 for (int direction : XFRM_DIRECTIONS) {
345 for (int addrFamily : ADDRESS_FAMILIES) {
346 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0);
347 EXPECT_TRUE(status.isOk());
348 }
349 }
350 }
351}
352
353TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
354 binder::Status status;
355
356 // Repeat to ensure cleanup and recreation works correctly
357 for (int i = 0; i < 2; i++) {
358 for (int direction : XFRM_DIRECTIONS) {
359 for (int addrFamily : ADDRESS_FAMILIES) {
360 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
361 "2001:db8::d00d", 123, 0, 0);
362 EXPECT_TRUE(status.isOk())
363 << " family: " << addrFamily << " direction: " << direction;
364 }
365 }
366
367 // Cleanup
368 for (int direction : XFRM_DIRECTIONS) {
369 for (int addrFamily : ADDRESS_FAMILIES) {
370 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0);
371 EXPECT_TRUE(status.isOk());
372 }
373 }
374 }
375}
376
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900377TEST_F(BinderTest, XfrmControllerInit) {
Nathan Harold21299f72018-03-16 20:13:03 -0700378 netdutils::Status status;
379 status = XfrmController::Init();
380 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700381
382 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
383 // feature.
384 if (status.code() == EOPNOTSUPP) return;
385
Nathan Harold21299f72018-03-16 20:13:03 -0700386 ASSERT_TRUE(status.ok());
387
388 int32_t spi = 0;
389
390 ASSERT_TRUE(allocateIpSecResources(true, &spi));
391 ASSERT_TRUE(allocateIpSecResources(false, &spi));
392
393 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700394 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700395 ASSERT_TRUE(allocateIpSecResources(true, &spi));
396
397 // Clean up
398 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0);
399 SCOPED_TRACE(status);
400 ASSERT_TRUE(status.ok());
401
Benedict Wonga04ffa72018-05-09 21:42:42 -0700402 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700403 SCOPED_TRACE(status);
404 ASSERT_TRUE(status.ok());
405
406 // Remove Virtual Tunnel Interface.
407 status = netdutils::statusFromErrno(
408 XfrmController::removeVirtualTunnelInterface("ipsec_test"),
409 "removeVirtualTunnelInterface");
410
411 ASSERT_TRUE(status.ok());
412}
Nathan Harold2deff322018-05-10 14:03:48 -0700413#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700414
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900415static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900416 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900417
418 // Output looks like this:
419 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900420 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900421 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900422 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900423 //
424 // or:
425 //
426 // Chain bw_data_saver (1 references)
427 // target prot opt source destination
428 // ... possibly connectivity critical packet rules here ...
429 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900430
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900431 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900432
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900433 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
434 // Data saver disabled.
435 return 0;
436 }
437
438 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
439
440 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
441 // Data saver enabled.
442 return 1;
443 }
444
445 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900446}
447
448bool enableDataSaver(sp<INetd>& netd, bool enable) {
449 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
450 bool ret;
451 netd->bandwidthEnableDataSaver(enable, &ret);
452 return ret;
453}
454
455int getDataSaverState() {
456 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
457 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
458 EXPECT_EQ(enabled4, enabled6);
459 EXPECT_NE(-1, enabled4);
460 EXPECT_NE(-1, enabled6);
461 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
462 return -1;
463 }
464 return enabled6;
465}
466
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900467TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900468 const int wasEnabled = getDataSaverState();
469 ASSERT_NE(-1, wasEnabled);
470
471 if (wasEnabled) {
472 ASSERT_TRUE(enableDataSaver(mNetd, false));
473 EXPECT_EQ(0, getDataSaverState());
474 }
475
476 ASSERT_TRUE(enableDataSaver(mNetd, false));
477 EXPECT_EQ(0, getDataSaverState());
478
479 ASSERT_TRUE(enableDataSaver(mNetd, true));
480 EXPECT_EQ(1, getDataSaverState());
481
482 ASSERT_TRUE(enableDataSaver(mNetd, true));
483 EXPECT_EQ(1, getDataSaverState());
484
485 if (!wasEnabled) {
486 ASSERT_TRUE(enableDataSaver(mNetd, false));
487 EXPECT_EQ(0, getDataSaverState());
488 }
489}
Robin Leeb8087362016-03-30 18:43:08 +0100490
491static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
492 const std::string& action, const char* ipVersion) {
493 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100494 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100495 std::vector<std::string> rules = listIpRules(ipVersion);
496
497 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
498 std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
499 range.getStart(), range.getStop(), action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900500 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800501 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100502 return true;
503 }
504 }
505 return false;
506}
507
508static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
509 const std::string& action) {
510 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
511 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
512 EXPECT_EQ(existsIp4, existsIp6);
513 return existsIp4;
514}
515
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900516TEST_F(BinderTest, NetworkInterfaces) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900517 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, "").isOk());
518 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, "").serviceSpecificErrorCode());
519 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
520 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
521
522 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
523 EXPECT_EQ(EBUSY,
524 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
525
526 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
527 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
528 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
529}
530
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900531TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900532 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
533
534 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
535 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
536 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
537
538 std::vector<UidRange> uidRanges = {
539 {BASE_UID + 8005, BASE_UID + 8012},
540 {BASE_UID + 8090, BASE_UID + 8099}
541 };
542 UidRange otherRange(BASE_UID + 8190, BASE_UID + 8299);
543 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
544
545 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
546
547 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
548 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
549 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
550 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
551
552 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
553 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
554 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
555 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
556
557 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
558}
559
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900560TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100561 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100562
Robin Leeb8087362016-03-30 18:43:08 +0100563 std::vector<UidRange> uidRanges = {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900564 {BASE_UID + 150, BASE_UID + 224},
565 {BASE_UID + 226, BASE_UID + 300}
Robin Leeb8087362016-03-30 18:43:08 +0100566 };
567
568 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
569 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
570
571 // Create two valid rules.
572 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
573 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
574 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
575 for (auto const& range : uidRanges) {
576 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
577 }
578
579 // Remove the rules.
580 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
581 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
582 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
583 for (auto const& range : uidRanges) {
584 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
585 }
586
587 // Fail to remove the rules a second time after they are already deleted.
588 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
589 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
590 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
591
592 // All rules should be the same as before.
593 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
594 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
595}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900596
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900597// Create a socket pair that isLoopbackSocket won't think is local.
598void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900599 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900600 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900601 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
602
603 socklen_t addrlen = sizeof(server6);
604 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
605 ASSERT_EQ(0, listen(*serverSocket, 10));
606
Bernie Innocentif6918262018-06-11 17:37:35 +0900607 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900608 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900609 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900610 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
611 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
612
Bernie Innocentif6918262018-06-11 17:37:35 +0900613 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900614 ASSERT_NE(-1, *acceptedSocket);
615
616 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
617}
618
619void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
620 char buf[4096];
621 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
622 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
623 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
624}
625
626void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
627 // Check that the client socket was closed with ECONNABORTED.
628 int ret = write(clientSocket, "foo", sizeof("foo"));
629 int err = errno;
630 EXPECT_EQ(-1, ret);
631 EXPECT_EQ(ECONNABORTED, err);
632
633 // Check that it sent a RST to the server.
634 ret = write(acceptedSocket, "foo", sizeof("foo"));
635 err = errno;
636 EXPECT_EQ(-1, ret);
637 EXPECT_EQ(ECONNRESET, err);
638}
639
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900640TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900641 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900642 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900643
644 // Pick a random UID in the system UID range.
645 constexpr int baseUid = AID_APP - 2000;
646 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
647 int uid = baseUid + 500 + arc4random_uniform(1000);
648 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
649
650 // UID ranges that don't contain uid.
651 std::vector<UidRange> uidRanges = {
652 {baseUid + 42, baseUid + 449},
653 {baseUid + 1536, AID_APP - 4},
654 {baseUid + 498, uid - 1},
655 {uid + 1, baseUid + 1520},
656 };
657 // A skip list that doesn't contain UID.
658 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
659
660 // Close sockets. Our test socket should be intact.
661 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
662 checkSocketpairOpen(clientSocket, acceptedSocket);
663
664 // UID ranges that do contain uid.
665 uidRanges = {
666 {baseUid + 42, baseUid + 449},
667 {baseUid + 1536, AID_APP - 4},
668 {baseUid + 498, baseUid + 1520},
669 };
670 // Add uid to the skip list.
671 skipUids.push_back(uid);
672
673 // Close sockets. Our test socket should still be intact because it's in the skip list.
674 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
675 checkSocketpairOpen(clientSocket, acceptedSocket);
676
677 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
678 skipUids.resize(skipUids.size() - 1);
679 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
680 checkSocketpairClosed(clientSocket, acceptedSocket);
681
682 close(clientSocket);
683 close(serverSocket);
684 close(acceptedSocket);
685}
Erik Klinecc4f2732016-08-03 11:24:27 +0900686
687namespace {
688
689int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
690 if (buf == nullptr) return -1;
691
692 int prefixLength = 0;
693 bool endOfContiguousBits = false;
694 for (unsigned int i = 0; i < buflen; i++) {
695 const uint8_t value = buf[i];
696
697 // Bad bit sequence: check for a contiguous set of bits from the high
698 // end by verifying that the inverted value + 1 is a power of 2
699 // (power of 2 iff. (v & (v - 1)) == 0).
700 const uint8_t inverse = ~value + 1;
701 if ((inverse & (inverse - 1)) != 0) return -1;
702
703 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
704
705 // Bogus netmask.
706 if (endOfContiguousBits && value != 0) return -1;
707
708 if (value != 0xff) endOfContiguousBits = true;
709 }
710
711 return prefixLength;
712}
713
714template<typename T>
715int netmaskToPrefixLength(const T *p) {
716 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
717}
718
719
720static bool interfaceHasAddress(
721 const std::string &ifname, const char *addrString, int prefixLength) {
722 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900723
724 const struct addrinfo hints = {
725 .ai_flags = AI_NUMERICHOST,
726 .ai_family = AF_UNSPEC,
727 .ai_socktype = SOCK_DGRAM,
728 };
729 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
730 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
731 return false;
732 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900733 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900734
735 struct ifaddrs *ifaddrsList = nullptr;
736 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
737
738 if (getifaddrs(&ifaddrsList) != 0) {
739 return false;
740 }
741
742 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
743 if (std::string(addr->ifa_name) != ifname ||
744 addr->ifa_addr == nullptr ||
745 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
746 continue;
747 }
748
749 switch (addr->ifa_addr->sa_family) {
750 case AF_INET: {
751 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
752 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
753 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
754 continue;
755 }
756
757 if (prefixLength < 0) return true; // not checking prefix lengths
758
759 if (addr->ifa_netmask == nullptr) return false;
760 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
761 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
762 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
763 }
764 case AF_INET6: {
765 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
766 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
767 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
768 continue;
769 }
770
771 if (prefixLength < 0) return true; // not checking prefix lengths
772
773 if (addr->ifa_netmask == nullptr) return false;
774 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
775 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
776 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
777 }
778 default:
779 // Cannot happen because we have already screened for matching
780 // address families at the top of each iteration.
781 continue;
782 }
783 }
784
785 return false;
786}
787
788} // namespace
789
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900790TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900791 static const struct TestData {
792 const char *addrString;
793 const int prefixLength;
794 const bool expectSuccess;
795 } kTestData[] = {
796 { "192.0.2.1", 24, true },
797 { "192.0.2.2", 25, true },
798 { "192.0.2.3", 32, true },
799 { "192.0.2.4", 33, false },
800 { "192.not.an.ip", 24, false },
801 { "2001:db8::1", 64, true },
802 { "2001:db8::2", 65, true },
803 { "2001:db8::3", 128, true },
804 { "2001:db8::4", 129, false },
805 { "foo:bar::bad", 64, false },
806 };
807
808 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
809 const auto &td = kTestData[i];
810
811 // [1.a] Add the address.
812 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900813 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900814 if (td.expectSuccess) {
815 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
816 } else {
817 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
818 ASSERT_NE(0, status.serviceSpecificErrorCode());
819 }
820
821 // [1.b] Verify the addition meets the expectation.
822 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900823 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900824 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900825 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900826 }
827
828 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900829 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900830 if (td.expectSuccess) {
831 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
832 } else {
833 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
834 ASSERT_NE(0, status.serviceSpecificErrorCode());
835 }
836
837 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900838 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900839 }
840}
Erik Kline55b06f82016-07-04 09:57:18 +0900841
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900842TEST_F(BinderTest, SetProcSysNet) {
Erik Kline55b06f82016-07-04 09:57:18 +0900843 static const struct TestData {
844 const int family;
845 const int which;
846 const char *ifname;
847 const char *parameter;
848 const char *value;
849 const int expectedReturnCode;
850 } kTestData[] = {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900851 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0 },
852 { -1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT },
853 { INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL },
Erik Kline55b06f82016-07-04 09:57:18 +0900854 { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
855 { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900856 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL },
857 { INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0 },
Erik Kline55b06f82016-07-04 09:57:18 +0900858 };
859
860 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
861 const auto &td = kTestData[i];
862
863 const binder::Status status = mNetd->setProcSysNet(
864 td.family, td.which, td.ifname, td.parameter,
865 td.value);
866
867 if (td.expectedReturnCode == 0) {
868 SCOPED_TRACE(String8::format("test case %d should have passed", i));
869 EXPECT_EQ(0, status.exceptionCode());
870 EXPECT_EQ(0, status.serviceSpecificErrorCode());
871 } else {
872 SCOPED_TRACE(String8::format("test case %d should have failed", i));
873 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
874 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
875 }
876 }
877}
Ben Schwartze7601812017-04-28 16:38:29 -0400878
879static std::string base64Encode(const std::vector<uint8_t>& input) {
880 size_t out_len;
881 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
882 // out_len includes the trailing NULL.
883 uint8_t output_bytes[out_len];
884 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
885 return std::string(reinterpret_cast<char*>(output_bytes));
886}
887
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900888TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900889 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400890 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400891 std::vector<uint8_t> short_fp(1);
892 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
893 std::vector<std::string> test_domains;
894 std::vector<int> test_params = { 300, 25, 8, 8 };
895 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400896 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400897 const std::vector<std::string> servers;
898 const std::string tlsName;
899 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400900 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900901 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400902 { {"192.0.2.1"}, "", {}, 0 },
903 { {"2001:db8::2"}, "host.name", {}, 0 },
904 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
905 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900906 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400907 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900908 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400909 { {"2001:dg8::6"}, "", {}, EINVAL },
910 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
911 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
912 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
913 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400914 };
915
Erik Klinea1476fb2018-03-04 21:01:56 +0900916 for (unsigned int i = 0; i < arraysize(kTlsTestData); i++) {
917 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -0400918
919 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400920 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400921 fingerprints.push_back(base64Encode(fingerprint));
922 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400923 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900924 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
925 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -0400926
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400927 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -0400928 SCOPED_TRACE(String8::format("test case %d should have passed", i));
929 SCOPED_TRACE(status.toString8());
930 EXPECT_EQ(0, status.exceptionCode());
931 } else {
932 SCOPED_TRACE(String8::format("test case %d should have failed", i));
933 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400934 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -0400935 }
Ben Schwartze7601812017-04-28 16:38:29 -0400936 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400937 // Ensure TLS is disabled before the start of the next test.
938 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900939 test_netid, kTlsTestData[0].servers, test_domains, test_params,
940 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -0400941}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900942
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900943namespace {
944
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900945void expectNoTestCounterRules() {
946 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
947 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
948 std::string allRules = Join(runCommand(command), "\n");
949 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
950 }
951}
952
Bernie Innocentif6918262018-06-11 17:37:35 +0900953void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
954 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900955 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
956 path, if1.c_str(), if2.c_str(), pkt, byte));
957}
958
Bernie Innocentif6918262018-06-11 17:37:35 +0900959void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900960 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
961 path, if1.c_str(), if2.c_str()));
962 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
963 path, if2.c_str(), if1.c_str()));
964}
965
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900966} // namespace
967
968TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900969 expectNoTestCounterRules();
970
971 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
972 // disabling tethering. We don't check the return value because these commands will fail if
973 // tethering is already enabled.
974 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
975 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
976
977 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
978 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
979 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
980 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
981 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
982
983 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
984 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
985 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
986 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
987 // RX is from external to internal, and TX is from internal to external.
988 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
989 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
990
991 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
992 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
993
994 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
995 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
996
997 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
998 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
999 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1000
1001 PersistableBundle stats;
1002 binder::Status status = mNetd->tetherGetStats(&stats);
1003 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1004
1005 std::vector<int64_t> actual1;
1006 EXPECT_TRUE(stats.getLongVector(String16(extIface1.c_str()), &actual1));
1007 EXPECT_EQ(expected1, actual1);
1008
1009 std::vector<int64_t> actual2;
1010 EXPECT_TRUE(stats.getLongVector(String16(extIface2.c_str()), &actual2));
1011 EXPECT_EQ(expected2, actual2);
1012
1013 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1014 delTetherCounterValues(path, intIface1, extIface1);
1015 delTetherCounterValues(path, intIface2, extIface2);
1016 if (path == IP6TABLES_PATH) {
1017 delTetherCounterValues(path, intIface3, extIface2);
1018 }
1019 }
1020
1021 expectNoTestCounterRules();
1022}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001023
Luke Huang0051a622018-07-23 20:30:16 +08001024namespace {
1025
Luke Huanga5211072018-08-01 23:36:29 +08001026constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1027constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001028
1029static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1030 const char* chainName) {
1031 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1032 return runCommand(command);
1033}
1034
Luke Huanga5211072018-08-01 23:36:29 +08001035bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001036 const std::string& expectedInterface,
1037 const std::string& expectedRule, const char* table) {
1038 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1039 for (const auto& rule : rules) {
1040 if (rule.find(expectedInterface) != std::string::npos) {
1041 if (rule.find(expectedRule) != std::string::npos) {
1042 return true;
1043 }
1044 }
1045 }
1046 return false;
1047}
1048
1049void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001050 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001051 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001052 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001053 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001054 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1055 IdletimerRule, RAW_TABLE));
1056 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001057 ifname, IdletimerRule, MANGLE_TABLE));
1058 }
1059}
1060
1061void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001062 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001063 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001064 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001065 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001066 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1067 IdletimerRule, RAW_TABLE));
1068 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001069 ifname, IdletimerRule, MANGLE_TABLE));
1070 }
1071}
1072
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001073} // namespace
1074
1075TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001076 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1077 // rule in the table. Because we only check the result after calling remove function. We might
1078 // check the actual rule which is removed by our function (maybe compare the results between
1079 // calling function before and after)
1080 binder::Status status;
1081 const struct TestData {
1082 const std::string ifname;
1083 int32_t timeout;
1084 const std::string classLabel;
1085 } idleTestData[] = {
1086 {"wlan0", 1234, "happyday"},
1087 {"rmnet_data0", 4567, "friday"},
1088 };
1089 for (const auto& td : idleTestData) {
1090 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1091 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1092 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1093
1094 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1095 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1096 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1097 }
1098}
1099
Luke Huanga67dd562018-07-17 19:58:25 +08001100namespace {
1101
1102constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1103constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1104
1105void expectStrictSetUidAccept(const int uid) {
1106 std::string uidRule = StringPrintf("owner UID match %u", uid);
1107 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1108 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1109 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1110 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1111 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1112 }
1113}
1114
1115void expectStrictSetUidLog(const int uid) {
1116 static const char logRule[] = "st_penalty_log all";
1117 std::string uidRule = StringPrintf("owner UID match %u", uid);
1118 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1119 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1120 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1121 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1122 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1123 }
1124}
1125
1126void expectStrictSetUidReject(const int uid) {
1127 static const char rejectRule[] = "st_penalty_reject all";
1128 std::string uidRule = StringPrintf("owner UID match %u", uid);
1129 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1130 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1131 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1132 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1133 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1134 }
1135}
1136
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001137} // namespace
1138
1139TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001140 binder::Status status;
1141 int32_t uid = randomUid();
1142
1143 // setUidCleartextPenalty Policy:Log with randomUid
1144 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1145 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1146 expectStrictSetUidLog(uid);
1147
1148 // setUidCleartextPenalty Policy:Accept with randomUid
1149 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1150 expectStrictSetUidAccept(uid);
1151
1152 // setUidCleartextPenalty Policy:Reject with randomUid
1153 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1154 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1155 expectStrictSetUidReject(uid);
1156
1157 // setUidCleartextPenalty Policy:Accept with randomUid
1158 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1159 expectStrictSetUidAccept(uid);
1160
1161 // test wrong policy
1162 int32_t wrongPolicy = -123;
1163 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1164 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1165}
1166
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001167namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001168
Luke Huanga5211072018-08-01 23:36:29 +08001169bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001170 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1171 return (runCommand(cmd.c_str()).size()) ? true : false;
1172}
1173
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001174} // namespace
1175
1176TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001177 binder::Status status;
1178 // use dummy0 for test since it is set ready
1179 static const char testIf[] = "dummy0";
1180 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1181
1182 status = mNetd->clatdStart(testIf);
1183 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1184 EXPECT_TRUE(processExists(clatdName));
1185
1186 mNetd->clatdStop(testIf);
1187 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1188 EXPECT_FALSE(processExists(clatdName));
1189}
Luke Huang457d4702018-08-16 15:39:15 +08001190
1191namespace {
1192
1193bool getIpfwdV4Enable() {
1194 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1195 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1196 EXPECT_TRUE(!result.empty());
1197 int v4Enable = std::stoi(result[0]);
1198 return v4Enable;
1199}
1200
1201bool getIpfwdV6Enable() {
1202 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1203 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1204 EXPECT_TRUE(!result.empty());
1205 int v6Enable = std::stoi(result[0]);
1206 return v6Enable;
1207}
1208
1209void expectIpfwdEnable(bool enable) {
1210 int enableIPv4 = getIpfwdV4Enable();
1211 int enableIPv6 = getIpfwdV6Enable();
1212 EXPECT_EQ(enable, enableIPv4);
1213 EXPECT_EQ(enable, enableIPv6);
1214}
1215
1216bool ipRuleIpfwdExists(const char* ipVersion, const std::string ipfwdRule) {
1217 std::vector<std::string> rules = listIpRules(ipVersion);
1218 for (const auto& rule : rules) {
1219 if (rule.find(ipfwdRule) != std::string::npos) {
1220 return true;
1221 }
1222 }
1223 return false;
1224}
1225
1226void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1227 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1228
1229 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1230 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1231 }
1232}
1233
1234void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1235 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1236
1237 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1238 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1239 }
1240}
1241
1242} // namespace
1243
1244TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1245 // Netd default enable Ipfwd with requester NetdHwService
1246 const std::string defaultRequester = "NetdHwService";
1247
1248 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1249 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1250 expectIpfwdEnable(false);
1251
1252 bool ipfwdEnabled;
1253 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1254 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1255 EXPECT_FALSE(ipfwdEnabled);
1256
1257 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1258 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1259 expectIpfwdEnable(true);
1260
1261 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1262 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1263 EXPECT_TRUE(ipfwdEnabled);
1264}
1265
1266TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1267 static const char testFromIf[] = "dummy0";
1268 static const char testToIf[] = "dummy0";
1269
1270 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1271 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1272 expectIpfwdRuleExists(testFromIf, testToIf);
1273
1274 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1275 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1276 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001277}