blob: d7c449e508952c2337f886edc68cd17d83890615 [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];
Erik Kline38e51f12018-09-06 20:14:44 +0900943 const binder::Status status =
944 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900945
946 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900947 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900948 EXPECT_EQ(0, status.exceptionCode());
949 EXPECT_EQ(0, status.serviceSpecificErrorCode());
950 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900951 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900952 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
953 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
954 }
955 }
956}
Ben Schwartze7601812017-04-28 16:38:29 -0400957
Erik Kline38e51f12018-09-06 20:14:44 +0900958TEST_F(BinderTest, GetSetProcSysNet) {
959 const int ipversion = INetd::IPV6;
960 const int category = INetd::NEIGH;
961 const std::string& tun = sTun.name();
962 const std::string parameter("ucast_solicit");
963
964 std::string value{};
965 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
966 EXPECT_FALSE(value.empty());
967 const int ival = std::stoi(value);
968 EXPECT_GT(ival, 0);
969 // Try doubling the parameter value (always best!).
970 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
971 .isOk());
972 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
973 EXPECT_EQ(2 * ival, std::stoi(value));
974 // Try resetting the parameter.
975 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
976 .isOk());
977 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
978 EXPECT_EQ(ival, std::stoi(value));
979}
980
Ben Schwartze7601812017-04-28 16:38:29 -0400981static std::string base64Encode(const std::vector<uint8_t>& input) {
982 size_t out_len;
983 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
984 // out_len includes the trailing NULL.
985 uint8_t output_bytes[out_len];
986 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
987 return std::string(reinterpret_cast<char*>(output_bytes));
988}
989
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900990TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900991 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400992 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400993 std::vector<uint8_t> short_fp(1);
994 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
995 std::vector<std::string> test_domains;
996 std::vector<int> test_params = { 300, 25, 8, 8 };
997 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400998 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400999 const std::vector<std::string> servers;
1000 const std::string tlsName;
1001 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -04001002 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +09001003 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001004 { {"192.0.2.1"}, "", {}, 0 },
1005 { {"2001:db8::2"}, "host.name", {}, 0 },
1006 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
1007 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +09001008 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001009 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +09001010 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001011 { {"2001:dg8::6"}, "", {}, EINVAL },
1012 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
1013 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
1014 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
1015 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -04001016 };
1017
Sehee Park8659b8d2018-11-16 10:53:16 +09001018 for (size_t i = 0; i < std::size(kTlsTestData); i++) {
Erik Klinea1476fb2018-03-04 21:01:56 +09001019 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -04001020
1021 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001022 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -04001023 fingerprints.push_back(base64Encode(fingerprint));
1024 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001025 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001026 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
1027 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -04001028
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001029 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +09001030 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Ben Schwartze7601812017-04-28 16:38:29 -04001031 SCOPED_TRACE(status.toString8());
1032 EXPECT_EQ(0, status.exceptionCode());
1033 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +09001034 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Ben Schwartze7601812017-04-28 16:38:29 -04001035 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001036 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -04001037 }
Ben Schwartze7601812017-04-28 16:38:29 -04001038 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001039 // Ensure TLS is disabled before the start of the next test.
1040 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001041 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1042 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001043}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001044
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001045namespace {
1046
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001047void expectNoTestCounterRules() {
1048 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1049 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1050 std::string allRules = Join(runCommand(command), "\n");
1051 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1052 }
1053}
1054
Bernie Innocentif6918262018-06-11 17:37:35 +09001055void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1056 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001057 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1058 path, if1.c_str(), if2.c_str(), pkt, byte));
1059}
1060
Bernie Innocentif6918262018-06-11 17:37:35 +09001061void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001062 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1063 path, if1.c_str(), if2.c_str()));
1064 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1065 path, if2.c_str(), if1.c_str()));
1066}
1067
Luke Huangcaebcbb2018-09-27 20:37:14 +08001068std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1069 const std::string& iface) {
1070 for (auto& stats : statsVec) {
1071 if (stats.iface == iface) {
1072 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1073 }
1074 }
1075 return {};
1076}
1077
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001078} // namespace
1079
1080TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001081 expectNoTestCounterRules();
1082
1083 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1084 // disabling tethering. We don't check the return value because these commands will fail if
1085 // tethering is already enabled.
1086 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1087 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1088
1089 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1090 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1091 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1092 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1093 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1094
1095 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1096 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1097 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1098 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1099 // RX is from external to internal, and TX is from internal to external.
1100 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1101 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1102
1103 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1104 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1105
1106 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1107 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1108
1109 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1110 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1111 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1112
Luke Huangcaebcbb2018-09-27 20:37:14 +08001113 std::vector<TetherStatsParcel> statsVec;
1114 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001115 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1116
Luke Huangcaebcbb2018-09-27 20:37:14 +08001117 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001118
Luke Huangcaebcbb2018-09-27 20:37:14 +08001119 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001120
1121 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1122 delTetherCounterValues(path, intIface1, extIface1);
1123 delTetherCounterValues(path, intIface2, extIface2);
1124 if (path == IP6TABLES_PATH) {
1125 delTetherCounterValues(path, intIface3, extIface2);
1126 }
1127 }
1128
1129 expectNoTestCounterRules();
1130}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001131
Luke Huang0051a622018-07-23 20:30:16 +08001132namespace {
1133
Luke Huanga5211072018-08-01 23:36:29 +08001134constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1135constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001136
1137static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1138 const char* chainName) {
1139 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1140 return runCommand(command);
1141}
1142
Luke Huang19b49c52018-10-22 12:12:05 +09001143// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001144bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001145 const std::string& expectedInterface,
1146 const std::string& expectedRule, const char* table) {
1147 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1148 for (const auto& rule : rules) {
1149 if (rule.find(expectedInterface) != std::string::npos) {
1150 if (rule.find(expectedRule) != std::string::npos) {
1151 return true;
1152 }
1153 }
1154 }
1155 return false;
1156}
1157
1158void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001159 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001160 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001161 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001162 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001163 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1164 IdletimerRule, RAW_TABLE));
1165 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001166 ifname, IdletimerRule, MANGLE_TABLE));
1167 }
1168}
1169
1170void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001171 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001172 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001173 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001174 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001175 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1176 IdletimerRule, RAW_TABLE));
1177 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001178 ifname, IdletimerRule, MANGLE_TABLE));
1179 }
1180}
1181
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001182} // namespace
1183
1184TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001185 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1186 // rule in the table. Because we only check the result after calling remove function. We might
1187 // check the actual rule which is removed by our function (maybe compare the results between
1188 // calling function before and after)
1189 binder::Status status;
1190 const struct TestData {
1191 const std::string ifname;
1192 int32_t timeout;
1193 const std::string classLabel;
1194 } idleTestData[] = {
1195 {"wlan0", 1234, "happyday"},
1196 {"rmnet_data0", 4567, "friday"},
1197 };
1198 for (const auto& td : idleTestData) {
1199 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1200 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1201 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1202
1203 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1204 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1205 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1206 }
1207}
1208
Luke Huanga67dd562018-07-17 19:58:25 +08001209namespace {
1210
1211constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1212constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1213
1214void expectStrictSetUidAccept(const int uid) {
1215 std::string uidRule = StringPrintf("owner UID match %u", uid);
1216 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1217 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1218 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1219 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1220 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1221 }
1222}
1223
1224void expectStrictSetUidLog(const int uid) {
1225 static const char logRule[] = "st_penalty_log all";
1226 std::string uidRule = StringPrintf("owner UID match %u", uid);
1227 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1228 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1229 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1230 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1231 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1232 }
1233}
1234
1235void expectStrictSetUidReject(const int uid) {
1236 static const char rejectRule[] = "st_penalty_reject all";
1237 std::string uidRule = StringPrintf("owner UID match %u", uid);
1238 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1239 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1240 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1241 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1242 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1243 }
1244}
1245
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001246} // namespace
1247
1248TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001249 binder::Status status;
1250 int32_t uid = randomUid();
1251
1252 // setUidCleartextPenalty Policy:Log with randomUid
1253 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1254 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1255 expectStrictSetUidLog(uid);
1256
1257 // setUidCleartextPenalty Policy:Accept with randomUid
1258 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1259 expectStrictSetUidAccept(uid);
1260
1261 // setUidCleartextPenalty Policy:Reject with randomUid
1262 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1263 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1264 expectStrictSetUidReject(uid);
1265
1266 // setUidCleartextPenalty Policy:Accept with randomUid
1267 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1268 expectStrictSetUidAccept(uid);
1269
1270 // test wrong policy
1271 int32_t wrongPolicy = -123;
1272 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1273 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1274}
1275
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001276namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001277
Luke Huanga5211072018-08-01 23:36:29 +08001278bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001279 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1280 return (runCommand(cmd.c_str()).size()) ? true : false;
1281}
1282
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001283} // namespace
1284
1285TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001286 binder::Status status;
1287 // use dummy0 for test since it is set ready
1288 static const char testIf[] = "dummy0";
1289 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1290
1291 status = mNetd->clatdStart(testIf);
1292 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1293 EXPECT_TRUE(processExists(clatdName));
1294
1295 mNetd->clatdStop(testIf);
1296 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1297 EXPECT_FALSE(processExists(clatdName));
1298}
Luke Huang457d4702018-08-16 15:39:15 +08001299
1300namespace {
1301
1302bool getIpfwdV4Enable() {
1303 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1304 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1305 EXPECT_TRUE(!result.empty());
1306 int v4Enable = std::stoi(result[0]);
1307 return v4Enable;
1308}
1309
1310bool getIpfwdV6Enable() {
1311 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1312 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1313 EXPECT_TRUE(!result.empty());
1314 int v6Enable = std::stoi(result[0]);
1315 return v6Enable;
1316}
1317
1318void expectIpfwdEnable(bool enable) {
1319 int enableIPv4 = getIpfwdV4Enable();
1320 int enableIPv6 = getIpfwdV6Enable();
1321 EXPECT_EQ(enable, enableIPv4);
1322 EXPECT_EQ(enable, enableIPv6);
1323}
1324
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001325bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001326 std::vector<std::string> rules = listIpRules(ipVersion);
1327 for (const auto& rule : rules) {
1328 if (rule.find(ipfwdRule) != std::string::npos) {
1329 return true;
1330 }
1331 }
1332 return false;
1333}
1334
1335void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1336 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1337
1338 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1339 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1340 }
1341}
1342
1343void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1344 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1345
1346 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1347 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1348 }
1349}
1350
1351} // namespace
1352
1353TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1354 // Netd default enable Ipfwd with requester NetdHwService
1355 const std::string defaultRequester = "NetdHwService";
1356
1357 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1358 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1359 expectIpfwdEnable(false);
1360
1361 bool ipfwdEnabled;
1362 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1363 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1364 EXPECT_FALSE(ipfwdEnabled);
1365
1366 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1367 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1368 expectIpfwdEnable(true);
1369
1370 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1371 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1372 EXPECT_TRUE(ipfwdEnabled);
1373}
1374
1375TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1376 static const char testFromIf[] = "dummy0";
1377 static const char testToIf[] = "dummy0";
1378
1379 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1380 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1381 expectIpfwdRuleExists(testFromIf, testToIf);
1382
1383 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1384 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1385 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001386}
Luke Huang531f5d32018-08-03 15:19:05 +08001387
1388namespace {
1389
1390constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1391constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1392constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1393constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1394constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001395constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001396
Luke Huang19b49c52018-10-22 12:12:05 +09001397// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1398// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001399bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1400 const char* chainName, const std::string& expectedTargetA,
1401 const std::string& expectedTargetB) {
1402 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1403 int matchCount = 0;
1404
1405 for (const auto& rule : rules) {
1406 if (rule.find(expectedTargetA) != std::string::npos) {
1407 if (rule.find(expectedTargetB) != std::string::npos) {
1408 matchCount++;
1409 }
1410 }
1411 }
1412 return matchCount == expectedCount;
1413}
1414
1415void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1416 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1417 std::string result = "";
1418
1419 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001420 // Quota value might be decreased while matching packets
1421 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001422}
1423
1424void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1425 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1426 std::string quotaRule = StringPrintf("quota %s", ifname);
1427
1428 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1429 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1430 BANDWIDTH_COSTLY_IF));
1431 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1432 BANDWIDTH_COSTLY_IF));
1433 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1434 BANDWIDTH_COSTLY_IF));
1435 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1436 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1437 }
1438 expectXtQuotaValueEqual(ifname, quotaBytes);
1439}
1440
1441void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1442 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1443 std::string quotaRule = StringPrintf("quota %s", ifname);
1444
1445 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1446 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1447 BANDWIDTH_COSTLY_IF));
1448 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1449 BANDWIDTH_COSTLY_IF));
1450 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1451 BANDWIDTH_COSTLY_IF));
1452 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1453 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1454 }
1455}
1456
1457void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1458 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1459 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1460 std::string alertName = StringPrintf("%sAlert", ifname);
1461
1462 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1463 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1464 }
1465 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1466}
1467
1468void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1469 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1470 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1471
1472 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1473 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1474 }
1475}
1476
1477void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1478 static const char globalAlertRule[] = "quota globalAlert";
1479 static const char globalAlertName[] = "globalAlert";
1480
1481 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001482 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001483 }
1484 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1485}
1486
1487void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1488 std::string uidRule = StringPrintf("owner UID match %u", uid);
1489
1490 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1491 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1492 }
1493}
1494
1495void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1496 std::string uidRule = StringPrintf("owner UID match %u", uid);
1497
1498 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1499 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1500 }
1501}
1502
1503} // namespace
1504
1505TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1506 long testQuotaBytes = 5550;
1507
1508 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001509 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001510 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1511
1512 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1513 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1514 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1515
1516 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1517 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1518 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1519
1520 // Remove test physical network
1521 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1522}
1523
1524TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1525 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001526 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001527 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001528 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001529 // Need to have a prior interface quota set to set an alert
1530 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1531 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1532 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1533 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1534
1535 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1536 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1537 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1538
1539 // Remove interface quota
1540 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1541 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1542 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1543
1544 // Remove test physical network
1545 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1546}
1547
1548TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1549 long testAlertBytes = 2097149;
1550
1551 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1552 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1553 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1554
1555 testAlertBytes = 2097152;
1556 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1557 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1558 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1559}
1560
1561TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1562 SKIP_IF_BPF_SUPPORTED;
1563
1564 int32_t uid = randomUid();
1565 static const char targetReject[] = "REJECT";
1566 static const char targetReturn[] = "RETURN";
1567
1568 // add NaughtyApp
1569 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1570 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1571 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1572
1573 // remove NaughtyApp
1574 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1575 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1576 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1577
1578 // add NiceApp
1579 status = mNetd->bandwidthAddNiceApp(uid);
1580 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1581 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1582
1583 // remove NiceApp
1584 status = mNetd->bandwidthRemoveNiceApp(uid);
1585 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1586 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1587}
Luke Huangb5733d72018-08-21 17:17:19 +08001588
1589namespace {
1590
Luke Huangb670d162018-08-23 20:01:13 +08001591std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1592 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1593 return runCommand(command);
1594}
1595
Luke Huangc3252cc2018-10-16 15:43:23 +08001596bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001597 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1598 for (const auto& route : routes) {
1599 if (route.find(ipRoute) != std::string::npos) {
1600 return true;
1601 }
1602 }
1603 return false;
1604}
1605
Luke Huangc3252cc2018-10-16 15:43:23 +08001606std::string ipRouteString(const std::string& ifName, const std::string& dst,
1607 const std::string& nextHop) {
1608 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1609
1610 if (!nextHop.empty()) {
1611 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001612 }
1613
Luke Huangc3252cc2018-10-16 15:43:23 +08001614 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001615}
1616
Luke Huangc3252cc2018-10-16 15:43:23 +08001617void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1618 const std::string& dst, const std::string& nextHop,
1619 const char* table) {
1620 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1621}
1622
1623void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001624 const std::string& dst, const std::string& nextHop,
1625 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001626 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001627}
1628
1629bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1630 std::vector<std::string> rules = listIpRules(ipVersion);
1631 for (const auto& rule : rules) {
1632 if (rule.find(ipRule) != std::string::npos) {
1633 return true;
1634 }
1635 }
1636 return false;
1637}
1638
1639void expectNetworkDefaultIpRuleExists(const char* ifName) {
1640 std::string networkDefaultRule =
1641 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1642
1643 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1644 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1645 }
1646}
1647
1648void expectNetworkDefaultIpRuleDoesNotExist() {
1649 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1650
1651 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1652 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1653 }
1654}
1655
1656void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1657 std::string networkPermissionRule = "";
1658 switch (permission) {
1659 case INetd::PERMISSION_NONE:
1660 networkPermissionRule = StringPrintf(
1661 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1662 break;
1663 case INetd::PERMISSION_NETWORK:
1664 networkPermissionRule = StringPrintf(
1665 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1666 break;
1667 case INetd::PERMISSION_SYSTEM:
1668 networkPermissionRule = StringPrintf(
1669 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1670 break;
1671 }
1672
1673 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1674 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1675 }
1676}
1677
1678// TODO: It is a duplicate function, need to remove it
1679bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1680 const std::string& expectedInterface,
1681 const std::string& expectedRule,
1682 const char* table) {
1683 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1684 for (const auto& rule : rules) {
1685 if (rule.find(expectedInterface) != std::string::npos) {
1686 if (rule.find(expectedRule) != std::string::npos) {
1687 return true;
1688 }
1689 }
1690 }
1691 return false;
1692}
1693
1694void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1695 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1696 std::string networkIncomingPacketMarkRule = "";
1697 switch (permission) {
1698 case INetd::PERMISSION_NONE:
1699 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1700 break;
1701 case INetd::PERMISSION_NETWORK:
1702 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1703 break;
1704 case INetd::PERMISSION_SYSTEM:
1705 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1706 break;
1707 }
1708
1709 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1710 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1711 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1712 }
1713}
1714
1715} // namespace
1716
1717TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001718 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001719 const char* ipVersion;
1720 const char* testDest;
1721 const char* testNextHop;
1722 const bool expectSuccess;
1723 } kTestData[] = {
1724 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001725 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1726 {IP_RULE_V4, "10.251.0.0/16", "", true},
1727 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1728 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001729 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001730 {IP_RULE_V6, "::/0", "2001:db8::", true},
1731 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001732 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1733 };
1734
Luke Huangc3252cc2018-10-16 15:43:23 +08001735 static const struct {
1736 const char* ipVersion;
1737 const char* testDest;
1738 const char* testNextHop;
1739 } kTestDataWithNextHop[] = {
1740 {IP_RULE_V4, "10.251.10.0/30", ""},
1741 {IP_RULE_V6, "2001:db8::/32", ""},
1742 };
1743
Luke Huangb670d162018-08-23 20:01:13 +08001744 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001745 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001746 const int testUid = randomUid();
1747 const std::vector<int32_t> testUids = {testUid};
1748
1749 // Add test physical network
1750 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1751 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1752
Luke Huangc3252cc2018-10-16 15:43:23 +08001753 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001754 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001755 const auto& td = kTestDataWithNextHop[i];
1756
1757 // All route for test tun will disappear once the tun interface is deleted.
1758 binder::Status status =
1759 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1760 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1761 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1762 sTun.name().c_str());
1763
1764 // Add system permission for test uid, setup route in legacy system table.
1765 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1766
1767 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1768 testUid);
1769 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1770 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1771 testTableLegacySystem);
1772
1773 // Remove system permission for test uid, setup route in legacy network table.
1774 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1775
1776 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1777 testUid);
1778 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1779 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1780 testTableLegacyNetwork);
1781 }
1782
Sehee Park8659b8d2018-11-16 10:53:16 +09001783 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001784 const auto& td = kTestData[i];
1785
1786 binder::Status status =
1787 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1788 if (td.expectSuccess) {
1789 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001790 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001791 sTun.name().c_str());
1792 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001793 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1794 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001795 }
1796
1797 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1798 if (td.expectSuccess) {
1799 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001800 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1801 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001802 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001803 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1804 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001805 }
1806
Luke Huangc3252cc2018-10-16 15:43:23 +08001807 // Add system permission for test uid, route will be added into legacy system table.
1808 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001809
1810 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1811 testUid);
1812 if (td.expectSuccess) {
1813 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001814 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001815 testTableLegacySystem);
1816 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001817 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1818 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001819 }
1820
1821 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1822 td.testNextHop, testUid);
1823 if (td.expectSuccess) {
1824 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001825 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1826 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001827 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001828 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1829 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001830 }
1831
Luke Huangc3252cc2018-10-16 15:43:23 +08001832 // Remove system permission for test uid, route will be added into legacy network table.
1833 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1834
1835 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1836 testUid);
1837 if (td.expectSuccess) {
1838 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1839 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1840 testTableLegacyNetwork);
1841 } else {
1842 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1843 EXPECT_NE(0, status.serviceSpecificErrorCode());
1844 }
1845
1846 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1847 td.testNextHop, testUid);
1848 if (td.expectSuccess) {
1849 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1850 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1851 testTableLegacyNetwork);
1852 } else {
1853 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1854 EXPECT_NE(0, status.serviceSpecificErrorCode());
1855 }
Luke Huangb670d162018-08-23 20:01:13 +08001856 }
1857
1858 // Remove test physical network
1859 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1860}
1861
1862TEST_F(BinderTest, NetworkPermissionDefault) {
1863 // Add test physical network
1864 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1865 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1866
Luke Huangc3252cc2018-10-16 15:43:23 +08001867 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001868 int currentNetid;
1869 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1870 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1871
1872 // Test SetDefault
1873 status = mNetd->networkSetDefault(TEST_NETID1);
1874 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1875 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1876
1877 status = mNetd->networkClearDefault();
1878 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1879 expectNetworkDefaultIpRuleDoesNotExist();
1880
1881 // Add default network back
1882 status = mNetd->networkSetDefault(currentNetid);
1883 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1884
1885 // Test SetPermission
1886 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1887 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1888 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1889 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1890
1891 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1892 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1893 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1894 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1895
1896 // Remove test physical network
1897 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1898}
1899
1900TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1901 const int testUid = randomUid();
1902 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1903 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1904 bool ret = false;
1905 status = mNetd->networkCanProtect(testUid, &ret);
1906 EXPECT_TRUE(ret);
1907
1908 status = mNetd->networkSetProtectDeny(testUid);
1909 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1910 status = mNetd->networkCanProtect(testUid, &ret);
1911 EXPECT_FALSE(ret);
1912}
1913
1914namespace {
1915
Luke Huangb5733d72018-08-21 17:17:19 +08001916int readIntFromPath(const std::string& path) {
1917 std::string result = "";
1918 EXPECT_TRUE(ReadFileToString(path, &result));
1919 return std::stoi(result);
1920}
1921
1922int getTetherAcceptIPv6Ra(const std::string& ifName) {
1923 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1924 return readIntFromPath(path);
1925}
1926
1927bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1928 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1929 return readIntFromPath(path);
1930}
1931
1932int getTetherIPv6DadTransmits(const std::string& ifName) {
1933 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1934 return readIntFromPath(path);
1935}
1936
1937bool getTetherEnableIPv6(const std::string& ifName) {
1938 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1939 int disableIPv6 = readIntFromPath(path);
1940 return !disableIPv6;
1941}
1942
1943bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1944 for (const auto& iface : ifList) {
1945 if (iface == ifName) {
1946 return true;
1947 }
1948 }
1949 return false;
1950}
1951
1952void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1953 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1954 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1955 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1956 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1957}
1958
1959void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1960 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1961 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1962 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1963 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1964}
1965
1966void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1967 const std::string& ifName) {
1968 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1969}
1970
1971void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1972 const std::string& ifName) {
1973 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1974}
1975
1976void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
1977 const std::vector<std::string>& testDnsAddrs) {
1978 EXPECT_TRUE(dnsList == testDnsAddrs);
1979}
1980
1981} // namespace
1982
1983TEST_F(BinderTest, TetherStartStopStatus) {
1984 std::vector<std::string> noDhcpRange = {};
1985 static const char dnsdName[] = "dnsmasq";
1986
1987 binder::Status status = mNetd->tetherStart(noDhcpRange);
1988 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1989 EXPECT_TRUE(processExists(dnsdName));
1990
1991 bool tetherEnabled;
1992 status = mNetd->tetherIsEnabled(&tetherEnabled);
1993 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1994 EXPECT_TRUE(tetherEnabled);
1995
1996 status = mNetd->tetherStop();
1997 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1998 EXPECT_FALSE(processExists(dnsdName));
1999
2000 status = mNetd->tetherIsEnabled(&tetherEnabled);
2001 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2002 EXPECT_FALSE(tetherEnabled);
2003}
2004
2005TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2006 // TODO: verify if dnsmasq update interface successfully
2007
2008 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2009 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2010 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2011
2012 std::vector<std::string> ifList;
2013 status = mNetd->tetherInterfaceList(&ifList);
2014 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2015 expectTetherInterfaceExists(ifList, sTun.name());
2016
2017 status = mNetd->tetherInterfaceRemove(sTun.name());
2018 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2019 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2020
2021 status = mNetd->tetherInterfaceList(&ifList);
2022 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2023 expectTetherInterfaceNotExists(ifList, sTun.name());
2024}
2025
2026TEST_F(BinderTest, TetherDnsSetList) {
2027 // TODO: verify if dnsmasq update dns successfully
2028 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
2029
2030 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2031 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2032
2033 std::vector<std::string> dnsList;
2034 status = mNetd->tetherDnsList(&dnsList);
2035 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2036 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002037}
2038
2039namespace {
2040
2041constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2042constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2043constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2044constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2045constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2046constexpr char FIREWALL_STANDBY[] = "fw_standby";
2047constexpr char targetReturn[] = "RETURN";
2048constexpr char targetDrop[] = "DROP";
2049
2050void expectFirewallWhitelistMode() {
2051 static const char dropRule[] = "DROP all";
2052 static const char rejectRule[] = "REJECT all";
2053 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2054 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2055 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2056 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2057 }
2058}
2059
2060void expectFirewallBlacklistMode() {
2061 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2062 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2063 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2064 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2065 }
2066}
2067
2068bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2069 const std::string& expectedInterface,
2070 const std::string& expectedRule) {
2071 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2072 // Expected rule:
2073 // Chain fw_INPUT (1 references)
2074 // pkts bytes target prot opt in out source destination
2075 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2076 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2077 int firstRuleIndex = 2;
2078 if (rules.size() < 4) return false;
2079 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2080 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2081 return true;
2082 }
2083 }
2084 return false;
2085}
2086
2087// TODO: It is a duplicate function, need to remove it
2088bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2089 const std::string& expectedInterface,
2090 const std::string& expectedRule) {
2091 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2092 for (const auto& rule : rules) {
2093 if (rule.find(expectedInterface) != std::string::npos) {
2094 if (rule.find(expectedRule) != std::string::npos) {
2095 return true;
2096 }
2097 }
2098 }
2099 return false;
2100}
2101
2102void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2103 static const char returnRule[] = "RETURN all";
2104 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2105 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2106 returnRule));
2107 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2108 returnRule));
2109 }
2110}
2111
2112void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2113 static const char returnRule[] = "RETURN all";
2114 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2115 EXPECT_FALSE(
2116 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2117 EXPECT_FALSE(
2118 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2119 }
2120}
2121
2122bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2123 const std::string& expectedTarget,
2124 const std::string& expectedRule) {
2125 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2126 int firstRuleIndex = 2;
2127 if (rules.size() < 4) return false;
2128 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2129 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2130 return true;
2131 }
2132 }
2133 return false;
2134}
2135
2136bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2137 const std::string& expectedTarget,
2138 const std::string& expectedRule) {
2139 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2140 int lastRuleIndex = rules.size() - 1;
2141 if (lastRuleIndex < 0) return false;
2142 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2143 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2144 return true;
2145 }
2146 }
2147 return false;
2148}
2149
2150void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2151 std::string uidRule = StringPrintf("owner UID match %u", uid);
2152 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2153 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2154}
2155
2156void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2157 std::string uidRule = StringPrintf("owner UID match %u", uid);
2158 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2159 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2160}
2161
2162void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2163 std::string uidRule = StringPrintf("owner UID match %u", uid);
2164 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2165 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2166}
2167
2168void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2169 std::string uidRule = StringPrintf("owner UID match %u", uid);
2170 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2171 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2172}
2173
2174bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2175 std::vector<std::string> inputRules =
2176 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2177 std::vector<std::string> outputRules =
2178 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2179 int inputLastRuleIndex = inputRules.size() - 1;
2180 int outputLastRuleIndex = outputRules.size() - 1;
2181
2182 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2183 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2184 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2185 return true;
2186 }
2187 }
2188 return false;
2189}
2190
2191void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2192 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2193 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2194}
2195
2196void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2197 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2198 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2199 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2200 }
2201}
2202
2203} // namespace
2204
2205TEST_F(BinderTest, FirewallSetFirewallType) {
2206 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2207 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2208 expectFirewallWhitelistMode();
2209
2210 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2211 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2212 expectFirewallBlacklistMode();
2213
2214 // set firewall type blacklist twice
2215 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2216 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2217 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2218 expectFirewallBlacklistMode();
2219
2220 // set firewall type whitelist twice
2221 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2222 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2223 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2224 expectFirewallWhitelistMode();
2225
2226 // reset firewall type to default
2227 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2228 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2229 expectFirewallBlacklistMode();
2230}
2231
2232TEST_F(BinderTest, FirewallSetInterfaceRule) {
2233 // setinterfaceRule is not supported in BLACKLIST MODE
2234 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2235 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2236
2237 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2238 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2239
2240 // set WHITELIST mode first
2241 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2242 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2243
2244 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2245 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2246 expectFirewallInterfaceRuleAllowExists(sTun.name());
2247
2248 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2249 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2250 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2251
2252 // reset firewall mode to default
2253 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2254 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2255 expectFirewallBlacklistMode();
2256}
2257
2258TEST_F(BinderTest, FirewallSetUidRule) {
2259 SKIP_IF_BPF_SUPPORTED;
2260
2261 int32_t uid = randomUid();
2262
2263 // Doze allow
2264 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2265 INetd::FIREWALL_RULE_ALLOW);
2266 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2267 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2268
2269 // Doze deny
2270 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2271 INetd::FIREWALL_RULE_DENY);
2272 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2273 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2274
2275 // Powersave allow
2276 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2277 INetd::FIREWALL_RULE_ALLOW);
2278 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2279 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2280
2281 // Powersave deny
2282 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2283 INetd::FIREWALL_RULE_DENY);
2284 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2285 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2286
2287 // Standby deny
2288 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2289 INetd::FIREWALL_RULE_DENY);
2290 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2291 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2292
2293 // Standby allow
2294 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2295 INetd::FIREWALL_RULE_ALLOW);
2296 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2297 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2298
2299 // None deny in BLACKLIST
2300 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2301 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2302 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2303 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2304
2305 // None allow in BLACKLIST
2306 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2307 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2308 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2309 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2310
2311 // set firewall type whitelist twice
2312 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2313 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2314 expectFirewallWhitelistMode();
2315
2316 // None allow in WHITELIST
2317 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2318 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2319 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2320 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2321
2322 // None deny in WHITELIST
2323 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2324 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2325 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2326 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2327
2328 // reset firewall mode to default
2329 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2330 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2331 expectFirewallBlacklistMode();
2332}
2333
2334TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2335 SKIP_IF_BPF_SUPPORTED;
2336
2337 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2338 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2339 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2340
2341 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2342 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2343 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2344
2345 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2346 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2347 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2348
2349 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2350 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2351 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2352
2353 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2354 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2355 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2356
2357 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2358 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2359 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2360}
Luke Huangf7782042018-08-08 13:13:04 +08002361
2362namespace {
2363
2364std::string hwAddrToStr(unsigned char* hwaddr) {
2365 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2366 hwaddr[4], hwaddr[5]);
2367}
2368
2369int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2370 int prefixLength = 0;
2371 uint32_t m = ntohl(mask);
2372 while (m & (1 << 31)) {
2373 prefixLength++;
2374 m = m << 1;
2375 }
2376 return prefixLength;
2377}
2378
2379std::string toStdString(const String16& s) {
2380 return std::string(String8(s.string()));
2381}
2382
2383android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2384 const auto& sys = sSyscalls.get();
2385 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2386 EXPECT_TRUE(isOk(fd.status()));
2387
2388 struct ifreq ifr = {};
2389 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2390
2391 return sys.ioctl(fd.value(), flag, &ifr);
2392}
2393
2394std::string getInterfaceHwAddr(const std::string& ifName) {
2395 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2396
2397 unsigned char hwaddr[ETH_ALEN] = {};
2398 if (isOk(res.status())) {
2399 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2400 }
2401
2402 return hwAddrToStr(hwaddr);
2403}
2404
2405int getInterfaceIPv4Prefix(const std::string& ifName) {
2406 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2407
2408 int prefixLength = 0;
2409 if (isOk(res.status())) {
2410 prefixLength = ipv4NetmaskToPrefixLength(
2411 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2412 }
2413
2414 return prefixLength;
2415}
2416
2417std::string getInterfaceIPv4Addr(const std::string& ifName) {
2418 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2419
2420 struct in_addr addr = {};
2421 if (isOk(res.status())) {
2422 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2423 }
2424
2425 return std::string(inet_ntoa(addr));
2426}
2427
2428std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2429 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2430
2431 unsigned flags = 0;
2432 if (isOk(res.status())) {
2433 flags = res.value().ifr_flags;
2434 }
2435
2436 std::vector<std::string> ifFlags;
2437 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2438 : toStdString(INetd::IF_STATE_DOWN()));
2439
2440 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2441 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2442 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2443 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2444 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2445
2446 return ifFlags;
2447}
2448
2449bool compareListInterface(const std::vector<std::string>& interfaceList) {
2450 const auto& res = InterfaceController::getIfaceNames();
2451 EXPECT_TRUE(isOk(res));
2452
2453 std::vector<std::string> resIfList;
2454 resIfList.reserve(res.value().size());
2455 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2456
2457 return resIfList == interfaceList;
2458}
2459
2460int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2461 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2462 return readIntFromPath(path);
2463}
2464
2465bool getInterfaceEnableIPv6(const std::string& ifName) {
2466 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2467
2468 int disableIPv6 = readIntFromPath(path);
2469 return !disableIPv6;
2470}
2471
2472int getInterfaceMtu(const std::string& ifName) {
2473 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2474 return readIntFromPath(path);
2475}
2476
2477void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2478 EXPECT_TRUE(compareListInterface(interfaceList));
2479}
2480
2481void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2482 const InterfaceConfigurationParcel& interfaceCfg) {
2483 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2484 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2485 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2486 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2487}
2488
2489void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2490 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2491 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2492
2493 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2494 for (const auto& flag : setCfg.flags) {
2495 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2496 }
2497}
2498
2499void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2500 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2501 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2502}
2503
2504void expectInterfaceNoAddr(const std::string& ifName) {
2505 // noAddr
2506 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2507 // noPrefix
2508 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2509}
2510
2511void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2512 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2513 EXPECT_EQ(enableIPv6, enable);
2514}
2515
2516void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2517 int mtuSize = getInterfaceMtu(ifName);
2518 EXPECT_EQ(mtu, mtuSize);
2519}
2520
2521InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2522 const std::string& addr, int prefixLength,
2523 const std::vector<std::string>& flags) {
2524 InterfaceConfigurationParcel cfg;
2525 cfg.ifName = ifName;
2526 cfg.hwAddr = "";
2527 cfg.ipv4Addr = addr;
2528 cfg.prefixLength = prefixLength;
2529 cfg.flags = flags;
2530 return cfg;
2531}
2532
2533void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2534 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2535 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2536
2537 for (const auto& flag : expectedFlags) {
2538 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2539 interfaceCfg.flags.end());
2540 }
2541
2542 for (const auto& flag : unexpectedFlags) {
2543 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2544 interfaceCfg.flags.end());
2545 }
2546}
2547
2548} // namespace
2549
2550TEST_F(BinderTest, InterfaceList) {
2551 std::vector<std::string> interfaceListResult;
2552
2553 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2554 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2555 expectInterfaceList(interfaceListResult);
2556}
2557
2558TEST_F(BinderTest, InterfaceGetCfg) {
2559 InterfaceConfigurationParcel interfaceCfgResult;
2560
2561 // Add test physical network
2562 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2563 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2564
2565 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2566 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2567 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2568 expectTunFlags(interfaceCfgResult);
2569
2570 // Remove test physical network
2571 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2572}
2573
2574TEST_F(BinderTest, InterfaceSetCfg) {
2575 const std::string testAddr = "192.0.2.3";
2576 const int testPrefixLength = 24;
2577 std::vector<std::string> upFlags = {"up"};
2578 std::vector<std::string> downFlags = {"down"};
2579
2580 // Add test physical network
2581 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2582 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2583
2584 // Set tun interface down.
2585 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2586 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2587 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2588 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2589
2590 // Set tun interface up again.
2591 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2592 status = mNetd->interfaceSetCfg(interfaceCfg);
2593 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2594 status = mNetd->interfaceClearAddrs(sTun.name());
2595 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2596
2597 // Remove test physical network
2598 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2599}
2600
2601TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2602 // enable
2603 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2604 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2605 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2606
2607 // disable
2608 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2609 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2610 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2611}
2612
2613TEST_F(BinderTest, InterfaceClearAddr) {
2614 const std::string testAddr = "192.0.2.3";
2615 const int testPrefixLength = 24;
2616 std::vector<std::string> noFlags{};
2617
2618 // Add test physical network
2619 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2620 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2621
2622 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2623 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2624 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2625 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2626
2627 status = mNetd->interfaceClearAddrs(sTun.name());
2628 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2629 expectInterfaceNoAddr(sTun.name());
2630
2631 // Remove test physical network
2632 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2633}
2634
2635TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2636 // Add test physical network
2637 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2638 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2639
2640 // disable
2641 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2642 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2643 expectInterfaceEnableIPv6(sTun.name(), false);
2644
2645 // enable
2646 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2647 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2648 expectInterfaceEnableIPv6(sTun.name(), true);
2649
2650 // Remove test physical network
2651 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2652}
2653
2654TEST_F(BinderTest, InterfaceSetMtu) {
2655 const int testMtu = 1200;
2656
2657 // Add test physical network
2658 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2659 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2660
2661 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2662 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2663 expectInterfaceMtu(sTun.name(), testMtu);
2664
2665 // Remove test physical network
2666 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2667}
Luke Huang19b49c52018-10-22 12:12:05 +09002668
2669namespace {
2670
2671constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2672constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002673constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002674constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2675
Luke Huangae038f82018-11-05 11:17:31 +09002676int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002677 return listIptablesRuleByTable(binary, table, chainName).size();
2678}
2679
2680bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2681 const std::vector<std::string>& targetVec) {
2682 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2683 if (targetVec.size() != rules.size() - 2) {
2684 return false;
2685 }
2686
2687 /*
Luke Huangae038f82018-11-05 11:17:31 +09002688 * Check that the rules match. Note that this function matches substrings, not entire rules,
2689 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002690 * Skip first two lines since rules start from third line.
2691 * Chain chainName (x references)
2692 * pkts bytes target prot opt in out source destination
2693 * ...
2694 */
2695 int rIndex = 2;
2696 for (const auto& target : targetVec) {
2697 if (rules[rIndex].find(target) == std::string::npos) {
2698 return false;
2699 }
2700 rIndex++;
2701 }
2702 return true;
2703}
2704
2705void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2706 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2707 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2708 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002709 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002710 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2711 "DROP"};
2712
2713 // V4
2714 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2715 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002716 EXPECT_TRUE(
2717 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002718 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2719
Luke Huangae038f82018-11-05 11:17:31 +09002720 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002721 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2722
2723 // V6
2724 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002725 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2726 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002727
2728 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2729 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2730 extIf));
2731 }
2732}
2733
2734void expectNatDisable() {
2735 // It is the default DROP rule with tethering disable.
2736 // Chain tetherctrl_FORWARD (1 references)
2737 // pkts bytes target prot opt in out source destination
2738 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2739 std::vector<std::string> forwardV4Match = {"DROP"};
2740 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2741
2742 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002743 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2744 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002745
Luke Huangae038f82018-11-05 11:17:31 +09002746 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2747 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002748
2749 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2750}
2751
2752} // namespace
2753
2754TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002755 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2756 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2757 expectNatEnable(sTun.name(), sTun2.name());
2758
2759 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2760 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2761 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002762}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002763
2764namespace {
2765
2766using TripleInt = std::array<int, 3>;
2767
2768TripleInt readProcFileToTripleInt(const std::string& path) {
2769 std::string valueString;
2770 int min, def, max;
2771 EXPECT_TRUE(ReadFileToString(path, &valueString));
2772 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2773 return {min, def, max};
2774}
2775
2776void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2777 std::string testRmemValues =
2778 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2779 std::string testWmemValues =
2780 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2781 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2782
2783 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2784 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2785
2786 for (int i = 0; i < 3; i++) {
2787 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2788 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2789 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2790 }
2791}
2792
2793} // namespace
2794
2795TEST_F(BinderTest, TcpBufferSet) {
2796 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2797 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2798 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2799 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2800
2801 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2802 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2803}