blob: c4029f0a8dc88bbd6bafd34555269c69edb5ccc6 [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
Luke Huangf7782042018-08-08 13:13:04 +080027#include <dirent.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090028#include <fcntl.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090029#include <ifaddrs.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090030#include <linux/if.h>
31#include <linux/if_tun.h>
Benedict Wonga450e722018-05-07 10:29:02 -070032#include <net/if.h>
Luke Huangf7782042018-08-08 13:13:04 +080033#include <netdb.h>
34#include <netinet/in.h>
Ben Schwartze7601812017-04-28 16:38:29 -040035#include <openssl/base64.h>
Luke Huangf7782042018-08-08 13:13:04 +080036#include <sys/socket.h>
37#include <sys/types.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090038
Luke Huang531f5d32018-08-03 15:19:05 +080039#include <android-base/file.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090040#include <android-base/macros.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090041#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090042#include <android-base/strings.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070043#include <bpf/BpfUtils.h>
Robin Leeb8087362016-03-30 18:43:08 +010044#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090045#include <gtest/gtest.h>
46#include <logwrap/logwrap.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090047#include <netutils/ifc.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090048
Nathan Harold21299f72018-03-16 20:13:03 -070049#include "InterfaceController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090050#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090051#include "Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070052#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090053#include "android/net/INetd.h"
54#include "binder/IServiceManager.h"
Nathan Harold21299f72018-03-16 20:13:03 -070055#include "netdutils/Syscalls.h"
Mike Yu5ae61542018-10-19 22:11:43 +080056#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090057
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090058#define IP_PATH "/system/bin/ip"
59#define IP6TABLES_PATH "/system/bin/ip6tables"
60#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090061#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080062#define RAW_TABLE "raw"
63#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080064#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090065#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090066
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090067namespace binder = android::binder;
68namespace netdutils = android::netdutils;
69
70using android::IBinder;
71using android::IServiceManager;
72using android::sp;
73using android::String16;
74using android::String8;
75using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080076using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090077using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090078using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080079using android::base::Trim;
Chenbo Fengf5663d82018-11-08 16:10:48 -080080using android::base::WriteStringToFile;
Chenbo Feng837ddfc2018-05-08 13:45:08 -070081using android::bpf::hasBpfSupport;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090082using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080083using android::net::InterfaceConfigurationParcel;
84using android::net::InterfaceController;
Luke Huangcaebcbb2018-09-27 20:37:14 +080085using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090086using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090087using android::net::UidRangeParcel;
Nathan Harold21299f72018-03-16 20:13:03 -070088using android::net::XfrmController;
Luke Huangf7782042018-08-08 13:13:04 +080089using android::netdutils::sSyscalls;
Robin Leeb8087362016-03-30 18:43:08 +010090
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090091#define SKIP_IF_BPF_SUPPORTED \
92 do { \
93 if (hasBpfSupport()) return; \
94 } while (0)
Chenbo Feng837ddfc2018-05-08 13:45:08 -070095
Robin Leeb8087362016-03-30 18:43:08 +010096static const char* IP_RULE_V4 = "-4";
97static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090098static const int TEST_NETID1 = 65501;
99static const int TEST_NETID2 = 65502;
100constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900101
Benedict Wongb2daefb2017-12-06 22:05:46 -0800102static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
103static const std::string ESP_ALLOW_RULE("esp");
104
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900105class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900106 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900107 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900108 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900109 sp<IBinder> binder = sm->getService(String16("netd"));
110 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900111 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900112 }
113 }
114
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900115 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900116 ASSERT_NE(nullptr, mNetd.get());
117 }
118
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900119 void TearDown() override {
120 mNetd->networkDestroy(TEST_NETID1);
121 mNetd->networkDestroy(TEST_NETID2);
122 }
123
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900124 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700125
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900126 // Static because setting up the tun interface takes about 40ms.
127 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900128 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900129 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900130 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900131 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900132 }
133
134 static void TearDownTestCase() {
135 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900136 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900137 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900138 }
139
140 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900141
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900142 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900143 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900144 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900145 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900146};
147
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900148TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900149TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900150
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900151class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900152 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700153 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900154 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900155 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900156 }
157
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900158 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900159 std::string mName;
160};
161
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900162TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900163 TimedOperation t("isAlive RPC");
164 bool isAlive = false;
165 mNetd->isAlive(&isAlive);
166 ASSERT_TRUE(isAlive);
167}
168
169static int randomUid() {
170 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
171}
172
Robin Leeb8087362016-03-30 18:43:08 +0100173static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900174 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900175 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
176 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900177 perror("popen");
178 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900179 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900180
181 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100182 size_t bufsize = 0;
183 ssize_t linelen = 0;
184 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900185 lines.push_back(std::string(line, linelen));
186 free(line);
187 line = nullptr;
188 }
189
190 pclose(f);
191 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900192}
193
Robin Leeb8087362016-03-30 18:43:08 +0100194static std::vector<std::string> listIpRules(const char *ipVersion) {
195 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
196 return runCommand(command);
197}
198
199static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900200 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100201 return runCommand(command);
202}
203
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900204static int iptablesRuleLineLength(const char *binary, const char *chainName) {
205 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900206}
207
Benedict Wongb2daefb2017-12-06 22:05:46 -0800208static bool iptablesRuleExists(const char *binary,
209 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900210 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800211 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900212 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800213 if(rule.find(expectedRule) != std::string::npos) {
214 return true;
215 }
216 }
217 return false;
218}
219
220static bool iptablesNoSocketAllowRuleExists(const char *chainName){
221 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
222 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
223}
224
225static bool iptablesEspAllowRuleExists(const char *chainName){
226 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
227 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
228}
229
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900230TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700231 SKIP_IF_BPF_SUPPORTED;
232
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900233 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
234 const int kNumUids = 500;
235 std::vector<int32_t> noUids(0);
236 std::vector<int32_t> uids(kNumUids);
237 for (int i = 0; i < kNumUids; i++) {
238 uids[i] = randomUid();
239 }
240
241 bool ret;
242 {
243 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900244 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900245 }
246 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800247 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
248 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
249 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
250 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900251 {
252 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900253 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900254 }
255 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900256 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
257 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900258
259 {
260 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900261 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900262 }
263 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900264 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
265 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800266 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
267 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900268
269 {
270 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900271 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900272 }
273 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900274 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
275 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900276
277 // Check that the call fails if iptables returns an error.
278 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900279 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900280 EXPECT_EQ(false, ret);
281}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900282
Benedict Wong319f17e2018-05-15 17:06:44 -0700283TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700284 const struct TestData {
285 const std::string family;
286 const std::string deviceName;
287 const std::string localAddress;
288 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800289 int32_t iKey;
290 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700291 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800292 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700293 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
294 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
295 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800296 };
297
Sehee Park8659b8d2018-11-16 10:53:16 +0900298 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700299 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800300
301 binder::Status status;
302
Benedict Wong319f17e2018-05-15 17:06:44 -0700303 // Create Tunnel Interface.
304 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700305 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800306 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
307
Benedict Wonga450e722018-05-07 10:29:02 -0700308 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900309 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700310
Benedict Wong319f17e2018-05-15 17:06:44 -0700311 // Update Tunnel Interface.
312 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700313 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800314 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
315
Benedict Wong319f17e2018-05-15 17:06:44 -0700316 // Remove Tunnel Interface.
317 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800318 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700319
320 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900321 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800322 }
323}
324
Benedict Wong1cb73df2018-12-03 00:54:14 -0800325TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
326 android::base::unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
327 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
328
329 int sockOptVal = UDP_ENCAP_ESPINUDP;
330 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
331
332 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
333 EXPECT_TRUE(res.isOk());
334
335 struct stat info;
336 EXPECT_EQ(0, fstat(sockFd.get(), &info));
337 EXPECT_EQ(1001, (int) info.st_uid);
338}
339
Nathan Harold2deff322018-05-10 14:03:48 -0700340// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
341// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
342#if INTPTR_MAX != INT32_MAX
Benedict Wonga04ffa72018-05-09 21:42:42 -0700343static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
344 static_cast<int>(android::net::XfrmDirection::OUT)};
345static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
346
Nathan Harold21299f72018-03-16 20:13:03 -0700347#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
348 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900349bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Nathan Harold21299f72018-03-16 20:13:03 -0700350 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
351 SCOPED_TRACE(status);
352 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
353
354 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700355 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700356 SCOPED_TRACE(status);
357 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
358
359 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700360 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
361 0xD00D, 0xE00D, false)
362 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700363}
364
Benedict Wonga04ffa72018-05-09 21:42:42 -0700365TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
366 binder::Status status;
367
368 // Repeat to ensure cleanup and recreation works correctly
369 for (int i = 0; i < 2; i++) {
370 for (int direction : XFRM_DIRECTIONS) {
371 for (int addrFamily : ADDRESS_FAMILIES) {
372 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700373 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700374 EXPECT_TRUE(status.isOk())
375 << " family: " << addrFamily << " direction: " << direction;
376 }
377 }
378
379 // Cleanup
380 for (int direction : XFRM_DIRECTIONS) {
381 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700382 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700383 EXPECT_TRUE(status.isOk());
384 }
385 }
386 }
387}
388
389TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
390 binder::Status status;
391
392 // Repeat to ensure cleanup and recreation works correctly
393 for (int i = 0; i < 2; i++) {
394 for (int direction : XFRM_DIRECTIONS) {
395 for (int addrFamily : ADDRESS_FAMILIES) {
396 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700397 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700398 EXPECT_TRUE(status.isOk())
399 << " family: " << addrFamily << " direction: " << direction;
400 }
401 }
402
403 // Cleanup
404 for (int direction : XFRM_DIRECTIONS) {
405 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700406 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700407 EXPECT_TRUE(status.isOk());
408 }
409 }
410 }
411}
412
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900413TEST_F(BinderTest, XfrmControllerInit) {
Nathan Harold21299f72018-03-16 20:13:03 -0700414 netdutils::Status status;
415 status = XfrmController::Init();
416 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700417
418 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
419 // feature.
420 if (status.code() == EOPNOTSUPP) return;
421
Nathan Harold21299f72018-03-16 20:13:03 -0700422 ASSERT_TRUE(status.ok());
423
424 int32_t spi = 0;
425
426 ASSERT_TRUE(allocateIpSecResources(true, &spi));
427 ASSERT_TRUE(allocateIpSecResources(false, &spi));
428
429 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700430 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700431 ASSERT_TRUE(allocateIpSecResources(true, &spi));
432
433 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700434 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700435 SCOPED_TRACE(status);
436 ASSERT_TRUE(status.ok());
437
Benedict Wonga450e722018-05-07 10:29:02 -0700438 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700439 SCOPED_TRACE(status);
440 ASSERT_TRUE(status.ok());
441
442 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700443 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700444}
Nathan Harold2deff322018-05-10 14:03:48 -0700445#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700446
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900447static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900448 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900449
450 // Output looks like this:
451 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900452 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900453 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900454 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900455 //
456 // or:
457 //
458 // Chain bw_data_saver (1 references)
459 // target prot opt source destination
460 // ... possibly connectivity critical packet rules here ...
461 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900462
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900463 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900464
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900465 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
466 // Data saver disabled.
467 return 0;
468 }
469
470 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
471
472 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
473 // Data saver enabled.
474 return 1;
475 }
476
477 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900478}
479
480bool enableDataSaver(sp<INetd>& netd, bool enable) {
481 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
482 bool ret;
483 netd->bandwidthEnableDataSaver(enable, &ret);
484 return ret;
485}
486
487int getDataSaverState() {
488 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
489 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
490 EXPECT_EQ(enabled4, enabled6);
491 EXPECT_NE(-1, enabled4);
492 EXPECT_NE(-1, enabled6);
493 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
494 return -1;
495 }
496 return enabled6;
497}
498
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900499TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900500 const int wasEnabled = getDataSaverState();
501 ASSERT_NE(-1, wasEnabled);
502
503 if (wasEnabled) {
504 ASSERT_TRUE(enableDataSaver(mNetd, false));
505 EXPECT_EQ(0, getDataSaverState());
506 }
507
508 ASSERT_TRUE(enableDataSaver(mNetd, false));
509 EXPECT_EQ(0, getDataSaverState());
510
511 ASSERT_TRUE(enableDataSaver(mNetd, true));
512 EXPECT_EQ(1, getDataSaverState());
513
514 ASSERT_TRUE(enableDataSaver(mNetd, true));
515 EXPECT_EQ(1, getDataSaverState());
516
517 if (!wasEnabled) {
518 ASSERT_TRUE(enableDataSaver(mNetd, false));
519 EXPECT_EQ(0, getDataSaverState());
520 }
521}
Robin Leeb8087362016-03-30 18:43:08 +0100522
Luke Huang94658ac2018-10-18 19:35:12 +0900523static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
524 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100525 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100526 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100527 std::vector<std::string> rules = listIpRules(ipVersion);
528
529 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900530 std::string suffix =
531 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900532 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800533 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100534 return true;
535 }
536 }
537 return false;
538}
539
Luke Huang94658ac2018-10-18 19:35:12 +0900540static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
541 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100542 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
543 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
544 EXPECT_EQ(existsIp4, existsIp6);
545 return existsIp4;
546}
547
Luke Huang94658ac2018-10-18 19:35:12 +0900548namespace {
549
550UidRangeParcel makeUidRangeParcel(int start, int stop) {
551 UidRangeParcel res;
552 res.start = start;
553 res.stop = stop;
554
555 return res;
556}
557
558} // namespace
559
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900560TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800561 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
562 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
563 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900564 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
565 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900566
567 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
568 EXPECT_EQ(EBUSY,
569 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
570
571 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
572 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
573 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800574 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900575}
576
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900577TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900578 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
579
cken67cd14c2018-12-05 17:26:59 +0900580 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
581 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900582 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
583
Luke Huang94658ac2018-10-18 19:35:12 +0900584 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
585 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
586 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900587 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
588
589 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
590
591 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
592 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
593 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
594 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
595
596 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
597 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
598 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
599 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
600
601 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
602}
603
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900604TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100605 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100606
Luke Huang94658ac2018-10-18 19:35:12 +0900607 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
608 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100609
610 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
611 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
612
613 // Create two valid rules.
614 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
615 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
616 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
617 for (auto const& range : uidRanges) {
618 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
619 }
620
621 // Remove the rules.
622 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
623 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
624 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
625 for (auto const& range : uidRanges) {
626 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
627 }
628
629 // Fail to remove the rules a second time after they are already deleted.
630 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
631 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
632 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
633
634 // All rules should be the same as before.
635 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
636 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
637}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900638
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900639// Create a socket pair that isLoopbackSocket won't think is local.
640void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900641 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900642 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900643 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
644
645 socklen_t addrlen = sizeof(server6);
646 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
647 ASSERT_EQ(0, listen(*serverSocket, 10));
648
Bernie Innocentif6918262018-06-11 17:37:35 +0900649 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900650 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900651 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900652 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
653 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
654
Bernie Innocentif6918262018-06-11 17:37:35 +0900655 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900656 ASSERT_NE(-1, *acceptedSocket);
657
658 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
659}
660
661void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
662 char buf[4096];
663 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
664 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
665 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
666}
667
668void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
669 // Check that the client socket was closed with ECONNABORTED.
670 int ret = write(clientSocket, "foo", sizeof("foo"));
671 int err = errno;
672 EXPECT_EQ(-1, ret);
673 EXPECT_EQ(ECONNABORTED, err);
674
675 // Check that it sent a RST to the server.
676 ret = write(acceptedSocket, "foo", sizeof("foo"));
677 err = errno;
678 EXPECT_EQ(-1, ret);
679 EXPECT_EQ(ECONNRESET, err);
680}
681
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900682TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900683 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900684 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900685
686 // Pick a random UID in the system UID range.
687 constexpr int baseUid = AID_APP - 2000;
688 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
689 int uid = baseUid + 500 + arc4random_uniform(1000);
690 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
691
692 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900693 std::vector<UidRangeParcel> uidRanges = {
694 makeUidRangeParcel(baseUid + 42, baseUid + 449),
695 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
696 makeUidRangeParcel(baseUid + 498, uid - 1),
697 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900698 };
699 // A skip list that doesn't contain UID.
700 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
701
702 // Close sockets. Our test socket should be intact.
703 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
704 checkSocketpairOpen(clientSocket, acceptedSocket);
705
706 // UID ranges that do contain uid.
707 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900708 makeUidRangeParcel(baseUid + 42, baseUid + 449),
709 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
710 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900711 };
712 // Add uid to the skip list.
713 skipUids.push_back(uid);
714
715 // Close sockets. Our test socket should still be intact because it's in the skip list.
716 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
717 checkSocketpairOpen(clientSocket, acceptedSocket);
718
719 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
720 skipUids.resize(skipUids.size() - 1);
721 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
722 checkSocketpairClosed(clientSocket, acceptedSocket);
723
724 close(clientSocket);
725 close(serverSocket);
726 close(acceptedSocket);
727}
Erik Klinecc4f2732016-08-03 11:24:27 +0900728
729namespace {
730
731int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
732 if (buf == nullptr) return -1;
733
734 int prefixLength = 0;
735 bool endOfContiguousBits = false;
736 for (unsigned int i = 0; i < buflen; i++) {
737 const uint8_t value = buf[i];
738
739 // Bad bit sequence: check for a contiguous set of bits from the high
740 // end by verifying that the inverted value + 1 is a power of 2
741 // (power of 2 iff. (v & (v - 1)) == 0).
742 const uint8_t inverse = ~value + 1;
743 if ((inverse & (inverse - 1)) != 0) return -1;
744
745 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
746
747 // Bogus netmask.
748 if (endOfContiguousBits && value != 0) return -1;
749
750 if (value != 0xff) endOfContiguousBits = true;
751 }
752
753 return prefixLength;
754}
755
756template<typename T>
757int netmaskToPrefixLength(const T *p) {
758 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
759}
760
761
762static bool interfaceHasAddress(
763 const std::string &ifname, const char *addrString, int prefixLength) {
764 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900765
766 const struct addrinfo hints = {
767 .ai_flags = AI_NUMERICHOST,
768 .ai_family = AF_UNSPEC,
769 .ai_socktype = SOCK_DGRAM,
770 };
771 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
772 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
773 return false;
774 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900775 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900776
777 struct ifaddrs *ifaddrsList = nullptr;
778 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
779
780 if (getifaddrs(&ifaddrsList) != 0) {
781 return false;
782 }
783
784 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
785 if (std::string(addr->ifa_name) != ifname ||
786 addr->ifa_addr == nullptr ||
787 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
788 continue;
789 }
790
791 switch (addr->ifa_addr->sa_family) {
792 case AF_INET: {
793 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
794 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
795 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
796 continue;
797 }
798
799 if (prefixLength < 0) return true; // not checking prefix lengths
800
801 if (addr->ifa_netmask == nullptr) return false;
802 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
803 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
804 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
805 }
806 case AF_INET6: {
807 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
808 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
809 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
810 continue;
811 }
812
813 if (prefixLength < 0) return true; // not checking prefix lengths
814
815 if (addr->ifa_netmask == nullptr) return false;
816 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
817 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
818 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
819 }
820 default:
821 // Cannot happen because we have already screened for matching
822 // address families at the top of each iteration.
823 continue;
824 }
825 }
826
827 return false;
828}
829
830} // namespace
831
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900832TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900833 static const struct TestData {
834 const char *addrString;
835 const int prefixLength;
836 const bool expectSuccess;
837 } kTestData[] = {
838 { "192.0.2.1", 24, true },
839 { "192.0.2.2", 25, true },
840 { "192.0.2.3", 32, true },
841 { "192.0.2.4", 33, false },
842 { "192.not.an.ip", 24, false },
843 { "2001:db8::1", 64, true },
844 { "2001:db8::2", 65, true },
845 { "2001:db8::3", 128, true },
846 { "2001:db8::4", 129, false },
847 { "foo:bar::bad", 64, false },
848 };
849
Sehee Park8659b8d2018-11-16 10:53:16 +0900850 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900851 const auto &td = kTestData[i];
852
853 // [1.a] Add the address.
854 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900855 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900856 if (td.expectSuccess) {
857 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
858 } else {
859 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
860 ASSERT_NE(0, status.serviceSpecificErrorCode());
861 }
862
863 // [1.b] Verify the addition meets the expectation.
864 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900865 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900866 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900867 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900868 }
869
870 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900871 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900872 if (td.expectSuccess) {
873 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
874 } else {
875 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
876 ASSERT_NE(0, status.serviceSpecificErrorCode());
877 }
878
879 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900880 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900881 }
882}
Erik Kline55b06f82016-07-04 09:57:18 +0900883
Erik Kline38e51f12018-09-06 20:14:44 +0900884TEST_F(BinderTest, GetProcSysNet) {
885 const char LOOPBACK[] = "lo";
886 static const struct {
887 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900888 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900889 const char* ifname;
890 const char* parameter;
891 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900892 const int expectedReturnCode;
893 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900894 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
895 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
896 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
897 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
898 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
899 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
900 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900901 };
902
Sehee Park8659b8d2018-11-16 10:53:16 +0900903 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900904 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900905
Erik Kline38e51f12018-09-06 20:14:44 +0900906 std::string value;
907 const binder::Status status =
908 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
909
910 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900911 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900912 EXPECT_EQ(0, status.exceptionCode());
913 EXPECT_EQ(0, status.serviceSpecificErrorCode());
914 EXPECT_EQ(td.expectedValue, value);
915 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900916 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900917 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
918 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
919 }
920 }
921}
922
923TEST_F(BinderTest, SetProcSysNet) {
924 static const struct {
925 const int ipversion;
926 const int which;
927 const char* ifname;
928 const char* parameter;
929 const char* value;
930 const int expectedReturnCode;
931 } kTestData[] = {
932 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
933 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
934 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
935 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
936 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
937 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
938 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
939 };
940
Sehee Park8659b8d2018-11-16 10:53:16 +0900941 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900942 const auto& td = kTestData[i];
943
944 const binder::Status status =
945 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900946
947 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900948 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900949 EXPECT_EQ(0, status.exceptionCode());
950 EXPECT_EQ(0, status.serviceSpecificErrorCode());
951 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900952 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900953 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
954 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
955 }
956 }
957}
Ben Schwartze7601812017-04-28 16:38:29 -0400958
Erik Kline38e51f12018-09-06 20:14:44 +0900959TEST_F(BinderTest, GetSetProcSysNet) {
960 const int ipversion = INetd::IPV6;
961 const int category = INetd::NEIGH;
962 const std::string& tun = sTun.name();
963 const std::string parameter("ucast_solicit");
964
965 std::string value{};
966 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
967 EXPECT_FALSE(value.empty());
968 const int ival = std::stoi(value);
969 EXPECT_GT(ival, 0);
970 // Try doubling the parameter value (always best!).
971 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
972 .isOk());
973 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
974 EXPECT_EQ(2 * ival, std::stoi(value));
975 // Try resetting the parameter.
976 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
977 .isOk());
978 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
979 EXPECT_EQ(ival, std::stoi(value));
980}
981
Ben Schwartze7601812017-04-28 16:38:29 -0400982static std::string base64Encode(const std::vector<uint8_t>& input) {
983 size_t out_len;
984 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
985 // out_len includes the trailing NULL.
986 uint8_t output_bytes[out_len];
987 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
988 return std::string(reinterpret_cast<char*>(output_bytes));
989}
990
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900991TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900992 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400993 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400994 std::vector<uint8_t> short_fp(1);
995 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
996 std::vector<std::string> test_domains;
997 std::vector<int> test_params = { 300, 25, 8, 8 };
998 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400999 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001000 const std::vector<std::string> servers;
1001 const std::string tlsName;
1002 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -04001003 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +09001004 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001005 { {"192.0.2.1"}, "", {}, 0 },
1006 { {"2001:db8::2"}, "host.name", {}, 0 },
1007 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
1008 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +09001009 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001010 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +09001011 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001012 { {"2001:dg8::6"}, "", {}, EINVAL },
1013 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
1014 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
1015 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
1016 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -04001017 };
1018
Sehee Park8659b8d2018-11-16 10:53:16 +09001019 for (size_t i = 0; i < std::size(kTlsTestData); i++) {
Erik Klinea1476fb2018-03-04 21:01:56 +09001020 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -04001021
1022 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001023 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -04001024 fingerprints.push_back(base64Encode(fingerprint));
1025 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001026 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001027 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
1028 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -04001029
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001030 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +09001031 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Ben Schwartze7601812017-04-28 16:38:29 -04001032 SCOPED_TRACE(status.toString8());
1033 EXPECT_EQ(0, status.exceptionCode());
1034 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +09001035 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Ben Schwartze7601812017-04-28 16:38:29 -04001036 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001037 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -04001038 }
Ben Schwartze7601812017-04-28 16:38:29 -04001039 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001040 // Ensure TLS is disabled before the start of the next test.
1041 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001042 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1043 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001044}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001045
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001046namespace {
1047
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001048void expectNoTestCounterRules() {
1049 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1050 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1051 std::string allRules = Join(runCommand(command), "\n");
1052 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1053 }
1054}
1055
Bernie Innocentif6918262018-06-11 17:37:35 +09001056void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1057 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001058 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1059 path, if1.c_str(), if2.c_str(), pkt, byte));
1060}
1061
Bernie Innocentif6918262018-06-11 17:37:35 +09001062void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001063 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1064 path, if1.c_str(), if2.c_str()));
1065 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1066 path, if2.c_str(), if1.c_str()));
1067}
1068
Luke Huangcaebcbb2018-09-27 20:37:14 +08001069std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1070 const std::string& iface) {
1071 for (auto& stats : statsVec) {
1072 if (stats.iface == iface) {
1073 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1074 }
1075 }
1076 return {};
1077}
1078
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001079} // namespace
1080
1081TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001082 expectNoTestCounterRules();
1083
1084 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1085 // disabling tethering. We don't check the return value because these commands will fail if
1086 // tethering is already enabled.
1087 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1088 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1089
1090 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1091 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1092 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1093 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1094 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1095
1096 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1097 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1098 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1099 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1100 // RX is from external to internal, and TX is from internal to external.
1101 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1102 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1103
1104 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1105 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1106
1107 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1108 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1109
1110 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1111 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1112 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1113
Luke Huangcaebcbb2018-09-27 20:37:14 +08001114 std::vector<TetherStatsParcel> statsVec;
1115 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001116 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1117
Luke Huangcaebcbb2018-09-27 20:37:14 +08001118 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001119
Luke Huangcaebcbb2018-09-27 20:37:14 +08001120 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001121
1122 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1123 delTetherCounterValues(path, intIface1, extIface1);
1124 delTetherCounterValues(path, intIface2, extIface2);
1125 if (path == IP6TABLES_PATH) {
1126 delTetherCounterValues(path, intIface3, extIface2);
1127 }
1128 }
1129
1130 expectNoTestCounterRules();
1131}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001132
Luke Huang0051a622018-07-23 20:30:16 +08001133namespace {
1134
Luke Huanga5211072018-08-01 23:36:29 +08001135constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1136constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001137
1138static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1139 const char* chainName) {
1140 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1141 return runCommand(command);
1142}
1143
Luke Huang19b49c52018-10-22 12:12:05 +09001144// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001145bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001146 const std::string& expectedInterface,
1147 const std::string& expectedRule, const char* table) {
1148 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1149 for (const auto& rule : rules) {
1150 if (rule.find(expectedInterface) != std::string::npos) {
1151 if (rule.find(expectedRule) != std::string::npos) {
1152 return true;
1153 }
1154 }
1155 }
1156 return false;
1157}
1158
1159void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001160 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001161 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001162 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001163 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001164 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1165 IdletimerRule, RAW_TABLE));
1166 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001167 ifname, IdletimerRule, MANGLE_TABLE));
1168 }
1169}
1170
1171void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001172 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001173 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001174 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001175 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001176 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1177 IdletimerRule, RAW_TABLE));
1178 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001179 ifname, IdletimerRule, MANGLE_TABLE));
1180 }
1181}
1182
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001183} // namespace
1184
1185TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001186 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1187 // rule in the table. Because we only check the result after calling remove function. We might
1188 // check the actual rule which is removed by our function (maybe compare the results between
1189 // calling function before and after)
1190 binder::Status status;
1191 const struct TestData {
1192 const std::string ifname;
1193 int32_t timeout;
1194 const std::string classLabel;
1195 } idleTestData[] = {
1196 {"wlan0", 1234, "happyday"},
1197 {"rmnet_data0", 4567, "friday"},
1198 };
1199 for (const auto& td : idleTestData) {
1200 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1201 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1202 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1203
1204 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1205 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1206 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1207 }
1208}
1209
Luke Huanga67dd562018-07-17 19:58:25 +08001210namespace {
1211
1212constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1213constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1214
1215void expectStrictSetUidAccept(const int uid) {
1216 std::string uidRule = StringPrintf("owner UID match %u", uid);
1217 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1218 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1219 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1220 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1221 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1222 }
1223}
1224
1225void expectStrictSetUidLog(const int uid) {
1226 static const char logRule[] = "st_penalty_log all";
1227 std::string uidRule = StringPrintf("owner UID match %u", uid);
1228 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1229 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1230 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1231 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1232 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1233 }
1234}
1235
1236void expectStrictSetUidReject(const int uid) {
1237 static const char rejectRule[] = "st_penalty_reject all";
1238 std::string uidRule = StringPrintf("owner UID match %u", uid);
1239 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1240 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1241 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1242 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1243 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1244 }
1245}
1246
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001247} // namespace
1248
1249TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001250 binder::Status status;
1251 int32_t uid = randomUid();
1252
1253 // setUidCleartextPenalty Policy:Log with randomUid
1254 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1255 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1256 expectStrictSetUidLog(uid);
1257
1258 // setUidCleartextPenalty Policy:Accept with randomUid
1259 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1260 expectStrictSetUidAccept(uid);
1261
1262 // setUidCleartextPenalty Policy:Reject with randomUid
1263 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1264 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1265 expectStrictSetUidReject(uid);
1266
1267 // setUidCleartextPenalty Policy:Accept with randomUid
1268 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1269 expectStrictSetUidAccept(uid);
1270
1271 // test wrong policy
1272 int32_t wrongPolicy = -123;
1273 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1274 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1275}
1276
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001277namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001278
Luke Huanga5211072018-08-01 23:36:29 +08001279bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001280 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1281 return (runCommand(cmd.c_str()).size()) ? true : false;
1282}
1283
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001284} // namespace
1285
1286TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001287 binder::Status status;
1288 // use dummy0 for test since it is set ready
1289 static const char testIf[] = "dummy0";
1290 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1291
1292 status = mNetd->clatdStart(testIf);
1293 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1294 EXPECT_TRUE(processExists(clatdName));
1295
1296 mNetd->clatdStop(testIf);
1297 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1298 EXPECT_FALSE(processExists(clatdName));
1299}
Luke Huang457d4702018-08-16 15:39:15 +08001300
1301namespace {
1302
1303bool getIpfwdV4Enable() {
1304 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1305 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1306 EXPECT_TRUE(!result.empty());
1307 int v4Enable = std::stoi(result[0]);
1308 return v4Enable;
1309}
1310
1311bool getIpfwdV6Enable() {
1312 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1313 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1314 EXPECT_TRUE(!result.empty());
1315 int v6Enable = std::stoi(result[0]);
1316 return v6Enable;
1317}
1318
1319void expectIpfwdEnable(bool enable) {
1320 int enableIPv4 = getIpfwdV4Enable();
1321 int enableIPv6 = getIpfwdV6Enable();
1322 EXPECT_EQ(enable, enableIPv4);
1323 EXPECT_EQ(enable, enableIPv6);
1324}
1325
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001326bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001327 std::vector<std::string> rules = listIpRules(ipVersion);
1328 for (const auto& rule : rules) {
1329 if (rule.find(ipfwdRule) != std::string::npos) {
1330 return true;
1331 }
1332 }
1333 return false;
1334}
1335
1336void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1337 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1338
1339 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1340 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1341 }
1342}
1343
1344void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1345 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1346
1347 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1348 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1349 }
1350}
1351
1352} // namespace
1353
1354TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1355 // Netd default enable Ipfwd with requester NetdHwService
1356 const std::string defaultRequester = "NetdHwService";
1357
1358 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1359 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1360 expectIpfwdEnable(false);
1361
1362 bool ipfwdEnabled;
1363 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1364 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1365 EXPECT_FALSE(ipfwdEnabled);
1366
1367 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1368 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1369 expectIpfwdEnable(true);
1370
1371 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1372 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1373 EXPECT_TRUE(ipfwdEnabled);
1374}
1375
1376TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1377 static const char testFromIf[] = "dummy0";
1378 static const char testToIf[] = "dummy0";
1379
1380 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1381 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1382 expectIpfwdRuleExists(testFromIf, testToIf);
1383
1384 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1385 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1386 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001387}
Luke Huang531f5d32018-08-03 15:19:05 +08001388
1389namespace {
1390
1391constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1392constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1393constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1394constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1395constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001396constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001397
Luke Huang19b49c52018-10-22 12:12:05 +09001398// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1399// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001400bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1401 const char* chainName, const std::string& expectedTargetA,
1402 const std::string& expectedTargetB) {
1403 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1404 int matchCount = 0;
1405
1406 for (const auto& rule : rules) {
1407 if (rule.find(expectedTargetA) != std::string::npos) {
1408 if (rule.find(expectedTargetB) != std::string::npos) {
1409 matchCount++;
1410 }
1411 }
1412 }
1413 return matchCount == expectedCount;
1414}
1415
1416void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1417 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1418 std::string result = "";
1419
1420 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001421 // Quota value might be decreased while matching packets
1422 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001423}
1424
1425void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1426 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1427 std::string quotaRule = StringPrintf("quota %s", ifname);
1428
1429 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1430 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1431 BANDWIDTH_COSTLY_IF));
1432 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1433 BANDWIDTH_COSTLY_IF));
1434 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1435 BANDWIDTH_COSTLY_IF));
1436 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1437 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1438 }
1439 expectXtQuotaValueEqual(ifname, quotaBytes);
1440}
1441
1442void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1443 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1444 std::string quotaRule = StringPrintf("quota %s", ifname);
1445
1446 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1447 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1448 BANDWIDTH_COSTLY_IF));
1449 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1450 BANDWIDTH_COSTLY_IF));
1451 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1452 BANDWIDTH_COSTLY_IF));
1453 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1454 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1455 }
1456}
1457
1458void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1459 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1460 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1461 std::string alertName = StringPrintf("%sAlert", ifname);
1462
1463 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1464 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1465 }
1466 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1467}
1468
1469void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1470 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1471 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1472
1473 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1474 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1475 }
1476}
1477
1478void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1479 static const char globalAlertRule[] = "quota globalAlert";
1480 static const char globalAlertName[] = "globalAlert";
1481
1482 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001483 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001484 }
1485 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1486}
1487
1488void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1489 std::string uidRule = StringPrintf("owner UID match %u", uid);
1490
1491 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1492 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1493 }
1494}
1495
1496void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1497 std::string uidRule = StringPrintf("owner UID match %u", uid);
1498
1499 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1500 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1501 }
1502}
1503
1504} // namespace
1505
1506TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1507 long testQuotaBytes = 5550;
1508
1509 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001510 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001511 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1512
1513 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1514 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1515 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1516
1517 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1518 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1519 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1520
1521 // Remove test physical network
1522 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1523}
1524
1525TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1526 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001527 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001528 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001529 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001530 // Need to have a prior interface quota set to set an alert
1531 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1532 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1533 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1534 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1535
1536 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1537 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1538 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1539
1540 // Remove interface quota
1541 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1542 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1543 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1544
1545 // Remove test physical network
1546 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1547}
1548
1549TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1550 long testAlertBytes = 2097149;
1551
1552 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1553 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1554 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1555
1556 testAlertBytes = 2097152;
1557 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1558 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1559 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1560}
1561
1562TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1563 SKIP_IF_BPF_SUPPORTED;
1564
1565 int32_t uid = randomUid();
1566 static const char targetReject[] = "REJECT";
1567 static const char targetReturn[] = "RETURN";
1568
1569 // add NaughtyApp
1570 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1571 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1572 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1573
1574 // remove NaughtyApp
1575 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1576 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1577 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1578
1579 // add NiceApp
1580 status = mNetd->bandwidthAddNiceApp(uid);
1581 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1582 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1583
1584 // remove NiceApp
1585 status = mNetd->bandwidthRemoveNiceApp(uid);
1586 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1587 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1588}
Luke Huangb5733d72018-08-21 17:17:19 +08001589
1590namespace {
1591
Luke Huangb670d162018-08-23 20:01:13 +08001592std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1593 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1594 return runCommand(command);
1595}
1596
Luke Huangc3252cc2018-10-16 15:43:23 +08001597bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001598 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1599 for (const auto& route : routes) {
1600 if (route.find(ipRoute) != std::string::npos) {
1601 return true;
1602 }
1603 }
1604 return false;
1605}
1606
Luke Huangc3252cc2018-10-16 15:43:23 +08001607std::string ipRouteString(const std::string& ifName, const std::string& dst,
1608 const std::string& nextHop) {
1609 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1610
1611 if (!nextHop.empty()) {
1612 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001613 }
1614
Luke Huangc3252cc2018-10-16 15:43:23 +08001615 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001616}
1617
Luke Huangc3252cc2018-10-16 15:43:23 +08001618void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1619 const std::string& dst, const std::string& nextHop,
1620 const char* table) {
1621 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1622}
1623
1624void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001625 const std::string& dst, const std::string& nextHop,
1626 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001627 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001628}
1629
1630bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1631 std::vector<std::string> rules = listIpRules(ipVersion);
1632 for (const auto& rule : rules) {
1633 if (rule.find(ipRule) != std::string::npos) {
1634 return true;
1635 }
1636 }
1637 return false;
1638}
1639
1640void expectNetworkDefaultIpRuleExists(const char* ifName) {
1641 std::string networkDefaultRule =
1642 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1643
1644 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1645 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1646 }
1647}
1648
1649void expectNetworkDefaultIpRuleDoesNotExist() {
1650 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1651
1652 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1653 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1654 }
1655}
1656
1657void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1658 std::string networkPermissionRule = "";
1659 switch (permission) {
1660 case INetd::PERMISSION_NONE:
1661 networkPermissionRule = StringPrintf(
1662 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1663 break;
1664 case INetd::PERMISSION_NETWORK:
1665 networkPermissionRule = StringPrintf(
1666 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1667 break;
1668 case INetd::PERMISSION_SYSTEM:
1669 networkPermissionRule = StringPrintf(
1670 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1671 break;
1672 }
1673
1674 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1675 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1676 }
1677}
1678
1679// TODO: It is a duplicate function, need to remove it
1680bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1681 const std::string& expectedInterface,
1682 const std::string& expectedRule,
1683 const char* table) {
1684 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1685 for (const auto& rule : rules) {
1686 if (rule.find(expectedInterface) != std::string::npos) {
1687 if (rule.find(expectedRule) != std::string::npos) {
1688 return true;
1689 }
1690 }
1691 }
1692 return false;
1693}
1694
1695void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1696 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1697 std::string networkIncomingPacketMarkRule = "";
1698 switch (permission) {
1699 case INetd::PERMISSION_NONE:
1700 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1701 break;
1702 case INetd::PERMISSION_NETWORK:
1703 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1704 break;
1705 case INetd::PERMISSION_SYSTEM:
1706 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1707 break;
1708 }
1709
1710 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1711 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1712 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1713 }
1714}
1715
1716} // namespace
1717
1718TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001719 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001720 const char* ipVersion;
1721 const char* testDest;
1722 const char* testNextHop;
1723 const bool expectSuccess;
1724 } kTestData[] = {
1725 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001726 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1727 {IP_RULE_V4, "10.251.0.0/16", "", true},
1728 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1729 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001730 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001731 {IP_RULE_V6, "::/0", "2001:db8::", true},
1732 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001733 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1734 };
1735
Luke Huangc3252cc2018-10-16 15:43:23 +08001736 static const struct {
1737 const char* ipVersion;
1738 const char* testDest;
1739 const char* testNextHop;
1740 } kTestDataWithNextHop[] = {
1741 {IP_RULE_V4, "10.251.10.0/30", ""},
1742 {IP_RULE_V6, "2001:db8::/32", ""},
1743 };
1744
Luke Huangb670d162018-08-23 20:01:13 +08001745 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001746 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001747 const int testUid = randomUid();
1748 const std::vector<int32_t> testUids = {testUid};
1749
1750 // Add test physical network
1751 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1752 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1753
Luke Huangc3252cc2018-10-16 15:43:23 +08001754 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001755 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001756 const auto& td = kTestDataWithNextHop[i];
1757
1758 // All route for test tun will disappear once the tun interface is deleted.
1759 binder::Status status =
1760 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1761 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1762 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1763 sTun.name().c_str());
1764
1765 // Add system permission for test uid, setup route in legacy system table.
1766 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1767
1768 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1769 testUid);
1770 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1771 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1772 testTableLegacySystem);
1773
1774 // Remove system permission for test uid, setup route in legacy network table.
1775 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1776
1777 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1778 testUid);
1779 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1780 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1781 testTableLegacyNetwork);
1782 }
1783
Sehee Park8659b8d2018-11-16 10:53:16 +09001784 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001785 const auto& td = kTestData[i];
1786
1787 binder::Status status =
1788 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1789 if (td.expectSuccess) {
1790 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001791 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001792 sTun.name().c_str());
1793 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001794 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1795 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001796 }
1797
1798 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1799 if (td.expectSuccess) {
1800 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001801 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1802 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001803 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001804 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1805 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001806 }
1807
Luke Huangc3252cc2018-10-16 15:43:23 +08001808 // Add system permission for test uid, route will be added into legacy system table.
1809 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001810
1811 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1812 testUid);
1813 if (td.expectSuccess) {
1814 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001815 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001816 testTableLegacySystem);
1817 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001818 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1819 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001820 }
1821
1822 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1823 td.testNextHop, testUid);
1824 if (td.expectSuccess) {
1825 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001826 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1827 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001828 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001829 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1830 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001831 }
1832
Luke Huangc3252cc2018-10-16 15:43:23 +08001833 // Remove system permission for test uid, route will be added into legacy network table.
1834 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1835
1836 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1837 testUid);
1838 if (td.expectSuccess) {
1839 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1840 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1841 testTableLegacyNetwork);
1842 } else {
1843 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1844 EXPECT_NE(0, status.serviceSpecificErrorCode());
1845 }
1846
1847 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1848 td.testNextHop, testUid);
1849 if (td.expectSuccess) {
1850 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1851 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1852 testTableLegacyNetwork);
1853 } else {
1854 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1855 EXPECT_NE(0, status.serviceSpecificErrorCode());
1856 }
Luke Huangb670d162018-08-23 20:01:13 +08001857 }
1858
1859 // Remove test physical network
1860 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1861}
1862
1863TEST_F(BinderTest, NetworkPermissionDefault) {
1864 // Add test physical network
1865 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1866 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1867
Luke Huangc3252cc2018-10-16 15:43:23 +08001868 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001869 int currentNetid;
1870 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1871 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1872
1873 // Test SetDefault
1874 status = mNetd->networkSetDefault(TEST_NETID1);
1875 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1876 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1877
1878 status = mNetd->networkClearDefault();
1879 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1880 expectNetworkDefaultIpRuleDoesNotExist();
1881
1882 // Add default network back
1883 status = mNetd->networkSetDefault(currentNetid);
1884 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1885
1886 // Test SetPermission
1887 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1888 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1889 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1890 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1891
1892 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1893 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1894 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1895 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1896
1897 // Remove test physical network
1898 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1899}
1900
1901TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1902 const int testUid = randomUid();
1903 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1904 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1905 bool ret = false;
1906 status = mNetd->networkCanProtect(testUid, &ret);
1907 EXPECT_TRUE(ret);
1908
1909 status = mNetd->networkSetProtectDeny(testUid);
1910 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1911 status = mNetd->networkCanProtect(testUid, &ret);
1912 EXPECT_FALSE(ret);
1913}
1914
1915namespace {
1916
Luke Huangb5733d72018-08-21 17:17:19 +08001917int readIntFromPath(const std::string& path) {
1918 std::string result = "";
1919 EXPECT_TRUE(ReadFileToString(path, &result));
1920 return std::stoi(result);
1921}
1922
1923int getTetherAcceptIPv6Ra(const std::string& ifName) {
1924 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1925 return readIntFromPath(path);
1926}
1927
1928bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1929 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1930 return readIntFromPath(path);
1931}
1932
1933int getTetherIPv6DadTransmits(const std::string& ifName) {
1934 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1935 return readIntFromPath(path);
1936}
1937
1938bool getTetherEnableIPv6(const std::string& ifName) {
1939 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1940 int disableIPv6 = readIntFromPath(path);
1941 return !disableIPv6;
1942}
1943
1944bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1945 for (const auto& iface : ifList) {
1946 if (iface == ifName) {
1947 return true;
1948 }
1949 }
1950 return false;
1951}
1952
1953void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1954 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1955 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1956 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1957 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1958}
1959
1960void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1961 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1962 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1963 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1964 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1965}
1966
1967void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1968 const std::string& ifName) {
1969 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1970}
1971
1972void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1973 const std::string& ifName) {
1974 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1975}
1976
1977void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
1978 const std::vector<std::string>& testDnsAddrs) {
1979 EXPECT_TRUE(dnsList == testDnsAddrs);
1980}
1981
1982} // namespace
1983
1984TEST_F(BinderTest, TetherStartStopStatus) {
1985 std::vector<std::string> noDhcpRange = {};
1986 static const char dnsdName[] = "dnsmasq";
1987
1988 binder::Status status = mNetd->tetherStart(noDhcpRange);
1989 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1990 EXPECT_TRUE(processExists(dnsdName));
1991
1992 bool tetherEnabled;
1993 status = mNetd->tetherIsEnabled(&tetherEnabled);
1994 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1995 EXPECT_TRUE(tetherEnabled);
1996
1997 status = mNetd->tetherStop();
1998 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1999 EXPECT_FALSE(processExists(dnsdName));
2000
2001 status = mNetd->tetherIsEnabled(&tetherEnabled);
2002 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2003 EXPECT_FALSE(tetherEnabled);
2004}
2005
2006TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2007 // TODO: verify if dnsmasq update interface successfully
2008
2009 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2010 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2011 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2012
2013 std::vector<std::string> ifList;
2014 status = mNetd->tetherInterfaceList(&ifList);
2015 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2016 expectTetherInterfaceExists(ifList, sTun.name());
2017
2018 status = mNetd->tetherInterfaceRemove(sTun.name());
2019 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2020 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2021
2022 status = mNetd->tetherInterfaceList(&ifList);
2023 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2024 expectTetherInterfaceNotExists(ifList, sTun.name());
2025}
2026
2027TEST_F(BinderTest, TetherDnsSetList) {
2028 // TODO: verify if dnsmasq update dns successfully
2029 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
2030
2031 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2032 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2033
2034 std::vector<std::string> dnsList;
2035 status = mNetd->tetherDnsList(&dnsList);
2036 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2037 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002038}
2039
2040namespace {
2041
2042constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2043constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2044constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2045constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2046constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2047constexpr char FIREWALL_STANDBY[] = "fw_standby";
2048constexpr char targetReturn[] = "RETURN";
2049constexpr char targetDrop[] = "DROP";
2050
2051void expectFirewallWhitelistMode() {
2052 static const char dropRule[] = "DROP all";
2053 static const char rejectRule[] = "REJECT all";
2054 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2055 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2056 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2057 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2058 }
2059}
2060
2061void expectFirewallBlacklistMode() {
2062 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2063 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2064 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2065 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2066 }
2067}
2068
2069bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2070 const std::string& expectedInterface,
2071 const std::string& expectedRule) {
2072 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2073 // Expected rule:
2074 // Chain fw_INPUT (1 references)
2075 // pkts bytes target prot opt in out source destination
2076 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2077 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2078 int firstRuleIndex = 2;
2079 if (rules.size() < 4) return false;
2080 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2081 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2082 return true;
2083 }
2084 }
2085 return false;
2086}
2087
2088// TODO: It is a duplicate function, need to remove it
2089bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2090 const std::string& expectedInterface,
2091 const std::string& expectedRule) {
2092 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2093 for (const auto& rule : rules) {
2094 if (rule.find(expectedInterface) != std::string::npos) {
2095 if (rule.find(expectedRule) != std::string::npos) {
2096 return true;
2097 }
2098 }
2099 }
2100 return false;
2101}
2102
2103void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2104 static const char returnRule[] = "RETURN all";
2105 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2106 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2107 returnRule));
2108 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2109 returnRule));
2110 }
2111}
2112
2113void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2114 static const char returnRule[] = "RETURN all";
2115 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2116 EXPECT_FALSE(
2117 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2118 EXPECT_FALSE(
2119 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2120 }
2121}
2122
2123bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2124 const std::string& expectedTarget,
2125 const std::string& expectedRule) {
2126 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2127 int firstRuleIndex = 2;
2128 if (rules.size() < 4) return false;
2129 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2130 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2131 return true;
2132 }
2133 }
2134 return false;
2135}
2136
2137bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2138 const std::string& expectedTarget,
2139 const std::string& expectedRule) {
2140 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2141 int lastRuleIndex = rules.size() - 1;
2142 if (lastRuleIndex < 0) return false;
2143 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2144 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2145 return true;
2146 }
2147 }
2148 return false;
2149}
2150
2151void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2152 std::string uidRule = StringPrintf("owner UID match %u", uid);
2153 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2154 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2155}
2156
2157void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2158 std::string uidRule = StringPrintf("owner UID match %u", uid);
2159 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2160 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2161}
2162
2163void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2164 std::string uidRule = StringPrintf("owner UID match %u", uid);
2165 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2166 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2167}
2168
2169void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2170 std::string uidRule = StringPrintf("owner UID match %u", uid);
2171 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2172 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2173}
2174
2175bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2176 std::vector<std::string> inputRules =
2177 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2178 std::vector<std::string> outputRules =
2179 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2180 int inputLastRuleIndex = inputRules.size() - 1;
2181 int outputLastRuleIndex = outputRules.size() - 1;
2182
2183 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2184 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2185 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2186 return true;
2187 }
2188 }
2189 return false;
2190}
2191
2192void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2193 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2194 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2195}
2196
2197void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2198 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2199 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2200 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2201 }
2202}
2203
2204} // namespace
2205
2206TEST_F(BinderTest, FirewallSetFirewallType) {
2207 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2208 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2209 expectFirewallWhitelistMode();
2210
2211 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2212 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2213 expectFirewallBlacklistMode();
2214
2215 // set firewall type blacklist twice
2216 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2217 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2218 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2219 expectFirewallBlacklistMode();
2220
2221 // set firewall type whitelist twice
2222 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2223 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2224 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2225 expectFirewallWhitelistMode();
2226
2227 // reset firewall type to default
2228 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2229 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2230 expectFirewallBlacklistMode();
2231}
2232
2233TEST_F(BinderTest, FirewallSetInterfaceRule) {
2234 // setinterfaceRule is not supported in BLACKLIST MODE
2235 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2236 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2237
2238 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2239 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2240
2241 // set WHITELIST mode first
2242 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2243 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2244
2245 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2246 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2247 expectFirewallInterfaceRuleAllowExists(sTun.name());
2248
2249 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2250 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2251 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2252
2253 // reset firewall mode to default
2254 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2255 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2256 expectFirewallBlacklistMode();
2257}
2258
2259TEST_F(BinderTest, FirewallSetUidRule) {
2260 SKIP_IF_BPF_SUPPORTED;
2261
2262 int32_t uid = randomUid();
2263
2264 // Doze allow
2265 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2266 INetd::FIREWALL_RULE_ALLOW);
2267 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2268 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2269
2270 // Doze deny
2271 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2272 INetd::FIREWALL_RULE_DENY);
2273 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2274 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2275
2276 // Powersave allow
2277 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2278 INetd::FIREWALL_RULE_ALLOW);
2279 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2280 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2281
2282 // Powersave deny
2283 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2284 INetd::FIREWALL_RULE_DENY);
2285 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2286 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2287
2288 // Standby deny
2289 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2290 INetd::FIREWALL_RULE_DENY);
2291 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2292 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2293
2294 // Standby allow
2295 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2296 INetd::FIREWALL_RULE_ALLOW);
2297 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2298 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2299
2300 // None deny in BLACKLIST
2301 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2302 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2303 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2304 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2305
2306 // None allow in BLACKLIST
2307 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2308 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2309 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2310 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2311
2312 // set firewall type whitelist twice
2313 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2314 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2315 expectFirewallWhitelistMode();
2316
2317 // None allow in WHITELIST
2318 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2319 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2320 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2321 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2322
2323 // None deny in WHITELIST
2324 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2325 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2326 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2327 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2328
2329 // reset firewall mode to default
2330 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2331 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2332 expectFirewallBlacklistMode();
2333}
2334
2335TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2336 SKIP_IF_BPF_SUPPORTED;
2337
2338 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2339 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2340 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2341
2342 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2343 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2344 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2345
2346 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2347 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2348 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2349
2350 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2351 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2352 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2353
2354 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2355 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2356 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2357
2358 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2359 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2360 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2361}
Luke Huangf7782042018-08-08 13:13:04 +08002362
2363namespace {
2364
2365std::string hwAddrToStr(unsigned char* hwaddr) {
2366 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2367 hwaddr[4], hwaddr[5]);
2368}
2369
2370int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2371 int prefixLength = 0;
2372 uint32_t m = ntohl(mask);
2373 while (m & (1 << 31)) {
2374 prefixLength++;
2375 m = m << 1;
2376 }
2377 return prefixLength;
2378}
2379
2380std::string toStdString(const String16& s) {
2381 return std::string(String8(s.string()));
2382}
2383
2384android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2385 const auto& sys = sSyscalls.get();
2386 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2387 EXPECT_TRUE(isOk(fd.status()));
2388
2389 struct ifreq ifr = {};
2390 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2391
2392 return sys.ioctl(fd.value(), flag, &ifr);
2393}
2394
2395std::string getInterfaceHwAddr(const std::string& ifName) {
2396 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2397
2398 unsigned char hwaddr[ETH_ALEN] = {};
2399 if (isOk(res.status())) {
2400 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2401 }
2402
2403 return hwAddrToStr(hwaddr);
2404}
2405
2406int getInterfaceIPv4Prefix(const std::string& ifName) {
2407 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2408
2409 int prefixLength = 0;
2410 if (isOk(res.status())) {
2411 prefixLength = ipv4NetmaskToPrefixLength(
2412 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2413 }
2414
2415 return prefixLength;
2416}
2417
2418std::string getInterfaceIPv4Addr(const std::string& ifName) {
2419 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2420
2421 struct in_addr addr = {};
2422 if (isOk(res.status())) {
2423 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2424 }
2425
2426 return std::string(inet_ntoa(addr));
2427}
2428
2429std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2430 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2431
2432 unsigned flags = 0;
2433 if (isOk(res.status())) {
2434 flags = res.value().ifr_flags;
2435 }
2436
2437 std::vector<std::string> ifFlags;
2438 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2439 : toStdString(INetd::IF_STATE_DOWN()));
2440
2441 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2442 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2443 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2444 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2445 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2446
2447 return ifFlags;
2448}
2449
2450bool compareListInterface(const std::vector<std::string>& interfaceList) {
2451 const auto& res = InterfaceController::getIfaceNames();
2452 EXPECT_TRUE(isOk(res));
2453
2454 std::vector<std::string> resIfList;
2455 resIfList.reserve(res.value().size());
2456 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2457
2458 return resIfList == interfaceList;
2459}
2460
2461int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2462 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2463 return readIntFromPath(path);
2464}
2465
2466bool getInterfaceEnableIPv6(const std::string& ifName) {
2467 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2468
2469 int disableIPv6 = readIntFromPath(path);
2470 return !disableIPv6;
2471}
2472
2473int getInterfaceMtu(const std::string& ifName) {
2474 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2475 return readIntFromPath(path);
2476}
2477
2478void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2479 EXPECT_TRUE(compareListInterface(interfaceList));
2480}
2481
2482void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2483 const InterfaceConfigurationParcel& interfaceCfg) {
2484 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2485 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2486 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2487 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2488}
2489
2490void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2491 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2492 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2493
2494 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2495 for (const auto& flag : setCfg.flags) {
2496 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2497 }
2498}
2499
2500void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2501 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2502 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2503}
2504
2505void expectInterfaceNoAddr(const std::string& ifName) {
2506 // noAddr
2507 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2508 // noPrefix
2509 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2510}
2511
2512void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2513 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2514 EXPECT_EQ(enableIPv6, enable);
2515}
2516
2517void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2518 int mtuSize = getInterfaceMtu(ifName);
2519 EXPECT_EQ(mtu, mtuSize);
2520}
2521
2522InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2523 const std::string& addr, int prefixLength,
2524 const std::vector<std::string>& flags) {
2525 InterfaceConfigurationParcel cfg;
2526 cfg.ifName = ifName;
2527 cfg.hwAddr = "";
2528 cfg.ipv4Addr = addr;
2529 cfg.prefixLength = prefixLength;
2530 cfg.flags = flags;
2531 return cfg;
2532}
2533
2534void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2535 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2536 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2537
2538 for (const auto& flag : expectedFlags) {
2539 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2540 interfaceCfg.flags.end());
2541 }
2542
2543 for (const auto& flag : unexpectedFlags) {
2544 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2545 interfaceCfg.flags.end());
2546 }
2547}
2548
2549} // namespace
2550
2551TEST_F(BinderTest, InterfaceList) {
2552 std::vector<std::string> interfaceListResult;
2553
2554 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2555 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2556 expectInterfaceList(interfaceListResult);
2557}
2558
2559TEST_F(BinderTest, InterfaceGetCfg) {
2560 InterfaceConfigurationParcel interfaceCfgResult;
2561
2562 // Add test physical network
2563 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2564 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2565
2566 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2567 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2568 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2569 expectTunFlags(interfaceCfgResult);
2570
2571 // Remove test physical network
2572 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2573}
2574
2575TEST_F(BinderTest, InterfaceSetCfg) {
2576 const std::string testAddr = "192.0.2.3";
2577 const int testPrefixLength = 24;
2578 std::vector<std::string> upFlags = {"up"};
2579 std::vector<std::string> downFlags = {"down"};
2580
2581 // Add test physical network
2582 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2583 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2584
2585 // Set tun interface down.
2586 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2587 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2588 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2589 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2590
2591 // Set tun interface up again.
2592 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2593 status = mNetd->interfaceSetCfg(interfaceCfg);
2594 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2595 status = mNetd->interfaceClearAddrs(sTun.name());
2596 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2597
2598 // Remove test physical network
2599 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2600}
2601
2602TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2603 // enable
2604 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2605 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2606 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2607
2608 // disable
2609 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2610 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2611 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2612}
2613
2614TEST_F(BinderTest, InterfaceClearAddr) {
2615 const std::string testAddr = "192.0.2.3";
2616 const int testPrefixLength = 24;
2617 std::vector<std::string> noFlags{};
2618
2619 // Add test physical network
2620 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2621 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2622
2623 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2624 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2625 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2626 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2627
2628 status = mNetd->interfaceClearAddrs(sTun.name());
2629 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2630 expectInterfaceNoAddr(sTun.name());
2631
2632 // Remove test physical network
2633 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2634}
2635
2636TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2637 // Add test physical network
2638 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2639 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2640
2641 // disable
2642 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2643 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2644 expectInterfaceEnableIPv6(sTun.name(), false);
2645
2646 // enable
2647 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2648 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2649 expectInterfaceEnableIPv6(sTun.name(), true);
2650
2651 // Remove test physical network
2652 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2653}
2654
2655TEST_F(BinderTest, InterfaceSetMtu) {
2656 const int testMtu = 1200;
2657
2658 // Add test physical network
2659 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2660 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2661
2662 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2663 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2664 expectInterfaceMtu(sTun.name(), testMtu);
2665
2666 // Remove test physical network
2667 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2668}
Luke Huang19b49c52018-10-22 12:12:05 +09002669
2670namespace {
2671
2672constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2673constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002674constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002675constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2676
Luke Huangae038f82018-11-05 11:17:31 +09002677int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002678 return listIptablesRuleByTable(binary, table, chainName).size();
2679}
2680
2681bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2682 const std::vector<std::string>& targetVec) {
2683 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2684 if (targetVec.size() != rules.size() - 2) {
2685 return false;
2686 }
2687
2688 /*
Luke Huangae038f82018-11-05 11:17:31 +09002689 * Check that the rules match. Note that this function matches substrings, not entire rules,
2690 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002691 * Skip first two lines since rules start from third line.
2692 * Chain chainName (x references)
2693 * pkts bytes target prot opt in out source destination
2694 * ...
2695 */
2696 int rIndex = 2;
2697 for (const auto& target : targetVec) {
2698 if (rules[rIndex].find(target) == std::string::npos) {
2699 return false;
2700 }
2701 rIndex++;
2702 }
2703 return true;
2704}
2705
2706void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2707 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2708 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2709 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002710 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002711 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2712 "DROP"};
2713
2714 // V4
2715 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2716 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002717 EXPECT_TRUE(
2718 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002719 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2720
Luke Huangae038f82018-11-05 11:17:31 +09002721 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002722 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2723
2724 // V6
2725 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002726 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2727 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002728
2729 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2730 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2731 extIf));
2732 }
2733}
2734
2735void expectNatDisable() {
2736 // It is the default DROP rule with tethering disable.
2737 // Chain tetherctrl_FORWARD (1 references)
2738 // pkts bytes target prot opt in out source destination
2739 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2740 std::vector<std::string> forwardV4Match = {"DROP"};
2741 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2742
2743 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002744 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2745 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002746
Luke Huangae038f82018-11-05 11:17:31 +09002747 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2748 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002749
2750 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2751}
2752
2753} // namespace
2754
2755TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002756 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2757 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2758 expectNatEnable(sTun.name(), sTun2.name());
2759
2760 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2761 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2762 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002763}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002764
2765namespace {
2766
2767using TripleInt = std::array<int, 3>;
2768
2769TripleInt readProcFileToTripleInt(const std::string& path) {
2770 std::string valueString;
2771 int min, def, max;
2772 EXPECT_TRUE(ReadFileToString(path, &valueString));
2773 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2774 return {min, def, max};
2775}
2776
2777void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2778 std::string testRmemValues =
2779 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2780 std::string testWmemValues =
2781 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2782 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2783
2784 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2785 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2786
2787 for (int i = 0; i < 3; i++) {
2788 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2789 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2790 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2791 }
2792}
2793
2794} // namespace
2795
2796TEST_F(BinderTest, TcpBufferSet) {
2797 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2798 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2799 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2800 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2801
2802 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2803 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2804}