blob: febe50b6baa28873c28f0e423fa7c7968d02be10 [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
Erik Kline38e51f12018-09-06 20:14:44 +0900842TEST_F(BinderTest, GetProcSysNet) {
843 const char LOOPBACK[] = "lo";
844 static const struct {
845 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900846 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900847 const char* ifname;
848 const char* parameter;
849 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900850 const int expectedReturnCode;
851 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900852 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
853 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
854 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
855 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
856 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
857 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
858 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900859 };
860
Erik Kline38e51f12018-09-06 20:14:44 +0900861 for (int i = 0; i < arraysize(kTestData); i++) {
862 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900863
Erik Kline38e51f12018-09-06 20:14:44 +0900864 std::string value;
865 const binder::Status status =
866 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
867
868 if (td.expectedReturnCode == 0) {
869 SCOPED_TRACE(String8::format("test case %d should have passed", i));
870 EXPECT_EQ(0, status.exceptionCode());
871 EXPECT_EQ(0, status.serviceSpecificErrorCode());
872 EXPECT_EQ(td.expectedValue, value);
873 } else {
874 SCOPED_TRACE(String8::format("test case %d should have failed", i));
875 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
876 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
877 }
878 }
879}
880
881TEST_F(BinderTest, SetProcSysNet) {
882 static const struct {
883 const int ipversion;
884 const int which;
885 const char* ifname;
886 const char* parameter;
887 const char* value;
888 const int expectedReturnCode;
889 } kTestData[] = {
890 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
891 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
892 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
893 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
894 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
895 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
896 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
897 };
898
899 for (int i = 0; i < arraysize(kTestData); i++) {
900 const auto& td = kTestData[i];
901
902 const binder::Status status =
903 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900904
905 if (td.expectedReturnCode == 0) {
906 SCOPED_TRACE(String8::format("test case %d should have passed", i));
907 EXPECT_EQ(0, status.exceptionCode());
908 EXPECT_EQ(0, status.serviceSpecificErrorCode());
909 } else {
910 SCOPED_TRACE(String8::format("test case %d should have failed", i));
911 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
912 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
913 }
914 }
915}
Ben Schwartze7601812017-04-28 16:38:29 -0400916
Erik Kline38e51f12018-09-06 20:14:44 +0900917TEST_F(BinderTest, GetSetProcSysNet) {
918 const int ipversion = INetd::IPV6;
919 const int category = INetd::NEIGH;
920 const std::string& tun = sTun.name();
921 const std::string parameter("ucast_solicit");
922
923 std::string value{};
924 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
925 EXPECT_FALSE(value.empty());
926 const int ival = std::stoi(value);
927 EXPECT_GT(ival, 0);
928 // Try doubling the parameter value (always best!).
929 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
930 .isOk());
931 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
932 EXPECT_EQ(2 * ival, std::stoi(value));
933 // Try resetting the parameter.
934 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
935 .isOk());
936 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
937 EXPECT_EQ(ival, std::stoi(value));
938}
939
Ben Schwartze7601812017-04-28 16:38:29 -0400940static std::string base64Encode(const std::vector<uint8_t>& input) {
941 size_t out_len;
942 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
943 // out_len includes the trailing NULL.
944 uint8_t output_bytes[out_len];
945 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
946 return std::string(reinterpret_cast<char*>(output_bytes));
947}
948
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900949TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900950 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400951 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400952 std::vector<uint8_t> short_fp(1);
953 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
954 std::vector<std::string> test_domains;
955 std::vector<int> test_params = { 300, 25, 8, 8 };
956 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400957 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400958 const std::vector<std::string> servers;
959 const std::string tlsName;
960 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400961 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900962 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400963 { {"192.0.2.1"}, "", {}, 0 },
964 { {"2001:db8::2"}, "host.name", {}, 0 },
965 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
966 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900967 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400968 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900969 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400970 { {"2001:dg8::6"}, "", {}, EINVAL },
971 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
972 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
973 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
974 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400975 };
976
Erik Klinea1476fb2018-03-04 21:01:56 +0900977 for (unsigned int i = 0; i < arraysize(kTlsTestData); i++) {
978 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -0400979
980 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400981 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400982 fingerprints.push_back(base64Encode(fingerprint));
983 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400984 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900985 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
986 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -0400987
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400988 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -0400989 SCOPED_TRACE(String8::format("test case %d should have passed", i));
990 SCOPED_TRACE(status.toString8());
991 EXPECT_EQ(0, status.exceptionCode());
992 } else {
993 SCOPED_TRACE(String8::format("test case %d should have failed", i));
994 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400995 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -0400996 }
Ben Schwartze7601812017-04-28 16:38:29 -0400997 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400998 // Ensure TLS is disabled before the start of the next test.
999 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001000 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1001 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001002}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001003
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001004namespace {
1005
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001006void expectNoTestCounterRules() {
1007 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1008 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1009 std::string allRules = Join(runCommand(command), "\n");
1010 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1011 }
1012}
1013
Bernie Innocentif6918262018-06-11 17:37:35 +09001014void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1015 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001016 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1017 path, if1.c_str(), if2.c_str(), pkt, byte));
1018}
1019
Bernie Innocentif6918262018-06-11 17:37:35 +09001020void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001021 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1022 path, if1.c_str(), if2.c_str()));
1023 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1024 path, if2.c_str(), if1.c_str()));
1025}
1026
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001027} // namespace
1028
1029TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001030 expectNoTestCounterRules();
1031
1032 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1033 // disabling tethering. We don't check the return value because these commands will fail if
1034 // tethering is already enabled.
1035 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1036 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1037
1038 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1039 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1040 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1041 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1042 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1043
1044 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1045 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1046 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1047 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1048 // RX is from external to internal, and TX is from internal to external.
1049 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1050 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1051
1052 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1053 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1054
1055 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1056 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1057
1058 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1059 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1060 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1061
1062 PersistableBundle stats;
1063 binder::Status status = mNetd->tetherGetStats(&stats);
1064 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1065
1066 std::vector<int64_t> actual1;
1067 EXPECT_TRUE(stats.getLongVector(String16(extIface1.c_str()), &actual1));
1068 EXPECT_EQ(expected1, actual1);
1069
1070 std::vector<int64_t> actual2;
1071 EXPECT_TRUE(stats.getLongVector(String16(extIface2.c_str()), &actual2));
1072 EXPECT_EQ(expected2, actual2);
1073
1074 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1075 delTetherCounterValues(path, intIface1, extIface1);
1076 delTetherCounterValues(path, intIface2, extIface2);
1077 if (path == IP6TABLES_PATH) {
1078 delTetherCounterValues(path, intIface3, extIface2);
1079 }
1080 }
1081
1082 expectNoTestCounterRules();
1083}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001084
Luke Huang0051a622018-07-23 20:30:16 +08001085namespace {
1086
Luke Huanga5211072018-08-01 23:36:29 +08001087constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1088constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001089
1090static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1091 const char* chainName) {
1092 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1093 return runCommand(command);
1094}
1095
Luke Huanga5211072018-08-01 23:36:29 +08001096bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001097 const std::string& expectedInterface,
1098 const std::string& expectedRule, const char* table) {
1099 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1100 for (const auto& rule : rules) {
1101 if (rule.find(expectedInterface) != std::string::npos) {
1102 if (rule.find(expectedRule) != std::string::npos) {
1103 return true;
1104 }
1105 }
1106 }
1107 return false;
1108}
1109
1110void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001111 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001112 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001113 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001114 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001115 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1116 IdletimerRule, RAW_TABLE));
1117 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001118 ifname, IdletimerRule, MANGLE_TABLE));
1119 }
1120}
1121
1122void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001123 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001124 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001125 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001126 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001127 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1128 IdletimerRule, RAW_TABLE));
1129 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001130 ifname, IdletimerRule, MANGLE_TABLE));
1131 }
1132}
1133
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001134} // namespace
1135
1136TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001137 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1138 // rule in the table. Because we only check the result after calling remove function. We might
1139 // check the actual rule which is removed by our function (maybe compare the results between
1140 // calling function before and after)
1141 binder::Status status;
1142 const struct TestData {
1143 const std::string ifname;
1144 int32_t timeout;
1145 const std::string classLabel;
1146 } idleTestData[] = {
1147 {"wlan0", 1234, "happyday"},
1148 {"rmnet_data0", 4567, "friday"},
1149 };
1150 for (const auto& td : idleTestData) {
1151 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1152 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1153 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1154
1155 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1156 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1157 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1158 }
1159}
1160
Luke Huanga67dd562018-07-17 19:58:25 +08001161namespace {
1162
1163constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1164constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1165
1166void expectStrictSetUidAccept(const int uid) {
1167 std::string uidRule = StringPrintf("owner UID match %u", uid);
1168 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1169 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1170 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1171 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1172 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1173 }
1174}
1175
1176void expectStrictSetUidLog(const int uid) {
1177 static const char logRule[] = "st_penalty_log all";
1178 std::string uidRule = StringPrintf("owner UID match %u", uid);
1179 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1180 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1181 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1182 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1183 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1184 }
1185}
1186
1187void expectStrictSetUidReject(const int uid) {
1188 static const char rejectRule[] = "st_penalty_reject all";
1189 std::string uidRule = StringPrintf("owner UID match %u", uid);
1190 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1191 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1192 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1193 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1194 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1195 }
1196}
1197
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001198} // namespace
1199
1200TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001201 binder::Status status;
1202 int32_t uid = randomUid();
1203
1204 // setUidCleartextPenalty Policy:Log with randomUid
1205 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1206 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1207 expectStrictSetUidLog(uid);
1208
1209 // setUidCleartextPenalty Policy:Accept with randomUid
1210 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1211 expectStrictSetUidAccept(uid);
1212
1213 // setUidCleartextPenalty Policy:Reject with randomUid
1214 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1215 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1216 expectStrictSetUidReject(uid);
1217
1218 // setUidCleartextPenalty Policy:Accept with randomUid
1219 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1220 expectStrictSetUidAccept(uid);
1221
1222 // test wrong policy
1223 int32_t wrongPolicy = -123;
1224 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1225 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1226}
1227
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001228namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001229
Luke Huanga5211072018-08-01 23:36:29 +08001230bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001231 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1232 return (runCommand(cmd.c_str()).size()) ? true : false;
1233}
1234
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001235} // namespace
1236
1237TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001238 binder::Status status;
1239 // use dummy0 for test since it is set ready
1240 static const char testIf[] = "dummy0";
1241 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1242
1243 status = mNetd->clatdStart(testIf);
1244 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1245 EXPECT_TRUE(processExists(clatdName));
1246
1247 mNetd->clatdStop(testIf);
1248 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1249 EXPECT_FALSE(processExists(clatdName));
1250}
Luke Huang457d4702018-08-16 15:39:15 +08001251
1252namespace {
1253
1254bool getIpfwdV4Enable() {
1255 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1256 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1257 EXPECT_TRUE(!result.empty());
1258 int v4Enable = std::stoi(result[0]);
1259 return v4Enable;
1260}
1261
1262bool getIpfwdV6Enable() {
1263 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1264 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1265 EXPECT_TRUE(!result.empty());
1266 int v6Enable = std::stoi(result[0]);
1267 return v6Enable;
1268}
1269
1270void expectIpfwdEnable(bool enable) {
1271 int enableIPv4 = getIpfwdV4Enable();
1272 int enableIPv6 = getIpfwdV6Enable();
1273 EXPECT_EQ(enable, enableIPv4);
1274 EXPECT_EQ(enable, enableIPv6);
1275}
1276
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001277bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001278 std::vector<std::string> rules = listIpRules(ipVersion);
1279 for (const auto& rule : rules) {
1280 if (rule.find(ipfwdRule) != std::string::npos) {
1281 return true;
1282 }
1283 }
1284 return false;
1285}
1286
1287void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1288 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1289
1290 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1291 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1292 }
1293}
1294
1295void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1296 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1297
1298 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1299 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1300 }
1301}
1302
1303} // namespace
1304
1305TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1306 // Netd default enable Ipfwd with requester NetdHwService
1307 const std::string defaultRequester = "NetdHwService";
1308
1309 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1310 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1311 expectIpfwdEnable(false);
1312
1313 bool ipfwdEnabled;
1314 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1315 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1316 EXPECT_FALSE(ipfwdEnabled);
1317
1318 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1319 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1320 expectIpfwdEnable(true);
1321
1322 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1323 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1324 EXPECT_TRUE(ipfwdEnabled);
1325}
1326
1327TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1328 static const char testFromIf[] = "dummy0";
1329 static const char testToIf[] = "dummy0";
1330
1331 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1332 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1333 expectIpfwdRuleExists(testFromIf, testToIf);
1334
1335 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1336 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1337 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001338}