blob: 0b87715448aa9460c7df493ca1b763aca3712dda [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>
Luke Huang528af602018-08-29 19:06:05 +080020#include <chrono>
Robin Leeb8087362016-03-30 18:43:08 +010021#include <cinttypes>
Luke Huang528af602018-08-29 19:06:05 +080022#include <condition_variable>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090023#include <cstdint>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090024#include <cstdlib>
Bernie Innocenti196f1b82019-05-20 16:34:16 +090025#include <iostream>
Luke Huang528af602018-08-29 19:06:05 +080026#include <mutex>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090027#include <set>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090028#include <vector>
29
Luke Huangf7782042018-08-08 13:13:04 +080030#include <dirent.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090031#include <fcntl.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090032#include <ifaddrs.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090033#include <linux/if.h>
34#include <linux/if_tun.h>
Benedict Wonga450e722018-05-07 10:29:02 -070035#include <net/if.h>
Luke Huangf7782042018-08-08 13:13:04 +080036#include <netdb.h>
37#include <netinet/in.h>
Ben Schwartze7601812017-04-28 16:38:29 -040038#include <openssl/base64.h>
Luke Huangf7782042018-08-08 13:13:04 +080039#include <sys/socket.h>
40#include <sys/types.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090041
Luke Huang531f5d32018-08-03 15:19:05 +080042#include <android-base/file.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090043#include <android-base/macros.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090044#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090045#include <android-base/strings.h>
Chiachang Wang00fc62f2019-12-04 20:38:26 +080046#include <android/multinetwork.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080047#include <binder/IPCThreadState.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080048#include <bpf/BpfMap.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070049#include <bpf/BpfUtils.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080050#include <com/android/internal/net/BnOemNetdUnsolicitedEventListener.h>
51#include <com/android/internal/net/IOemNetd.h>
Robin Leeb8087362016-03-30 18:43:08 +010052#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090053#include <gtest/gtest.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080054#include <netdbpf/bpf_shared.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090055#include <netutils/ifc.h>
Luke Huangd2861982019-05-17 19:47:28 +080056#include "Fwmark.h"
Nathan Harold21299f72018-03-16 20:13:03 -070057#include "InterfaceController.h"
Luke Huangd2861982019-05-17 19:47:28 +080058#include "NetdClient.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090059#include "NetdConstants.h"
Chiachang Wang00fc62f2019-12-04 20:38:26 +080060#include "NetworkController.h"
Luke Huang528af602018-08-29 19:06:05 +080061#include "TestUnsolService.h"
Nathan Harold21299f72018-03-16 20:13:03 -070062#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090063#include "android/net/INetd.h"
64#include "binder/IServiceManager.h"
Luke Huang25599322019-06-14 00:34:05 +080065#include "netdutils/InternetAddresses.h"
Mike Yue7e332f2019-03-13 17:15:48 +080066#include "netdutils/Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070067#include "netdutils/Syscalls.h"
Luke Huangd2861982019-05-17 19:47:28 +080068#include "netid_client.h" // NETID_UNSET
Lorenzo Colitti758bccc2019-06-26 22:12:35 +090069#include "test_utils.h"
Mike Yu5ae61542018-10-19 22:11:43 +080070#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090071
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090072#define IP6TABLES_PATH "/system/bin/ip6tables"
73#define IPTABLES_PATH "/system/bin/iptables"
Luke Huang0051a622018-07-23 20:30:16 +080074#define RAW_TABLE "raw"
75#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080076#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090077#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090078
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090079namespace binder = android::binder;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090080
81using android::IBinder;
82using android::IServiceManager;
83using android::sp;
84using android::String16;
85using android::String8;
86using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080087using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090088using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090089using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080090using android::base::Trim;
Bernie Innocentid26a04a2019-10-30 17:15:15 +090091using android::base::unique_fd;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090092using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080093using android::net::InterfaceConfigurationParcel;
94using android::net::InterfaceController;
Chiachang Wang00fc62f2019-12-04 20:38:26 +080095using android::net::MarkMaskParcel;
Lorenzo Colittif0e051c2020-04-06 09:19:57 +000096using android::net::TetherOffloadRuleParcel;
Luke Huangcaebcbb2018-09-27 20:37:14 +080097using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090098using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090099using android::net::UidRangeParcel;
Luke Huang25599322019-06-14 00:34:05 +0800100using android::netdutils::ScopedAddrinfo;
Luke Huangf7782042018-08-08 13:13:04 +0800101using android::netdutils::sSyscalls;
Mike Yue7e332f2019-03-13 17:15:48 +0800102using android::netdutils::Stopwatch;
Robin Leeb8087362016-03-30 18:43:08 +0100103
104static const char* IP_RULE_V4 = "-4";
105static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900106static const int TEST_NETID1 = 65501;
107static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -0800108
109// Use maximum reserved appId for applications to avoid conflict with existing
110// uids.
111static const int TEST_UID1 = 99999;
112static const int TEST_UID2 = 99998;
113
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900114constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900115
Benedict Wongb2daefb2017-12-06 22:05:46 -0800116static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
117static const std::string ESP_ALLOW_RULE("esp");
118
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900119class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900120 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900121 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900122 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900123 sp<IBinder> binder = sm->getService(String16("netd"));
124 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900125 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900126 }
127 }
128
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900129 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900130 ASSERT_NE(nullptr, mNetd.get());
131 }
132
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900133 void TearDown() override {
134 mNetd->networkDestroy(TEST_NETID1);
135 mNetd->networkDestroy(TEST_NETID2);
Luke Huangd2861982019-05-17 19:47:28 +0800136 setNetworkForProcess(NETID_UNSET);
137 // Restore default network
138 if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900139 }
140
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900141 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700142
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900143 // Static because setting up the tun interface takes about 40ms.
144 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900145 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900146 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900147 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900148 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900149 }
150
151 static void TearDownTestCase() {
152 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900153 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900154 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900155 }
156
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900157 static void fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
158 unique_fd* acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900159
Luke Huangd2861982019-05-17 19:47:28 +0800160 void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
161 int fallthroughNetId = TEST_NETID1);
162
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900163 protected:
Luke Huangd2861982019-05-17 19:47:28 +0800164 // Use -1 to represent that default network was not modified because
165 // real netId must be an unsigned value.
166 int mStoredDefaultNetwork = -1;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900167 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900168 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900169 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900170};
171
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900172TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900173TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900174
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900175class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900176 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700177 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900178 virtual ~TimedOperation() {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900179 std::cerr << " " << mName << ": " << timeTakenUs() << "us" << std::endl;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900180 }
181
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900182 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900183 std::string mName;
184};
185
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900186TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900187 TimedOperation t("isAlive RPC");
188 bool isAlive = false;
189 mNetd->isAlive(&isAlive);
190 ASSERT_TRUE(isAlive);
191}
192
Benedict Wongb2daefb2017-12-06 22:05:46 -0800193static bool iptablesNoSocketAllowRuleExists(const char *chainName){
194 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
195 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
196}
197
198static bool iptablesEspAllowRuleExists(const char *chainName){
199 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
200 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
201}
202
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900203TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700204 SKIP_IF_BPF_SUPPORTED;
205
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900206 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
207 const int kNumUids = 500;
208 std::vector<int32_t> noUids(0);
209 std::vector<int32_t> uids(kNumUids);
210 for (int i = 0; i < kNumUids; i++) {
211 uids[i] = randomUid();
212 }
213
214 bool ret;
215 {
216 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900217 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900218 }
219 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800220 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
221 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
222 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
223 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900224 {
225 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900226 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900227 }
228 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900229 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
230 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900231
232 {
233 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900234 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900235 }
236 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900237 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
238 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800239 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
240 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900241
242 {
243 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900244 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900245 }
246 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900247 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
248 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900249
250 // Check that the call fails if iptables returns an error.
251 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900252 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900253 EXPECT_EQ(false, ret);
254}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900255
Benedict Wong319f17e2018-05-15 17:06:44 -0700256TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700257 const struct TestData {
258 const std::string family;
259 const std::string deviceName;
260 const std::string localAddress;
261 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800262 int32_t iKey;
263 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700264 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800265 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700266 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
267 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
268 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800269 };
270
Sehee Park8659b8d2018-11-16 10:53:16 +0900271 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700272 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800273
274 binder::Status status;
275
Benedict Wong319f17e2018-05-15 17:06:44 -0700276 // Create Tunnel Interface.
277 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700278 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800279 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
280
Benedict Wonga450e722018-05-07 10:29:02 -0700281 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900282 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700283
Benedict Wong319f17e2018-05-15 17:06:44 -0700284 // Update Tunnel Interface.
285 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700286 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800287 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
288
Benedict Wong319f17e2018-05-15 17:06:44 -0700289 // Remove Tunnel Interface.
290 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800291 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700292
293 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900294 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800295 }
296}
297
Benedict Wong1cb73df2018-12-03 00:54:14 -0800298TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900299 unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Benedict Wong1cb73df2018-12-03 00:54:14 -0800300 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
301
302 int sockOptVal = UDP_ENCAP_ESPINUDP;
303 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
304
305 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
306 EXPECT_TRUE(res.isOk());
307
308 struct stat info;
309 EXPECT_EQ(0, fstat(sockFd.get(), &info));
310 EXPECT_EQ(1001, (int) info.st_uid);
311}
312
Nathan Harold2deff322018-05-10 14:03:48 -0700313// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
314// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
315#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900316
317using android::net::XfrmController;
318
Benedict Wonga04ffa72018-05-09 21:42:42 -0700319static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
320 static_cast<int>(android::net::XfrmDirection::OUT)};
321static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
322
Nathan Harold21299f72018-03-16 20:13:03 -0700323#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
324 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900325bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900326 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700327 SCOPED_TRACE(status);
328 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
329
330 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700331 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700332 SCOPED_TRACE(status);
333 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
334
335 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700336 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
337 0xD00D, 0xE00D, false)
338 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700339}
340
Benedict Wonga04ffa72018-05-09 21:42:42 -0700341TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900342 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700343
344 // Repeat to ensure cleanup and recreation works correctly
345 for (int i = 0; i < 2; i++) {
346 for (int direction : XFRM_DIRECTIONS) {
347 for (int addrFamily : ADDRESS_FAMILIES) {
348 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700349 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700350 EXPECT_TRUE(status.isOk())
351 << " family: " << addrFamily << " direction: " << direction;
352 }
353 }
354
355 // Cleanup
356 for (int direction : XFRM_DIRECTIONS) {
357 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700358 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700359 EXPECT_TRUE(status.isOk());
360 }
361 }
362 }
363}
364
365TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
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, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700373 "2001:db8::d00d", 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
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900389TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900390 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700391 status = XfrmController::Init();
392 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700393
394 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
395 // feature.
396 if (status.code() == EOPNOTSUPP) return;
397
Nathan Harold21299f72018-03-16 20:13:03 -0700398 ASSERT_TRUE(status.ok());
399
400 int32_t spi = 0;
401
402 ASSERT_TRUE(allocateIpSecResources(true, &spi));
403 ASSERT_TRUE(allocateIpSecResources(false, &spi));
404
405 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700406 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700407 ASSERT_TRUE(allocateIpSecResources(true, &spi));
408
409 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700410 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700411 SCOPED_TRACE(status);
412 ASSERT_TRUE(status.ok());
413
Benedict Wonga450e722018-05-07 10:29:02 -0700414 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700415 SCOPED_TRACE(status);
416 ASSERT_TRUE(status.ok());
417
418 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700419 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700420}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900421
422#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700423
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900424static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900425 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900426
427 // Output looks like this:
428 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900429 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900430 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900431 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900432 //
433 // or:
434 //
435 // Chain bw_data_saver (1 references)
436 // target prot opt source destination
437 // ... possibly connectivity critical packet rules here ...
438 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900439
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900440 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900441
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900442 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
443 // Data saver disabled.
444 return 0;
445 }
446
447 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
448
449 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
450 // Data saver enabled.
451 return 1;
452 }
453
454 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900455}
456
457bool enableDataSaver(sp<INetd>& netd, bool enable) {
458 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
459 bool ret;
460 netd->bandwidthEnableDataSaver(enable, &ret);
461 return ret;
462}
463
464int getDataSaverState() {
465 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
466 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
467 EXPECT_EQ(enabled4, enabled6);
468 EXPECT_NE(-1, enabled4);
469 EXPECT_NE(-1, enabled6);
470 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
471 return -1;
472 }
473 return enabled6;
474}
475
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900476TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900477 const int wasEnabled = getDataSaverState();
478 ASSERT_NE(-1, wasEnabled);
479
480 if (wasEnabled) {
481 ASSERT_TRUE(enableDataSaver(mNetd, false));
482 EXPECT_EQ(0, getDataSaverState());
483 }
484
485 ASSERT_TRUE(enableDataSaver(mNetd, false));
486 EXPECT_EQ(0, getDataSaverState());
487
488 ASSERT_TRUE(enableDataSaver(mNetd, true));
489 EXPECT_EQ(1, getDataSaverState());
490
491 ASSERT_TRUE(enableDataSaver(mNetd, true));
492 EXPECT_EQ(1, getDataSaverState());
493
494 if (!wasEnabled) {
495 ASSERT_TRUE(enableDataSaver(mNetd, false));
496 EXPECT_EQ(0, getDataSaverState());
497 }
498}
Robin Leeb8087362016-03-30 18:43:08 +0100499
Luke Huang94658ac2018-10-18 19:35:12 +0900500static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
501 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100502 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100503 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100504 std::vector<std::string> rules = listIpRules(ipVersion);
505
506 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900507 std::string suffix =
508 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900509 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800510 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100511 return true;
512 }
513 }
514 return false;
515}
516
Luke Huang94658ac2018-10-18 19:35:12 +0900517static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
518 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100519 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
520 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
521 EXPECT_EQ(existsIp4, existsIp6);
522 return existsIp4;
523}
524
Luke Huang94658ac2018-10-18 19:35:12 +0900525namespace {
526
527UidRangeParcel makeUidRangeParcel(int start, int stop) {
528 UidRangeParcel res;
529 res.start = start;
530 res.stop = stop;
531
532 return res;
533}
534
535} // namespace
536
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900537TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800538 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
539 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
540 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900541 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
542 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900543
544 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
545 EXPECT_EQ(EBUSY,
546 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
547
548 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
549 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
550 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800551 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900552}
553
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900554TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900555 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
556
cken67cd14c2018-12-05 17:26:59 +0900557 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
558 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900559 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
560
Luke Huang94658ac2018-10-18 19:35:12 +0900561 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
562 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
563 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900564 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
565
566 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
567
568 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
569 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
570 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
571 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
572
573 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
574 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
575 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
576 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
577
578 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
579}
580
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900581TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100582 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100583
Luke Huang94658ac2018-10-18 19:35:12 +0900584 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
585 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Luke Huang841f3ef2019-05-30 15:09:19 +0800586 // Make sure no rules existed before calling commands.
587 for (auto const& range : uidRanges) {
588 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
589 }
Robin Leeb8087362016-03-30 18:43:08 +0100590 // Create two valid rules.
591 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100592 for (auto const& range : uidRanges) {
593 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
594 }
595
596 // Remove the rules.
597 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100598 for (auto const& range : uidRanges) {
599 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
600 }
601
602 // Fail to remove the rules a second time after they are already deleted.
603 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
604 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
605 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
Robin Leeb8087362016-03-30 18:43:08 +0100606}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900607
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900608// Create a socket pair that isLoopbackSocket won't think is local.
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900609void BinderTest::fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
610 unique_fd* acceptedSocket) {
611 serverSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900612 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900613 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
614
615 socklen_t addrlen = sizeof(server6);
616 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
617 ASSERT_EQ(0, listen(*serverSocket, 10));
618
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900619 clientSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900620 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900621 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900622 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
623 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
624
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900625 acceptedSocket->reset(
626 accept4(*serverSocket, (struct sockaddr*)&server6, &addrlen, SOCK_CLOEXEC));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900627 ASSERT_NE(-1, *acceptedSocket);
628
629 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
630}
631
632void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
633 char buf[4096];
634 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
635 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
636 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
637}
638
639void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
640 // Check that the client socket was closed with ECONNABORTED.
641 int ret = write(clientSocket, "foo", sizeof("foo"));
642 int err = errno;
643 EXPECT_EQ(-1, ret);
644 EXPECT_EQ(ECONNABORTED, err);
645
646 // Check that it sent a RST to the server.
647 ret = write(acceptedSocket, "foo", sizeof("foo"));
648 err = errno;
649 EXPECT_EQ(-1, ret);
650 EXPECT_EQ(ECONNRESET, err);
651}
652
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900653TEST_F(BinderTest, SocketDestroy) {
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900654 unique_fd clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900655 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900656
657 // Pick a random UID in the system UID range.
658 constexpr int baseUid = AID_APP - 2000;
659 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
660 int uid = baseUid + 500 + arc4random_uniform(1000);
661 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
662
663 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900664 std::vector<UidRangeParcel> uidRanges = {
665 makeUidRangeParcel(baseUid + 42, baseUid + 449),
666 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
667 makeUidRangeParcel(baseUid + 498, uid - 1),
668 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900669 };
670 // A skip list that doesn't contain UID.
671 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
672
673 // Close sockets. Our test socket should be intact.
674 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
675 checkSocketpairOpen(clientSocket, acceptedSocket);
676
677 // UID ranges that do contain uid.
678 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900679 makeUidRangeParcel(baseUid + 42, baseUid + 449),
680 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
681 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900682 };
683 // Add uid to the skip list.
684 skipUids.push_back(uid);
685
686 // Close sockets. Our test socket should still be intact because it's in the skip list.
687 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
688 checkSocketpairOpen(clientSocket, acceptedSocket);
689
690 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
691 skipUids.resize(skipUids.size() - 1);
692 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
693 checkSocketpairClosed(clientSocket, acceptedSocket);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900694}
Erik Klinecc4f2732016-08-03 11:24:27 +0900695
696namespace {
697
698int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
699 if (buf == nullptr) return -1;
700
701 int prefixLength = 0;
702 bool endOfContiguousBits = false;
703 for (unsigned int i = 0; i < buflen; i++) {
704 const uint8_t value = buf[i];
705
706 // Bad bit sequence: check for a contiguous set of bits from the high
707 // end by verifying that the inverted value + 1 is a power of 2
708 // (power of 2 iff. (v & (v - 1)) == 0).
709 const uint8_t inverse = ~value + 1;
710 if ((inverse & (inverse - 1)) != 0) return -1;
711
712 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
713
714 // Bogus netmask.
715 if (endOfContiguousBits && value != 0) return -1;
716
717 if (value != 0xff) endOfContiguousBits = true;
718 }
719
720 return prefixLength;
721}
722
723template<typename T>
724int netmaskToPrefixLength(const T *p) {
725 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
726}
727
728
729static bool interfaceHasAddress(
730 const std::string &ifname, const char *addrString, int prefixLength) {
731 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900732
733 const struct addrinfo hints = {
734 .ai_flags = AI_NUMERICHOST,
735 .ai_family = AF_UNSPEC,
736 .ai_socktype = SOCK_DGRAM,
737 };
738 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
739 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
740 return false;
741 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900742 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900743
744 struct ifaddrs *ifaddrsList = nullptr;
745 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
746
747 if (getifaddrs(&ifaddrsList) != 0) {
748 return false;
749 }
750
751 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
752 if (std::string(addr->ifa_name) != ifname ||
753 addr->ifa_addr == nullptr ||
754 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
755 continue;
756 }
757
758 switch (addr->ifa_addr->sa_family) {
759 case AF_INET: {
760 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
761 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
762 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
763 continue;
764 }
765
766 if (prefixLength < 0) return true; // not checking prefix lengths
767
768 if (addr->ifa_netmask == nullptr) return false;
769 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
770 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
771 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
772 }
773 case AF_INET6: {
774 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
775 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
776 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
777 continue;
778 }
779
780 if (prefixLength < 0) return true; // not checking prefix lengths
781
782 if (addr->ifa_netmask == nullptr) return false;
783 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
784 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
785 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
786 }
787 default:
788 // Cannot happen because we have already screened for matching
789 // address families at the top of each iteration.
790 continue;
791 }
792 }
793
794 return false;
795}
796
797} // namespace
798
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900799TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900800 static const struct TestData {
801 const char *addrString;
802 const int prefixLength;
Lorenzo Colitti01118982019-12-02 13:19:44 +0900803 const int expectAddResult;
804 const int expectRemoveResult;
Erik Klinecc4f2732016-08-03 11:24:27 +0900805 } kTestData[] = {
Lorenzo Colitti01118982019-12-02 13:19:44 +0900806 {"192.0.2.1", 24, 0, 0},
807 {"192.0.2.2", 25, 0, 0},
808 {"192.0.2.3", 32, 0, 0},
809 {"192.0.2.4", 33, EINVAL, EADDRNOTAVAIL},
810 {"192.not.an.ip", 24, EINVAL, EINVAL},
811 {"2001:db8::1", 64, 0, 0},
812 {"2001:db8::2", 65, 0, 0},
813 {"2001:db8::3", 128, 0, 0},
814 {"2001:db8::4", 129, EINVAL, EINVAL},
815 {"foo:bar::bad", 64, EINVAL, EINVAL},
816 {"2001:db8::1/64", 64, EINVAL, EINVAL},
Erik Klinecc4f2732016-08-03 11:24:27 +0900817 };
818
Sehee Park8659b8d2018-11-16 10:53:16 +0900819 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900820 const auto &td = kTestData[i];
821
Lorenzo Colitti01118982019-12-02 13:19:44 +0900822 SCOPED_TRACE(String8::format("Offending IP address %s/%d", td.addrString, td.prefixLength));
823
Erik Klinecc4f2732016-08-03 11:24:27 +0900824 // [1.a] Add the address.
825 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900826 sTun.name(), td.addrString, td.prefixLength);
Lorenzo Colitti01118982019-12-02 13:19:44 +0900827 if (td.expectAddResult == 0) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900828 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
829 } else {
830 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Lorenzo Colitti01118982019-12-02 13:19:44 +0900831 ASSERT_EQ(td.expectAddResult, status.serviceSpecificErrorCode());
Erik Klinecc4f2732016-08-03 11:24:27 +0900832 }
833
834 // [1.b] Verify the addition meets the expectation.
Lorenzo Colitti01118982019-12-02 13:19:44 +0900835 if (td.expectAddResult == 0) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900836 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900837 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900838 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900839 }
840
841 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900842 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Lorenzo Colitti01118982019-12-02 13:19:44 +0900843 if (td.expectRemoveResult == 0) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900844 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
845 } else {
846 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Lorenzo Colitti01118982019-12-02 13:19:44 +0900847 ASSERT_EQ(td.expectRemoveResult, status.serviceSpecificErrorCode());
Erik Klinecc4f2732016-08-03 11:24:27 +0900848 }
849
850 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900851 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900852 }
Lorenzo Colitti9ae17712019-12-02 17:28:49 +0900853
854 // Check that netlink errors are returned correctly.
855 // We do this by attempting to create an IPv6 address on an interface that has IPv6 disabled,
856 // which returns EACCES.
857 TunInterface tun;
858 ASSERT_EQ(0, tun.init());
859 binder::Status status =
860 mNetd->setProcSysNet(INetd::IPV6, INetd::CONF, tun.name(), "disable_ipv6", "1");
861 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
862 status = mNetd->interfaceAddAddress(tun.name(), "2001:db8::1", 64);
863 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
864 EXPECT_EQ(EACCES, status.serviceSpecificErrorCode());
865 tun.destroy();
Erik Klinecc4f2732016-08-03 11:24:27 +0900866}
Erik Kline55b06f82016-07-04 09:57:18 +0900867
Erik Kline38e51f12018-09-06 20:14:44 +0900868TEST_F(BinderTest, GetProcSysNet) {
869 const char LOOPBACK[] = "lo";
870 static const struct {
871 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900872 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900873 const char* ifname;
874 const char* parameter;
875 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900876 const int expectedReturnCode;
877 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900878 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
879 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
880 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
881 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
882 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
883 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
884 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900885 };
886
Sehee Park8659b8d2018-11-16 10:53:16 +0900887 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900888 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900889
Erik Kline38e51f12018-09-06 20:14:44 +0900890 std::string value;
891 const binder::Status status =
892 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
893
894 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900895 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900896 EXPECT_EQ(0, status.exceptionCode());
897 EXPECT_EQ(0, status.serviceSpecificErrorCode());
898 EXPECT_EQ(td.expectedValue, value);
899 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900900 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900901 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
902 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
903 }
904 }
905}
906
907TEST_F(BinderTest, SetProcSysNet) {
908 static const struct {
909 const int ipversion;
910 const int which;
911 const char* ifname;
912 const char* parameter;
913 const char* value;
914 const int expectedReturnCode;
915 } kTestData[] = {
916 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
917 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
918 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
919 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
920 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
921 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
922 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
923 };
924
Sehee Park8659b8d2018-11-16 10:53:16 +0900925 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900926 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900927 const binder::Status status =
928 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900929
930 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900931 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900932 EXPECT_EQ(0, status.exceptionCode());
933 EXPECT_EQ(0, status.serviceSpecificErrorCode());
934 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900935 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900936 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
937 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
938 }
939 }
940}
Ben Schwartze7601812017-04-28 16:38:29 -0400941
Erik Kline38e51f12018-09-06 20:14:44 +0900942TEST_F(BinderTest, GetSetProcSysNet) {
943 const int ipversion = INetd::IPV6;
944 const int category = INetd::NEIGH;
945 const std::string& tun = sTun.name();
946 const std::string parameter("ucast_solicit");
947
948 std::string value{};
949 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
Maciej Żenczykowski7b789b92019-04-09 15:55:06 -0700950 ASSERT_FALSE(value.empty());
Erik Kline38e51f12018-09-06 20:14:44 +0900951 const int ival = std::stoi(value);
952 EXPECT_GT(ival, 0);
953 // Try doubling the parameter value (always best!).
954 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
955 .isOk());
956 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
957 EXPECT_EQ(2 * ival, std::stoi(value));
958 // Try resetting the parameter.
959 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
960 .isOk());
961 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
962 EXPECT_EQ(ival, std::stoi(value));
963}
964
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900965namespace {
966
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900967void expectNoTestCounterRules() {
968 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
969 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
970 std::string allRules = Join(runCommand(command), "\n");
971 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
972 }
973}
974
Bernie Innocentif6918262018-06-11 17:37:35 +0900975void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
976 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900977 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
978 path, if1.c_str(), if2.c_str(), pkt, byte));
979}
980
Bernie Innocentif6918262018-06-11 17:37:35 +0900981void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900982 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
983 path, if1.c_str(), if2.c_str()));
984 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
985 path, if2.c_str(), if1.c_str()));
986}
987
Luke Huangcaebcbb2018-09-27 20:37:14 +0800988std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
989 const std::string& iface) {
990 for (auto& stats : statsVec) {
991 if (stats.iface == iface) {
992 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
993 }
994 }
995 return {};
996}
997
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900998} // namespace
999
1000TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001001 expectNoTestCounterRules();
1002
1003 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1004 // disabling tethering. We don't check the return value because these commands will fail if
1005 // tethering is already enabled.
1006 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1007 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1008
1009 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1010 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1011 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
Luke Huang0f91cdc2019-05-29 17:55:51 +08001012
1013 // Ensure we won't use the same interface name, otherwise the test will fail.
1014 u_int32_t rNumber = arc4random_uniform(10000);
1015 std::string extIface1 = StringPrintf("netdtest_%u", rNumber);
1016 std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001017
1018 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1019 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1020 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1021 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1022 // RX is from external to internal, and TX is from internal to external.
1023 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1024 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1025
1026 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1027 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1028
1029 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1030 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1031
1032 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1033 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1034 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1035
Luke Huangcaebcbb2018-09-27 20:37:14 +08001036 std::vector<TetherStatsParcel> statsVec;
1037 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001038 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1039
Luke Huangcaebcbb2018-09-27 20:37:14 +08001040 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001041
Luke Huangcaebcbb2018-09-27 20:37:14 +08001042 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001043
1044 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1045 delTetherCounterValues(path, intIface1, extIface1);
1046 delTetherCounterValues(path, intIface2, extIface2);
1047 if (path == IP6TABLES_PATH) {
1048 delTetherCounterValues(path, intIface3, extIface2);
1049 }
1050 }
1051
1052 expectNoTestCounterRules();
1053}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001054
Luke Huang0051a622018-07-23 20:30:16 +08001055namespace {
1056
Luke Huanga5211072018-08-01 23:36:29 +08001057constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1058constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001059
1060static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1061 const char* chainName) {
1062 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1063 return runCommand(command);
1064}
1065
Luke Huang19b49c52018-10-22 12:12:05 +09001066// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001067bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001068 const std::string& expectedInterface,
1069 const std::string& expectedRule, const char* table) {
1070 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1071 for (const auto& rule : rules) {
1072 if (rule.find(expectedInterface) != std::string::npos) {
1073 if (rule.find(expectedRule) != std::string::npos) {
1074 return true;
1075 }
1076 }
1077 }
1078 return false;
1079}
1080
1081void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001082 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001083 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001084 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001085 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001086 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1087 IdletimerRule, RAW_TABLE));
1088 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001089 ifname, IdletimerRule, MANGLE_TABLE));
1090 }
1091}
1092
1093void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001094 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001095 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001096 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001097 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001098 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1099 IdletimerRule, RAW_TABLE));
1100 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001101 ifname, IdletimerRule, MANGLE_TABLE));
1102 }
1103}
1104
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001105} // namespace
1106
1107TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001108 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1109 // rule in the table. Because we only check the result after calling remove function. We might
1110 // check the actual rule which is removed by our function (maybe compare the results between
1111 // calling function before and after)
1112 binder::Status status;
1113 const struct TestData {
1114 const std::string ifname;
1115 int32_t timeout;
1116 const std::string classLabel;
1117 } idleTestData[] = {
1118 {"wlan0", 1234, "happyday"},
1119 {"rmnet_data0", 4567, "friday"},
1120 };
1121 for (const auto& td : idleTestData) {
1122 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1123 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1124 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1125
1126 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1127 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1128 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1129 }
1130}
1131
Luke Huanga67dd562018-07-17 19:58:25 +08001132namespace {
1133
1134constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1135constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1136
1137void expectStrictSetUidAccept(const int uid) {
1138 std::string uidRule = StringPrintf("owner UID match %u", uid);
1139 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1140 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001141 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1142 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001143 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1144 }
1145}
1146
1147void expectStrictSetUidLog(const int uid) {
1148 static const char logRule[] = "st_penalty_log all";
1149 std::string uidRule = StringPrintf("owner UID match %u", uid);
1150 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1151 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001152 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1153 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001154 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1155 }
1156}
1157
1158void expectStrictSetUidReject(const int uid) {
1159 static const char rejectRule[] = "st_penalty_reject all";
1160 std::string uidRule = StringPrintf("owner UID match %u", uid);
1161 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1162 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001163 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1164 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001165 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1166 }
1167}
1168
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001169} // namespace
1170
1171TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001172 binder::Status status;
1173 int32_t uid = randomUid();
1174
1175 // setUidCleartextPenalty Policy:Log with randomUid
1176 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1177 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1178 expectStrictSetUidLog(uid);
1179
1180 // setUidCleartextPenalty Policy:Accept with randomUid
1181 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1182 expectStrictSetUidAccept(uid);
1183
1184 // setUidCleartextPenalty Policy:Reject with randomUid
1185 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1186 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1187 expectStrictSetUidReject(uid);
1188
1189 // setUidCleartextPenalty Policy:Accept with randomUid
1190 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1191 expectStrictSetUidAccept(uid);
1192
1193 // test wrong policy
1194 int32_t wrongPolicy = -123;
1195 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1196 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1197}
1198
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001199namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001200
Luke Huangd1675922019-03-11 17:29:27 +08001201std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001202 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001203 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001204 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1205 // ...
1206 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1207
Luke Huangd1675922019-03-11 17:29:27 +08001208 // (dnsmasq)
1209 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1210
1211 if (maxTries == 0) return {};
1212
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001213 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001214 std::vector<std::string> result;
1215 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001216 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001217 if (result.size() || ++run > maxTries) {
1218 break;
1219 }
1220
Luke Huang728cf4c2019-03-14 19:43:02 +08001221 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001222 }
1223 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001224}
1225
Luke Huangd1675922019-03-11 17:29:27 +08001226void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001227 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001228}
1229
Luke Huang728cf4c2019-03-14 19:43:02 +08001230void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001231 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001232}
1233
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001234} // namespace
1235
1236TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001237 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001238
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001239 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1240 std::string clatAddress;
1241 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001242
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001243 // Can't start clatd on an interface that's not part of any network...
1244 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1245 EXPECT_FALSE(status.isOk());
1246 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1247
1248 // ... so create a test physical network and add our tun to it.
1249 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1250 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1251
1252 // Prefix must be 96 bits long.
1253 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1254 EXPECT_FALSE(status.isOk());
1255 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1256
1257 // Can't start clatd unless there's a default route...
1258 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1259 EXPECT_FALSE(status.isOk());
1260 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1261
1262 // so add a default route.
1263 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1264
1265 // Can't start clatd unless there's a global address...
1266 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1267 EXPECT_FALSE(status.isOk());
1268 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1269
1270 // ... so add a global address.
1271 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001272 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001273
1274 // Now expect clatd to start successfully.
1275 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1276 EXPECT_TRUE(status.isOk());
1277 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1278
1279 // Starting it again returns EBUSY.
1280 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1281 EXPECT_FALSE(status.isOk());
1282 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1283
Luke Huangd1675922019-03-11 17:29:27 +08001284 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001285
1286 // Expect clatd to stop successfully.
1287 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001288 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001289 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001290
1291 // Stopping a clatd that doesn't exist returns ENODEV.
1292 status = mNetd->clatdStop(sTun.name());
1293 EXPECT_FALSE(status.isOk());
1294 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001295 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001296
1297 // Clean up.
1298 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1299 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1300 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001301}
Luke Huang457d4702018-08-16 15:39:15 +08001302
1303namespace {
1304
1305bool getIpfwdV4Enable() {
1306 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1307 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1308 EXPECT_TRUE(!result.empty());
1309 int v4Enable = std::stoi(result[0]);
1310 return v4Enable;
1311}
1312
1313bool getIpfwdV6Enable() {
Lorenzo Colitti76edb4b2019-05-09 11:46:45 +09001314 static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
Luke Huang457d4702018-08-16 15:39:15 +08001315 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1316 EXPECT_TRUE(!result.empty());
1317 int v6Enable = std::stoi(result[0]);
1318 return v6Enable;
1319}
1320
1321void expectIpfwdEnable(bool enable) {
1322 int enableIPv4 = getIpfwdV4Enable();
1323 int enableIPv6 = getIpfwdV6Enable();
1324 EXPECT_EQ(enable, enableIPv4);
1325 EXPECT_EQ(enable, enableIPv6);
1326}
1327
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001328bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001329 std::vector<std::string> rules = listIpRules(ipVersion);
1330 for (const auto& rule : rules) {
1331 if (rule.find(ipfwdRule) != std::string::npos) {
1332 return true;
1333 }
1334 }
1335 return false;
1336}
1337
1338void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1339 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1340
1341 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1342 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1343 }
1344}
1345
1346void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1347 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1348
1349 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1350 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1351 }
1352}
1353
1354} // namespace
1355
1356TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001357 // Get ipfwd requester list from Netd
1358 std::vector<std::string> requesterList;
1359 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001360 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001361
1362 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001363 if (requesterList.size() == 0) {
1364 // No requester in Netd, ipfwd should be disabled
1365 // So add one test requester and verify
1366 status = mNetd->ipfwdEnableForwarding("TestRequester");
1367 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001368
Luke Huang728cf4c2019-03-14 19:43:02 +08001369 expectIpfwdEnable(true);
1370 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1371 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1372 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001373
Luke Huang728cf4c2019-03-14 19:43:02 +08001374 // Remove test one, verify again
1375 status = mNetd->ipfwdDisableForwarding("TestRequester");
1376 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1377
1378 expectIpfwdEnable(false);
1379 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1380 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1381 EXPECT_FALSE(ipfwdEnabled);
1382 } else {
1383 // Disable all requesters
1384 for (const auto& requester : requesterList) {
1385 status = mNetd->ipfwdDisableForwarding(requester);
1386 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1387 }
1388
1389 // After disable all requester, ipfwd should be disabled
1390 expectIpfwdEnable(false);
1391 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1392 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1393 EXPECT_FALSE(ipfwdEnabled);
1394
1395 // Enable them back
1396 for (const auto& requester : requesterList) {
1397 status = mNetd->ipfwdEnableForwarding(requester);
1398 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1399 }
1400
1401 // ipfwd should be enabled
1402 expectIpfwdEnable(true);
1403 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1404 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1405 EXPECT_TRUE(ipfwdEnabled);
1406 }
Luke Huang457d4702018-08-16 15:39:15 +08001407}
1408
1409TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001410 // Add test physical network
1411 EXPECT_TRUE(
1412 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1413 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1414 EXPECT_TRUE(
1415 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1416 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001417
Luke Huangd1827b82019-02-15 15:03:27 +08001418 binder::Status status =
1419 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1420 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1421 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001422
Luke Huangd1827b82019-02-15 15:03:27 +08001423 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1424 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1425 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001426}
Luke Huang531f5d32018-08-03 15:19:05 +08001427
1428namespace {
1429
1430constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1431constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1432constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1433constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1434constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001435constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001436
Luke Huang19b49c52018-10-22 12:12:05 +09001437// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1438// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001439bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1440 const char* chainName, const std::string& expectedTargetA,
1441 const std::string& expectedTargetB) {
1442 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1443 int matchCount = 0;
1444
1445 for (const auto& rule : rules) {
1446 if (rule.find(expectedTargetA) != std::string::npos) {
1447 if (rule.find(expectedTargetB) != std::string::npos) {
1448 matchCount++;
1449 }
1450 }
1451 }
1452 return matchCount == expectedCount;
1453}
1454
1455void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1456 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1457 std::string result = "";
1458
1459 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001460 // Quota value might be decreased while matching packets
1461 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001462}
1463
1464void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1465 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1466 std::string quotaRule = StringPrintf("quota %s", ifname);
1467
1468 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1469 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1470 BANDWIDTH_COSTLY_IF));
1471 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1472 BANDWIDTH_COSTLY_IF));
1473 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1474 BANDWIDTH_COSTLY_IF));
1475 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1476 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1477 }
1478 expectXtQuotaValueEqual(ifname, quotaBytes);
1479}
1480
1481void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1482 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1483 std::string quotaRule = StringPrintf("quota %s", ifname);
1484
1485 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1486 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1487 BANDWIDTH_COSTLY_IF));
1488 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1489 BANDWIDTH_COSTLY_IF));
1490 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1491 BANDWIDTH_COSTLY_IF));
1492 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1493 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1494 }
1495}
1496
1497void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1498 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1499 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1500 std::string alertName = StringPrintf("%sAlert", ifname);
1501
1502 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1503 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1504 }
1505 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1506}
1507
1508void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1509 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1510 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1511
1512 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1513 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1514 }
1515}
1516
1517void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1518 static const char globalAlertRule[] = "quota globalAlert";
1519 static const char globalAlertName[] = "globalAlert";
1520
1521 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001522 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001523 }
1524 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1525}
1526
1527void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1528 std::string uidRule = StringPrintf("owner UID match %u", uid);
1529
1530 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1531 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1532 }
1533}
1534
1535void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1536 std::string uidRule = StringPrintf("owner UID match %u", uid);
1537
1538 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1539 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1540 }
1541}
1542
1543} // namespace
1544
1545TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1546 long testQuotaBytes = 5550;
1547
1548 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001549 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001550 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1551
1552 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1553 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1554 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1555
1556 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1557 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1558 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1559
1560 // Remove test physical network
1561 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1562}
1563
1564TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1565 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001566 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001567 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001568 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001569 // Need to have a prior interface quota set to set an alert
1570 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1571 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1572 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1573 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1574
1575 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1576 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1577 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1578
1579 // Remove interface quota
1580 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1581 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1582 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1583
1584 // Remove test physical network
1585 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1586}
1587
1588TEST_F(BinderTest, BandwidthSetGlobalAlert) {
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001589 int64_t testAlertBytes = 2097200;
Luke Huang531f5d32018-08-03 15:19:05 +08001590
1591 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1592 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1593 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1594
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001595 testAlertBytes = 2098230;
Luke Huang531f5d32018-08-03 15:19:05 +08001596 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1597 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1598 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1599}
1600
1601TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1602 SKIP_IF_BPF_SUPPORTED;
1603
1604 int32_t uid = randomUid();
1605 static const char targetReject[] = "REJECT";
1606 static const char targetReturn[] = "RETURN";
1607
1608 // add NaughtyApp
1609 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1610 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1611 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1612
1613 // remove NaughtyApp
1614 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1615 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1616 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1617
1618 // add NiceApp
1619 status = mNetd->bandwidthAddNiceApp(uid);
1620 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1621 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1622
1623 // remove NiceApp
1624 status = mNetd->bandwidthRemoveNiceApp(uid);
1625 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1626 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1627}
Luke Huangb5733d72018-08-21 17:17:19 +08001628
1629namespace {
1630
Luke Huangc3252cc2018-10-16 15:43:23 +08001631std::string ipRouteString(const std::string& ifName, const std::string& dst,
Tyler Wearfa94a272019-12-05 15:01:48 -08001632 const std::string& nextHop, const std::string& mtu) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001633 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1634
1635 if (!nextHop.empty()) {
1636 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001637 }
1638
Tyler Wearfa94a272019-12-05 15:01:48 -08001639 dstString += " dev " + ifName;
1640
1641 if (!mtu.empty()) {
1642 dstString += " proto static";
1643 // IPv6 routes report the metric, IPv4 routes report the scope.
1644 // TODO: move away from specifying the entire string and use a regexp instead.
1645 if (dst.find(':') != std::string::npos) {
1646 dstString += " metric 1024";
1647 } else {
1648 if (nextHop.empty()) {
1649 dstString += " scope link";
1650 }
1651 }
1652 dstString += " mtu " + mtu;
1653 }
1654
1655 return dstString;
1656}
1657
1658void expectNetworkRouteExistsWithMtu(const char* ipVersion, const std::string& ifName,
1659 const std::string& dst, const std::string& nextHop,
1660 const std::string& mtu, const char* table) {
1661 std::string routeString = ipRouteString(ifName, dst, nextHop, mtu);
1662 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop, mtu)))
1663 << "Couldn't find route to " << dst << ": '" << routeString << "' in table " << table;
Luke Huangb670d162018-08-23 20:01:13 +08001664}
1665
Luke Huangc3252cc2018-10-16 15:43:23 +08001666void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1667 const std::string& dst, const std::string& nextHop,
1668 const char* table) {
Tyler Wearfa94a272019-12-05 15:01:48 -08001669 expectNetworkRouteExistsWithMtu(ipVersion, ifName, dst, nextHop, "", table);
Luke Huangc3252cc2018-10-16 15:43:23 +08001670}
1671
1672void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001673 const std::string& dst, const std::string& nextHop,
1674 const char* table) {
Tyler Wearfa94a272019-12-05 15:01:48 -08001675 std::string routeString = ipRouteString(ifName, dst, nextHop, "");
1676 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop, "")))
1677 << "Found unexpected route " << routeString << " in table " << table;
Luke Huangb670d162018-08-23 20:01:13 +08001678}
1679
1680bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1681 std::vector<std::string> rules = listIpRules(ipVersion);
1682 for (const auto& rule : rules) {
1683 if (rule.find(ipRule) != std::string::npos) {
1684 return true;
1685 }
1686 }
1687 return false;
1688}
1689
1690void expectNetworkDefaultIpRuleExists(const char* ifName) {
1691 std::string networkDefaultRule =
1692 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1693
1694 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1695 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1696 }
1697}
1698
1699void expectNetworkDefaultIpRuleDoesNotExist() {
1700 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1701
1702 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1703 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1704 }
1705}
1706
1707void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1708 std::string networkPermissionRule = "";
1709 switch (permission) {
1710 case INetd::PERMISSION_NONE:
1711 networkPermissionRule = StringPrintf(
1712 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1713 break;
1714 case INetd::PERMISSION_NETWORK:
1715 networkPermissionRule = StringPrintf(
1716 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1717 break;
1718 case INetd::PERMISSION_SYSTEM:
1719 networkPermissionRule = StringPrintf(
1720 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1721 break;
1722 }
1723
1724 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1725 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1726 }
1727}
1728
1729// TODO: It is a duplicate function, need to remove it
1730bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1731 const std::string& expectedInterface,
1732 const std::string& expectedRule,
1733 const char* table) {
1734 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1735 for (const auto& rule : rules) {
1736 if (rule.find(expectedInterface) != std::string::npos) {
1737 if (rule.find(expectedRule) != std::string::npos) {
1738 return true;
1739 }
1740 }
1741 }
1742 return false;
1743}
1744
1745void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1746 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1747 std::string networkIncomingPacketMarkRule = "";
1748 switch (permission) {
1749 case INetd::PERMISSION_NONE:
1750 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1751 break;
1752 case INetd::PERMISSION_NETWORK:
1753 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1754 break;
1755 case INetd::PERMISSION_SYSTEM:
1756 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1757 break;
1758 }
1759
1760 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1761 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1762 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1763 }
1764}
1765
1766} // namespace
1767
1768TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001769 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001770 const char* ipVersion;
1771 const char* testDest;
1772 const char* testNextHop;
1773 const bool expectSuccess;
1774 } kTestData[] = {
1775 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001776 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1777 {IP_RULE_V4, "10.251.0.0/16", "", true},
1778 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1779 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001780 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001781 {IP_RULE_V6, "::/0", "2001:db8::", true},
1782 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001783 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1784 };
1785
Luke Huangc3252cc2018-10-16 15:43:23 +08001786 static const struct {
1787 const char* ipVersion;
1788 const char* testDest;
1789 const char* testNextHop;
1790 } kTestDataWithNextHop[] = {
1791 {IP_RULE_V4, "10.251.10.0/30", ""},
1792 {IP_RULE_V6, "2001:db8::/32", ""},
1793 };
1794
Luke Huangb670d162018-08-23 20:01:13 +08001795 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001796 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001797 const int testUid = randomUid();
1798 const std::vector<int32_t> testUids = {testUid};
1799
1800 // Add test physical network
1801 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1802 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1803
Luke Huangc3252cc2018-10-16 15:43:23 +08001804 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001805 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001806 const auto& td = kTestDataWithNextHop[i];
1807
1808 // All route for test tun will disappear once the tun interface is deleted.
1809 binder::Status status =
1810 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1811 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1812 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1813 sTun.name().c_str());
1814
1815 // Add system permission for test uid, setup route in legacy system table.
1816 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1817
1818 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1819 testUid);
1820 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1821 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1822 testTableLegacySystem);
1823
1824 // Remove system permission for test uid, setup route in legacy network table.
1825 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1826
1827 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1828 testUid);
1829 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1830 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1831 testTableLegacyNetwork);
1832 }
1833
Sehee Park8659b8d2018-11-16 10:53:16 +09001834 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001835 const auto& td = kTestData[i];
1836
1837 binder::Status status =
1838 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1839 if (td.expectSuccess) {
1840 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001841 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001842 sTun.name().c_str());
1843 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001844 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1845 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001846 }
1847
1848 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1849 if (td.expectSuccess) {
1850 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001851 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1852 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001853 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001854 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1855 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001856 }
1857
Luke Huangc3252cc2018-10-16 15:43:23 +08001858 // Add system permission for test uid, route will be added into legacy system table.
1859 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001860
1861 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1862 testUid);
1863 if (td.expectSuccess) {
1864 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001865 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001866 testTableLegacySystem);
1867 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001868 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1869 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001870 }
1871
1872 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1873 td.testNextHop, testUid);
1874 if (td.expectSuccess) {
1875 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001876 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1877 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001878 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001879 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1880 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001881 }
1882
Luke Huangc3252cc2018-10-16 15:43:23 +08001883 // Remove system permission for test uid, route will be added into legacy network table.
1884 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1885
1886 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1887 testUid);
1888 if (td.expectSuccess) {
1889 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1890 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1891 testTableLegacyNetwork);
1892 } else {
1893 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1894 EXPECT_NE(0, status.serviceSpecificErrorCode());
1895 }
1896
1897 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1898 td.testNextHop, testUid);
1899 if (td.expectSuccess) {
1900 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1901 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1902 testTableLegacyNetwork);
1903 } else {
1904 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1905 EXPECT_NE(0, status.serviceSpecificErrorCode());
1906 }
Luke Huangb670d162018-08-23 20:01:13 +08001907 }
1908
Tyler Wearfa94a272019-12-05 15:01:48 -08001909 for (size_t i = 0; i < std::size(kTestData); i++) {
1910 const auto& td = kTestData[i];
1911 int mtu = (i % 2) ? 1480 : 1280;
1912
1913 android::net::RouteInfoParcel parcel;
1914 parcel.ifName = sTun.name();
1915 parcel.destination = td.testDest;
1916 parcel.nextHop = td.testNextHop;
1917 parcel.mtu = mtu;
1918 binder::Status status = mNetd->networkAddRouteParcel(TEST_NETID1, parcel);
1919 if (td.expectSuccess) {
1920 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1921 expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1922 std::to_string(parcel.mtu), sTun.name().c_str());
1923 } else {
1924 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1925 EXPECT_NE(0, status.serviceSpecificErrorCode());
1926 }
1927
1928 parcel.mtu = 1337;
1929 status = mNetd->networkUpdateRouteParcel(TEST_NETID1, parcel);
1930 if (td.expectSuccess) {
1931 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1932 expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1933 std::to_string(parcel.mtu), sTun.name().c_str());
1934 } else {
1935 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1936 EXPECT_NE(0, status.serviceSpecificErrorCode());
1937 }
1938
1939 status = mNetd->networkRemoveRouteParcel(TEST_NETID1, parcel);
1940 if (td.expectSuccess) {
1941 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1942 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1943 sTun.name().c_str());
1944 } else {
1945 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1946 EXPECT_NE(0, status.serviceSpecificErrorCode());
1947 }
1948 }
Luke Huangb670d162018-08-23 20:01:13 +08001949 // Remove test physical network
1950 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1951}
1952
1953TEST_F(BinderTest, NetworkPermissionDefault) {
1954 // Add test physical network
1955 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1956 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1957
Luke Huangc3252cc2018-10-16 15:43:23 +08001958 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001959 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1960 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001961
1962 // Test SetDefault
1963 status = mNetd->networkSetDefault(TEST_NETID1);
1964 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1965 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1966
1967 status = mNetd->networkClearDefault();
1968 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1969 expectNetworkDefaultIpRuleDoesNotExist();
1970
Luke Huangd2861982019-05-17 19:47:28 +08001971 // Set default network back
1972 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001973 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1974
1975 // Test SetPermission
1976 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1977 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1978 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1979 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1980
1981 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1982 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1983 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1984 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1985
1986 // Remove test physical network
1987 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1988}
1989
1990TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
Luke Huang854e2992019-05-29 16:42:48 +08001991 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001992 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1993 bool ret = false;
Luke Huang854e2992019-05-29 16:42:48 +08001994 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08001995 EXPECT_TRUE(ret);
1996
Luke Huang854e2992019-05-29 16:42:48 +08001997 status = mNetd->networkSetProtectDeny(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001998 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang854e2992019-05-29 16:42:48 +08001999
2000 // Clear uid permission before calling networkCanProtect to ensure
2001 // the call won't be affected by uid permission.
2002 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
2003
2004 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002005 EXPECT_FALSE(ret);
2006}
2007
2008namespace {
2009
Luke Huangb5733d72018-08-21 17:17:19 +08002010int readIntFromPath(const std::string& path) {
2011 std::string result = "";
2012 EXPECT_TRUE(ReadFileToString(path, &result));
2013 return std::stoi(result);
2014}
2015
2016int getTetherAcceptIPv6Ra(const std::string& ifName) {
2017 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
2018 return readIntFromPath(path);
2019}
2020
2021bool getTetherAcceptIPv6Dad(const std::string& ifName) {
2022 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
2023 return readIntFromPath(path);
2024}
2025
2026int getTetherIPv6DadTransmits(const std::string& ifName) {
2027 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
2028 return readIntFromPath(path);
2029}
2030
2031bool getTetherEnableIPv6(const std::string& ifName) {
2032 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2033 int disableIPv6 = readIntFromPath(path);
2034 return !disableIPv6;
2035}
2036
2037bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2038 for (const auto& iface : ifList) {
2039 if (iface == ifName) {
2040 return true;
2041 }
2042 }
2043 return false;
2044}
2045
2046void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2047 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2048 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2049 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2050 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2051}
2052
2053void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2054 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2055 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2056 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2057 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2058}
2059
2060void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2061 const std::string& ifName) {
2062 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2063}
2064
2065void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2066 const std::string& ifName) {
2067 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2068}
2069
2070void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2071 const std::vector<std::string>& testDnsAddrs) {
2072 EXPECT_TRUE(dnsList == testDnsAddrs);
2073}
2074
2075} // namespace
2076
2077TEST_F(BinderTest, TetherStartStopStatus) {
2078 std::vector<std::string> noDhcpRange = {};
2079 static const char dnsdName[] = "dnsmasq";
2080
Luke Huang91bd3e12019-08-20 11:33:52 +08002081 for (bool usingLegacyDnsProxy : {true, false}) {
Chiachang Wang08cb2112019-12-10 09:53:24 +08002082 android::net::TetherConfigParcel config;
2083 config.usingLegacyDnsProxy = usingLegacyDnsProxy;
2084 config.dhcpRanges = noDhcpRange;
2085 binder::Status status = mNetd->tetherStartWithConfiguration(config);
Luke Huang91bd3e12019-08-20 11:33:52 +08002086 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2087 SCOPED_TRACE(StringPrintf("usingLegacyDnsProxy: %d", usingLegacyDnsProxy));
2088 if (usingLegacyDnsProxy == true) {
2089 expectProcessExists(dnsdName);
2090 } else {
2091 expectProcessDoesNotExist(dnsdName);
2092 }
Luke Huangb5733d72018-08-21 17:17:19 +08002093
Luke Huang91bd3e12019-08-20 11:33:52 +08002094 bool tetherEnabled;
2095 status = mNetd->tetherIsEnabled(&tetherEnabled);
2096 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2097 EXPECT_TRUE(tetherEnabled);
Luke Huangb5733d72018-08-21 17:17:19 +08002098
Luke Huang91bd3e12019-08-20 11:33:52 +08002099 status = mNetd->tetherStop();
2100 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2101 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002102
Luke Huang91bd3e12019-08-20 11:33:52 +08002103 status = mNetd->tetherIsEnabled(&tetherEnabled);
2104 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2105 EXPECT_FALSE(tetherEnabled);
2106 }
Luke Huangb5733d72018-08-21 17:17:19 +08002107}
2108
2109TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2110 // TODO: verify if dnsmasq update interface successfully
2111
2112 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2113 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2114 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2115
2116 std::vector<std::string> ifList;
2117 status = mNetd->tetherInterfaceList(&ifList);
2118 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2119 expectTetherInterfaceExists(ifList, sTun.name());
2120
2121 status = mNetd->tetherInterfaceRemove(sTun.name());
2122 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2123 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2124
2125 status = mNetd->tetherInterfaceList(&ifList);
2126 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2127 expectTetherInterfaceNotExists(ifList, sTun.name());
2128}
2129
2130TEST_F(BinderTest, TetherDnsSetList) {
2131 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002132 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2133 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002134
2135 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2136 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2137
2138 std::vector<std::string> dnsList;
2139 status = mNetd->tetherDnsList(&dnsList);
2140 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2141 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002142}
2143
2144namespace {
2145
2146constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2147constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2148constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2149constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2150constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2151constexpr char FIREWALL_STANDBY[] = "fw_standby";
2152constexpr char targetReturn[] = "RETURN";
2153constexpr char targetDrop[] = "DROP";
2154
2155void expectFirewallWhitelistMode() {
2156 static const char dropRule[] = "DROP all";
2157 static const char rejectRule[] = "REJECT all";
2158 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2159 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2160 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2161 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2162 }
2163}
2164
2165void expectFirewallBlacklistMode() {
2166 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2167 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2168 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2169 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2170 }
2171}
2172
2173bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2174 const std::string& expectedInterface,
2175 const std::string& expectedRule) {
2176 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2177 // Expected rule:
2178 // Chain fw_INPUT (1 references)
2179 // pkts bytes target prot opt in out source destination
2180 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2181 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2182 int firstRuleIndex = 2;
2183 if (rules.size() < 4) return false;
2184 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2185 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2186 return true;
2187 }
2188 }
2189 return false;
2190}
2191
2192// TODO: It is a duplicate function, need to remove it
2193bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2194 const std::string& expectedInterface,
2195 const std::string& expectedRule) {
2196 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2197 for (const auto& rule : rules) {
2198 if (rule.find(expectedInterface) != std::string::npos) {
2199 if (rule.find(expectedRule) != std::string::npos) {
2200 return true;
2201 }
2202 }
2203 }
2204 return false;
2205}
2206
2207void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2208 static const char returnRule[] = "RETURN all";
2209 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2210 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2211 returnRule));
2212 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2213 returnRule));
2214 }
2215}
2216
2217void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2218 static const char returnRule[] = "RETURN all";
2219 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2220 EXPECT_FALSE(
2221 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2222 EXPECT_FALSE(
2223 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2224 }
2225}
2226
2227bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2228 const std::string& expectedTarget,
2229 const std::string& expectedRule) {
2230 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2231 int firstRuleIndex = 2;
2232 if (rules.size() < 4) return false;
2233 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2234 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2235 return true;
2236 }
2237 }
2238 return false;
2239}
2240
2241bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2242 const std::string& expectedTarget,
2243 const std::string& expectedRule) {
2244 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2245 int lastRuleIndex = rules.size() - 1;
2246 if (lastRuleIndex < 0) return false;
2247 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2248 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2249 return true;
2250 }
2251 }
2252 return false;
2253}
2254
2255void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2256 std::string uidRule = StringPrintf("owner UID match %u", uid);
2257 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2258 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2259}
2260
2261void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2262 std::string uidRule = StringPrintf("owner UID match %u", uid);
2263 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2264 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2265}
2266
2267void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2268 std::string uidRule = StringPrintf("owner UID match %u", uid);
2269 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2270 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2271}
2272
2273void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2274 std::string uidRule = StringPrintf("owner UID match %u", uid);
2275 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2276 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2277}
2278
2279bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2280 std::vector<std::string> inputRules =
2281 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2282 std::vector<std::string> outputRules =
2283 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2284 int inputLastRuleIndex = inputRules.size() - 1;
2285 int outputLastRuleIndex = outputRules.size() - 1;
2286
2287 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2288 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2289 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2290 return true;
2291 }
2292 }
2293 return false;
2294}
2295
2296void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2297 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2298 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2299}
2300
2301void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2302 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2303 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2304 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2305 }
2306}
2307
2308} // namespace
2309
2310TEST_F(BinderTest, FirewallSetFirewallType) {
2311 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2312 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2313 expectFirewallWhitelistMode();
2314
2315 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2316 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2317 expectFirewallBlacklistMode();
2318
2319 // set firewall type blacklist twice
2320 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2321 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2322 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2323 expectFirewallBlacklistMode();
2324
2325 // set firewall type whitelist twice
2326 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2327 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2328 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2329 expectFirewallWhitelistMode();
2330
2331 // reset firewall type to default
2332 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2333 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2334 expectFirewallBlacklistMode();
2335}
2336
2337TEST_F(BinderTest, FirewallSetInterfaceRule) {
2338 // setinterfaceRule is not supported in BLACKLIST MODE
2339 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2340 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2341
2342 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2343 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2344
2345 // set WHITELIST mode first
2346 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2347 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2348
2349 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2350 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2351 expectFirewallInterfaceRuleAllowExists(sTun.name());
2352
2353 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2354 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2355 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2356
2357 // reset firewall mode to default
2358 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2359 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2360 expectFirewallBlacklistMode();
2361}
2362
2363TEST_F(BinderTest, FirewallSetUidRule) {
2364 SKIP_IF_BPF_SUPPORTED;
2365
2366 int32_t uid = randomUid();
2367
2368 // Doze allow
2369 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2370 INetd::FIREWALL_RULE_ALLOW);
2371 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2372 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2373
2374 // Doze deny
2375 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2376 INetd::FIREWALL_RULE_DENY);
2377 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2378 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2379
2380 // Powersave allow
2381 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2382 INetd::FIREWALL_RULE_ALLOW);
2383 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2384 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2385
2386 // Powersave deny
2387 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2388 INetd::FIREWALL_RULE_DENY);
2389 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2390 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2391
2392 // Standby deny
2393 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2394 INetd::FIREWALL_RULE_DENY);
2395 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2396 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2397
2398 // Standby allow
2399 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2400 INetd::FIREWALL_RULE_ALLOW);
2401 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2402 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2403
2404 // None deny in BLACKLIST
2405 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2406 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2407 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2408 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2409
2410 // None allow in BLACKLIST
2411 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2412 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2413 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2414 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2415
2416 // set firewall type whitelist twice
2417 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2418 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2419 expectFirewallWhitelistMode();
2420
2421 // None allow in WHITELIST
2422 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2423 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2424 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2425 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2426
2427 // None deny in WHITELIST
2428 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2429 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2430 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2431 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2432
2433 // reset firewall mode to default
2434 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2435 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2436 expectFirewallBlacklistMode();
2437}
2438
2439TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2440 SKIP_IF_BPF_SUPPORTED;
2441
2442 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2443 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2444 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2445
2446 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2447 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2448 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2449
2450 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2451 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2452 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2453
2454 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2455 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2456 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2457
2458 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2459 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2460 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2461
2462 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2463 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2464 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2465}
Luke Huangf7782042018-08-08 13:13:04 +08002466
2467namespace {
2468
2469std::string hwAddrToStr(unsigned char* hwaddr) {
2470 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2471 hwaddr[4], hwaddr[5]);
2472}
2473
2474int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2475 int prefixLength = 0;
2476 uint32_t m = ntohl(mask);
2477 while (m & (1 << 31)) {
2478 prefixLength++;
2479 m = m << 1;
2480 }
2481 return prefixLength;
2482}
2483
2484std::string toStdString(const String16& s) {
2485 return std::string(String8(s.string()));
2486}
2487
2488android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2489 const auto& sys = sSyscalls.get();
2490 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2491 EXPECT_TRUE(isOk(fd.status()));
2492
2493 struct ifreq ifr = {};
2494 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2495
2496 return sys.ioctl(fd.value(), flag, &ifr);
2497}
2498
2499std::string getInterfaceHwAddr(const std::string& ifName) {
2500 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2501
2502 unsigned char hwaddr[ETH_ALEN] = {};
2503 if (isOk(res.status())) {
2504 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2505 }
2506
2507 return hwAddrToStr(hwaddr);
2508}
2509
2510int getInterfaceIPv4Prefix(const std::string& ifName) {
2511 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2512
2513 int prefixLength = 0;
2514 if (isOk(res.status())) {
2515 prefixLength = ipv4NetmaskToPrefixLength(
2516 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2517 }
2518
2519 return prefixLength;
2520}
2521
2522std::string getInterfaceIPv4Addr(const std::string& ifName) {
2523 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2524
2525 struct in_addr addr = {};
2526 if (isOk(res.status())) {
2527 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2528 }
2529
2530 return std::string(inet_ntoa(addr));
2531}
2532
2533std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2534 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2535
2536 unsigned flags = 0;
2537 if (isOk(res.status())) {
2538 flags = res.value().ifr_flags;
2539 }
2540
2541 std::vector<std::string> ifFlags;
2542 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2543 : toStdString(INetd::IF_STATE_DOWN()));
2544
2545 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2546 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2547 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2548 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2549 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2550
2551 return ifFlags;
2552}
2553
2554bool compareListInterface(const std::vector<std::string>& interfaceList) {
2555 const auto& res = InterfaceController::getIfaceNames();
2556 EXPECT_TRUE(isOk(res));
2557
2558 std::vector<std::string> resIfList;
2559 resIfList.reserve(res.value().size());
2560 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2561
2562 return resIfList == interfaceList;
2563}
2564
2565int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2566 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2567 return readIntFromPath(path);
2568}
2569
2570bool getInterfaceEnableIPv6(const std::string& ifName) {
2571 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2572
2573 int disableIPv6 = readIntFromPath(path);
2574 return !disableIPv6;
2575}
2576
2577int getInterfaceMtu(const std::string& ifName) {
2578 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2579 return readIntFromPath(path);
2580}
2581
2582void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2583 EXPECT_TRUE(compareListInterface(interfaceList));
2584}
2585
2586void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2587 const InterfaceConfigurationParcel& interfaceCfg) {
2588 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2589 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2590 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2591 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2592}
2593
2594void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2595 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2596 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2597
2598 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2599 for (const auto& flag : setCfg.flags) {
2600 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2601 }
2602}
2603
2604void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2605 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2606 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2607}
2608
2609void expectInterfaceNoAddr(const std::string& ifName) {
2610 // noAddr
2611 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2612 // noPrefix
2613 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2614}
2615
2616void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2617 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2618 EXPECT_EQ(enableIPv6, enable);
2619}
2620
2621void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2622 int mtuSize = getInterfaceMtu(ifName);
2623 EXPECT_EQ(mtu, mtuSize);
2624}
2625
2626InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2627 const std::string& addr, int prefixLength,
2628 const std::vector<std::string>& flags) {
2629 InterfaceConfigurationParcel cfg;
2630 cfg.ifName = ifName;
2631 cfg.hwAddr = "";
2632 cfg.ipv4Addr = addr;
2633 cfg.prefixLength = prefixLength;
2634 cfg.flags = flags;
2635 return cfg;
2636}
2637
2638void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2639 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2640 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2641
2642 for (const auto& flag : expectedFlags) {
2643 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2644 interfaceCfg.flags.end());
2645 }
2646
2647 for (const auto& flag : unexpectedFlags) {
2648 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2649 interfaceCfg.flags.end());
2650 }
2651}
2652
2653} // namespace
2654
2655TEST_F(BinderTest, InterfaceList) {
2656 std::vector<std::string> interfaceListResult;
2657
2658 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2659 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2660 expectInterfaceList(interfaceListResult);
2661}
2662
2663TEST_F(BinderTest, InterfaceGetCfg) {
2664 InterfaceConfigurationParcel interfaceCfgResult;
2665
2666 // Add test physical network
2667 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2668 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2669
2670 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2671 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2672 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2673 expectTunFlags(interfaceCfgResult);
2674
2675 // Remove test physical network
2676 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2677}
2678
2679TEST_F(BinderTest, InterfaceSetCfg) {
2680 const std::string testAddr = "192.0.2.3";
2681 const int testPrefixLength = 24;
2682 std::vector<std::string> upFlags = {"up"};
2683 std::vector<std::string> downFlags = {"down"};
2684
2685 // Add test physical network
2686 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2687 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2688
2689 // Set tun interface down.
2690 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2691 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2692 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2693 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2694
2695 // Set tun interface up again.
2696 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2697 status = mNetd->interfaceSetCfg(interfaceCfg);
2698 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2699 status = mNetd->interfaceClearAddrs(sTun.name());
2700 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2701
2702 // Remove test physical network
2703 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2704}
2705
2706TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2707 // enable
2708 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2709 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2710 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2711
2712 // disable
2713 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2714 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2715 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2716}
2717
2718TEST_F(BinderTest, InterfaceClearAddr) {
2719 const std::string testAddr = "192.0.2.3";
2720 const int testPrefixLength = 24;
2721 std::vector<std::string> noFlags{};
2722
2723 // Add test physical network
2724 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2725 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2726
2727 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2728 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2729 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2730 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2731
2732 status = mNetd->interfaceClearAddrs(sTun.name());
2733 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2734 expectInterfaceNoAddr(sTun.name());
2735
2736 // Remove test physical network
2737 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2738}
2739
2740TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2741 // Add test physical network
2742 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2743 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2744
2745 // disable
2746 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2747 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2748 expectInterfaceEnableIPv6(sTun.name(), false);
2749
2750 // enable
2751 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2752 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2753 expectInterfaceEnableIPv6(sTun.name(), true);
2754
2755 // Remove test physical network
2756 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2757}
2758
2759TEST_F(BinderTest, InterfaceSetMtu) {
2760 const int testMtu = 1200;
2761
2762 // Add test physical network
2763 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2764 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2765
2766 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2767 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2768 expectInterfaceMtu(sTun.name(), testMtu);
2769
2770 // Remove test physical network
2771 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2772}
Luke Huang19b49c52018-10-22 12:12:05 +09002773
2774namespace {
2775
2776constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2777constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002778constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002779constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2780
Luke Huangae038f82018-11-05 11:17:31 +09002781int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002782 return listIptablesRuleByTable(binary, table, chainName).size();
2783}
2784
2785bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2786 const std::vector<std::string>& targetVec) {
2787 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2788 if (targetVec.size() != rules.size() - 2) {
2789 return false;
2790 }
2791
2792 /*
Luke Huangae038f82018-11-05 11:17:31 +09002793 * Check that the rules match. Note that this function matches substrings, not entire rules,
2794 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002795 * Skip first two lines since rules start from third line.
2796 * Chain chainName (x references)
2797 * pkts bytes target prot opt in out source destination
2798 * ...
2799 */
2800 int rIndex = 2;
2801 for (const auto& target : targetVec) {
2802 if (rules[rIndex].find(target) == std::string::npos) {
2803 return false;
2804 }
2805 rIndex++;
2806 }
2807 return true;
2808}
2809
2810void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2811 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2812 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2813 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002814 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002815 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2816 "DROP"};
2817
2818 // V4
2819 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2820 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002821 EXPECT_TRUE(
2822 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002823 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2824
Luke Huangae038f82018-11-05 11:17:31 +09002825 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002826 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2827
2828 // V6
2829 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002830 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2831 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002832
2833 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2834 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2835 extIf));
2836 }
2837}
2838
2839void expectNatDisable() {
2840 // It is the default DROP rule with tethering disable.
2841 // Chain tetherctrl_FORWARD (1 references)
2842 // pkts bytes target prot opt in out source destination
2843 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2844 std::vector<std::string> forwardV4Match = {"DROP"};
2845 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2846
2847 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002848 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2849 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002850
Luke Huangae038f82018-11-05 11:17:31 +09002851 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2852 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002853
2854 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2855}
2856
2857} // namespace
2858
2859TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002860 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2861 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2862 expectNatEnable(sTun.name(), sTun2.name());
2863
2864 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2865 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2866 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002867}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002868
2869namespace {
2870
2871using TripleInt = std::array<int, 3>;
2872
2873TripleInt readProcFileToTripleInt(const std::string& path) {
2874 std::string valueString;
2875 int min, def, max;
2876 EXPECT_TRUE(ReadFileToString(path, &valueString));
2877 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2878 return {min, def, max};
2879}
2880
2881void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2882 std::string testRmemValues =
2883 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2884 std::string testWmemValues =
2885 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2886 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2887
2888 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2889 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2890
2891 for (int i = 0; i < 3; i++) {
2892 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2893 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2894 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2895 }
2896}
2897
2898} // namespace
2899
2900TEST_F(BinderTest, TcpBufferSet) {
2901 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2902 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2903 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2904 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2905
2906 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2907 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2908}
Luke Huang528af602018-08-29 19:06:05 +08002909
Chenbo Feng48eaed32018-12-26 17:40:21 -08002910namespace {
2911
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002912void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Maciej Żenczykowskif879a7f2020-01-20 03:18:06 -08002913 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(UID_PERMISSION_MAP_PATH);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002914 for (int32_t uid : uids) {
Steven Morelanda3074542020-01-13 14:13:44 -08002915 android::base::Result<uint8_t> permission = uidPermissionMap.readValue(uid);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002916 if (exist) {
Bernie Innocentidfd5a432020-02-12 09:21:56 +09002917 ASSERT_RESULT_OK(permission);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002918 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002919 } else {
Bernie Innocentidfd5a432020-02-12 09:21:56 +09002920 ASSERT_FALSE(permission.ok());
Steven Morelanda3074542020-01-13 14:13:44 -08002921 EXPECT_EQ(ENOENT, permission.error().code());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002922 }
2923 }
2924}
2925
2926} // namespace
2927
2928TEST_F(BinderTest, TestInternetPermission) {
2929 SKIP_IF_BPF_NOT_SUPPORTED;
2930
2931 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2932
2933 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002934 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002935 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002936 checkUidsInPermissionMap(appUids, true);
2937 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2938 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002939}
2940
Luke Huang528af602018-08-29 19:06:05 +08002941TEST_F(BinderTest, UnsolEvents) {
2942 auto testUnsolService = android::net::TestUnsolService::start();
2943 std::string oldTunName = sTun.name();
2944 std::string newTunName = "unsolTest";
2945 testUnsolService->tarVec.push_back(oldTunName);
2946 testUnsolService->tarVec.push_back(newTunName);
2947 auto& cv = testUnsolService->getCv();
2948 auto& cvMutex = testUnsolService->getCvMutex();
2949 binder::Status status = mNetd->registerUnsolicitedEventListener(
2950 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2951 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2952
2953 // TODO: Add test for below events
2954 // StrictCleartextDetected / InterfaceDnsServersAdded
2955 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2956
2957 {
2958 std::unique_lock lock(cvMutex);
2959
2960 // Re-init test Tun, and we expect that we will get some unsol events.
2961 // Use the test Tun device name to verify if we receive its unsol events.
2962 sTun.destroy();
2963 // Use predefined name
2964 sTun.init(newTunName);
2965
2966 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2967 }
2968
2969 // bit mask 1101101000
2970 // Test only covers below events currently
2971 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2972 InterfaceLinkStatusChanged | RouteChanged;
2973 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08002974
2975 // Re-init sTun to clear predefined name
2976 sTun.destroy();
2977 sTun.init();
2978}
2979
2980TEST_F(BinderTest, NDC) {
2981 struct Command {
2982 const std::string cmdString;
2983 const std::string expectedResult;
2984 };
2985
2986 // clang-format off
2987 // Do not change the commands order
2988 const Command networkCmds[] = {
2989 {StringPrintf("ndc network create %d", TEST_NETID1),
2990 "200 0 success"},
2991 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
2992 "200 0 success"},
2993 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
2994 "200 0 success"},
2995 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
2996 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
2997 {StringPrintf("ndc network destroy %d", TEST_NETID1),
2998 "200 0 success"},
2999 };
3000
3001 const std::vector<Command> ipfwdCmds = {
3002 {"ndc ipfwd enable " + sTun.name(),
3003 "200 0 ipfwd operation succeeded"},
3004 {"ndc ipfwd disable " + sTun.name(),
3005 "200 0 ipfwd operation succeeded"},
3006 {"ndc ipfwd add lo2 lo3",
3007 "400 0 ipfwd operation failed (No such process)"},
3008 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
3009 "200 0 ipfwd operation succeeded"},
3010 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
3011 "200 0 ipfwd operation succeeded"},
3012 };
3013
3014 static const struct {
3015 const char* ipVersion;
3016 const char* testDest;
3017 const char* testNextHop;
3018 const bool expectSuccess;
3019 const std::string expectedResult;
3020 } kTestData[] = {
3021 {IP_RULE_V4, "0.0.0.0/0", "", true,
3022 "200 0 success"},
3023 {IP_RULE_V4, "10.251.0.0/16", "", true,
3024 "200 0 success"},
3025 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
3026 "400 0 addRoute() failed (Invalid argument)",},
3027 {IP_RULE_V6, "::/0", "", true,
3028 "200 0 success"},
3029 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
3030 "200 0 success"},
3031 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
3032 "400 0 addRoute() failed (Invalid argument)"},
3033 };
3034 // clang-format on
3035
3036 for (const auto& cmd : networkCmds) {
3037 const std::vector<std::string> result = runCommand(cmd.cmdString);
3038 SCOPED_TRACE(cmd.cmdString);
3039 EXPECT_EQ(result.size(), 1U);
3040 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3041 }
3042
3043 for (const auto& cmd : ipfwdCmds) {
3044 const std::vector<std::string> result = runCommand(cmd.cmdString);
3045 SCOPED_TRACE(cmd.cmdString);
3046 EXPECT_EQ(result.size(), 1U);
3047 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3048 }
3049
3050 // Add test physical network
3051 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3052 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3053
3054 for (const auto& td : kTestData) {
3055 const std::string routeAddCmd =
3056 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
3057 td.testDest, td.testNextHop);
3058 const std::string routeRemoveCmd =
3059 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
3060 sTun.name().c_str(), td.testDest, td.testNextHop);
3061 std::vector<std::string> result = runCommand(routeAddCmd);
3062 SCOPED_TRACE(routeAddCmd);
3063 EXPECT_EQ(result.size(), 1U);
3064 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3065 if (td.expectSuccess) {
3066 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3067 sTun.name().c_str());
3068 result = runCommand(routeRemoveCmd);
3069 EXPECT_EQ(result.size(), 1U);
3070 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3071 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3072 sTun.name().c_str());
3073 }
3074 }
3075 // Remove test physical network
3076 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09003077}
Luke Huang0e5e69d2019-03-06 15:42:38 +08003078
Luke Huang2ff8b342019-04-30 15:33:33 +08003079TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08003080 sp<IBinder> binder;
3081 binder::Status status = mNetd->getOemNetd(&binder);
3082 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3083 sp<com::android::internal::net::IOemNetd> oemNetd;
3084 if (binder != nullptr) {
3085 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3086 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003087 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003088
3089 TimedOperation t("OemNetd isAlive RPC");
3090 bool isAlive = false;
3091 oemNetd->isAlive(&isAlive);
3092 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003093
3094 class TestOemUnsolListener
3095 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3096 public:
3097 android::binder::Status onRegistered() override {
3098 std::lock_guard lock(mCvMutex);
3099 mCv.notify_one();
3100 return android::binder::Status::ok();
3101 }
3102 std::condition_variable& getCv() { return mCv; }
3103 std::mutex& getCvMutex() { return mCvMutex; }
3104
3105 private:
3106 std::mutex mCvMutex;
3107 std::condition_variable mCv;
3108 };
3109
3110 // Start the Binder thread pool.
3111 android::ProcessState::self()->startThreadPool();
3112
3113 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3114
3115 auto& cv = testListener->getCv();
3116 auto& cvMutex = testListener->getCvMutex();
3117
3118 {
3119 std::unique_lock lock(cvMutex);
3120
3121 status = oemNetd->registerOemUnsolicitedEventListener(
3122 ::android::interface_cast<
3123 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3124 testListener));
3125 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3126
3127 // Wait for receiving expected events.
3128 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3129 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003130}
Luke Huangd2861982019-05-17 19:47:28 +08003131
3132void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3133 int fallthroughNetId) {
3134 // Re-init sTun* to ensure route rule exists.
3135 sTun.destroy();
3136 sTun.init();
3137 sTun2.destroy();
3138 sTun2.init();
3139
3140 // Create physical network with fallthroughNetId but not set it as default network
3141 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3142 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3143
3144 // Create VPN with vpnNetId
3145 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3146
3147 // Add uid to VPN
3148 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3149 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3150
3151 // Add default route to fallthroughNetwork
3152 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3153 // Add limited route
3154 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3155}
3156
3157namespace {
3158
3159class ScopedUidChange {
3160 public:
3161 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3162 mStoredUid = getuid();
3163 if (mInputUid == mStoredUid) return;
3164 EXPECT_TRUE(seteuid(uid) == 0);
3165 }
3166 ~ScopedUidChange() {
3167 if (mInputUid == mStoredUid) return;
3168 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3169 }
3170
3171 private:
3172 uid_t mInputUid;
3173 uid_t mStoredUid;
3174};
3175
3176constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3177
3178void clearQueue(int tunFd) {
3179 char buf[4096];
3180 int ret;
3181 do {
3182 ret = read(tunFd, buf, sizeof(buf));
3183 } while (ret > 0);
3184}
3185
3186void checkDataReceived(int udpSocket, int tunFd) {
3187 char buf[4096] = {};
3188 // Clear tunFd's queue before write something because there might be some
3189 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3190 clearQueue(tunFd);
3191 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3192 // TODO: extract header and verify data
3193 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3194}
3195
3196bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3197 ScopedUidChange scopedUidChange(uid);
Bernie Innocentid26a04a2019-10-30 17:15:15 +09003198 unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Luke Huangd2861982019-05-17 19:47:28 +08003199 if (testSocket < 0) return false;
3200
Nick Desaulniers6b357502019-10-11 09:26:44 -07003201 const sockaddr_in6 dst6 = {
3202 .sin6_family = AF_INET6,
3203 .sin6_port = 42,
3204 .sin6_addr = dstAddr,
3205 };
Luke Huangd2861982019-05-17 19:47:28 +08003206 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3207 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3208 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3209 if (res == -1) return false;
3210
3211 char addr[INET6_ADDRSTRLEN];
3212 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3213 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3214 checkDataReceived(testSocket, tunFd);
3215 return true;
3216}
3217
3218void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3219 std::string vpnFallthroughRule =
3220 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3221 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3222 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3223 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3224 }
3225}
3226
3227void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3228 const TunInterface& fallthroughNetwork,
3229 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3230 int fallthroughNetId = TEST_NETID1) {
3231 // Set default network to NETID_UNSET
3232 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3233
3234 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3235 in6_addr insideVpnAddr = {
3236 {// 2001:db8:cafe::1
3237 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3238 // outsideVpnAddr will hit the route in the fallthrough network route table
3239 // because we added default route in createVpnNetworkWithUid
3240 in6_addr outsideVpnAddr = {
3241 {// 2607:f0d0:1002::4
3242 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3243
3244 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3245 int vpnFd = vpnNetwork.getFdForTesting();
3246 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3247 // default network.
3248 Fwmark fwmark;
3249 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3250 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3251
3252 // Set default network
3253 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3254
3255 // Connections go on the default network because UID 0 is not subject to the VPN.
3256 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3257 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3258 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3259 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3260
3261 // Check if fallthrough rule exists
3262 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3263
3264 // Expect fallthrough to default network
3265 // The fwmark differs depending on whether the VPN is bypassable or not.
3266 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3267 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3268
3269 // Expect connect success, packet will be sent to vpnFd.
3270 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3271 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3272
3273 // Explicitly select vpn network
3274 setNetworkForProcess(vpnNetId);
3275
3276 // Expect fallthrough to default network
3277 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3278 // Expect the mark contains all the bit because we've selected network.
3279 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3280
3281 // Expect connect success, packet will be sent to vpnFd.
3282 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3283 // Expect the mark contains all the bit because we've selected network.
3284 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3285
3286 // Explicitly select fallthrough network
3287 setNetworkForProcess(fallthroughNetId);
3288
3289 // The mark is set to fallthrough network because we've selected it.
3290 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3291 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3292
3293 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3294 if (bypassable) {
3295 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3296 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3297 } else {
3298 // If not, no permission to bypass vpn.
3299 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3300 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3301 }
3302}
3303
3304} // namespace
3305
3306TEST_F(BinderTest, SecureVPNFallthrough) {
3307 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3308 // Get current default network NetId
3309 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3310 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3311}
3312
3313TEST_F(BinderTest, BypassableVPNFallthrough) {
3314 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3315 // Get current default network NetId
3316 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3317 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
Bernie Innocenti80ffd0f2019-06-05 15:27:46 +09003318}
Chiachang Wang00fc62f2019-12-04 20:38:26 +08003319
3320namespace {
3321
3322int32_t createIpv6SocketAndCheckMark(int type, const in6_addr& dstAddr) {
3323 const sockaddr_in6 dst6 = {
3324 .sin6_family = AF_INET6,
3325 .sin6_port = 1234,
3326 .sin6_addr = dstAddr,
3327 };
3328 // create non-blocking socket.
3329 int sockFd = socket(AF_INET6, type | SOCK_NONBLOCK, 0);
3330 EXPECT_NE(-1, sockFd);
3331 EXPECT_EQ((type == SOCK_STREAM) ? -1 : 0, connect(sockFd, (sockaddr*)&dst6, sizeof(dst6)));
3332
3333 // Get socket fwmark.
3334 Fwmark fwmark;
3335 socklen_t fwmarkLen = sizeof(fwmark.intValue);
3336 EXPECT_EQ(0, getsockopt(sockFd, SOL_SOCKET, SO_MARK, &fwmark.intValue, &fwmarkLen));
3337 EXPECT_EQ(0, close(sockFd));
3338 return fwmark.intValue;
3339}
3340
3341} // namespace
3342
3343TEST_F(BinderTest, GetFwmarkForNetwork) {
3344 in6_addr v6Addr = {
3345 {// 2001:db8:cafe::8888
3346 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0x88}}};
3347 // Add test physical network 1 and set as default network.
3348 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3349 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3350 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "2001:db8::/32", "").isOk());
3351 EXPECT_TRUE(mNetd->networkSetDefault(TEST_NETID1).isOk());
3352 // Add test physical network 2
3353 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
3354 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
3355
3356 // Get fwmark for network 1.
3357 MarkMaskParcel maskMarkNet1;
3358 ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID1, &maskMarkNet1).isOk());
3359
3360 uint32_t fwmarkTcp = createIpv6SocketAndCheckMark(SOCK_STREAM, v6Addr);
3361 uint32_t fwmarkUdp = createIpv6SocketAndCheckMark(SOCK_DGRAM, v6Addr);
3362 EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkTcp & maskMarkNet1.mask));
3363 EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkUdp & maskMarkNet1.mask));
3364
3365 // Get fwmark for network 2.
3366 MarkMaskParcel maskMarkNet2;
3367 ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID2, &maskMarkNet2).isOk());
3368 EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkTcp & maskMarkNet2.mask));
3369 EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkUdp & maskMarkNet2.mask));
3370
3371 // Remove test physical network.
3372 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
3373 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
3374}
Hungming Chen92571042020-02-20 17:01:31 +08003375
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003376namespace {
3377
3378TetherOffloadRuleParcel makeTetherOffloadRule(int inputInterfaceIndex, int outputInterfaceIndex,
3379 const std::vector<uint8_t>& destination,
3380 int prefixLength,
3381 const std::vector<uint8_t>& srcL2Address,
3382 const std::vector<uint8_t>& dstL2Address) {
3383 android::net::TetherOffloadRuleParcel parcel;
3384 parcel.inputInterfaceIndex = inputInterfaceIndex;
3385 parcel.outputInterfaceIndex = outputInterfaceIndex;
3386 parcel.destination = destination;
3387 parcel.prefixLength = prefixLength;
3388 parcel.srcL2Address = srcL2Address;
3389 parcel.dstL2Address = dstL2Address;
3390 return parcel;
3391}
3392
3393} // namespace
3394
3395TEST_F(BinderTest, TetherOffloadRule) {
Hungming Chen92571042020-02-20 17:01:31 +08003396 SKIP_IF_BPF_NOT_SUPPORTED;
3397
3398 // TODO: Perhaps verify invalid interface index once the netd handle the error in methods.
3399 constexpr uint32_t kIfaceInt = 101;
3400 constexpr uint32_t kIfaceExt = 102;
3401 constexpr uint32_t kIfaceNonExistent = 103;
3402
3403 const std::vector<uint8_t> kAddr6 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0x00, 0x00,
3404 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88};
3405 const std::vector<uint8_t> kSrcMac = {0x00, 0x00, 0x00, 0x00, 0x00, 0x0a};
3406 const std::vector<uint8_t> kDstMac = {0x00, 0x00, 0x00, 0x00, 0x00, 0x0b};
3407
3408 const std::vector<uint8_t> kInvalidAddr4 = {0xac, 0x0a, 0x0d, 0xb8}; // should be IPv6 address
3409 const std::vector<uint8_t> kInvalidMac = {0xde, 0xad, 0xbe, 0xef}; // should be 6-byte length
3410
3411 // Invalid IP address, add rule
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003412 TetherOffloadRuleParcel rule = makeTetherOffloadRule(
3413 kIfaceExt, kIfaceInt, kInvalidAddr4 /*bad*/, 128, kSrcMac, kDstMac);
3414 auto status = mNetd->tetherOffloadRuleAdd(rule);
Hungming Chen92571042020-02-20 17:01:31 +08003415 EXPECT_FALSE(status.isOk());
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003416 EXPECT_EQ(EAFNOSUPPORT, status.serviceSpecificErrorCode());
Hungming Chen92571042020-02-20 17:01:31 +08003417
3418 // Invalid source L2 address, add rule
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003419 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kInvalidMac /*bad*/, kDstMac);
3420 status = mNetd->tetherOffloadRuleAdd(rule);
Hungming Chen92571042020-02-20 17:01:31 +08003421 EXPECT_FALSE(status.isOk());
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003422 EXPECT_EQ(ENXIO, status.serviceSpecificErrorCode());
Hungming Chen92571042020-02-20 17:01:31 +08003423
3424 // Invalid destination L2 address, add rule
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003425 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kSrcMac, kInvalidMac /*bad*/);
3426 status = mNetd->tetherOffloadRuleAdd(rule);
Hungming Chen92571042020-02-20 17:01:31 +08003427 EXPECT_FALSE(status.isOk());
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003428 EXPECT_EQ(ENXIO, status.serviceSpecificErrorCode());
Hungming Chen92571042020-02-20 17:01:31 +08003429
3430 // Invalid IP address, remove rule
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003431 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kInvalidAddr4 /*bad*/, 128, kSrcMac,
3432 kDstMac);
3433 status = mNetd->tetherOffloadRuleRemove(rule);
3434 EXPECT_FALSE(status.isOk());
3435 EXPECT_EQ(EAFNOSUPPORT, status.serviceSpecificErrorCode());
3436
3437 // Invalid prefix length
3438 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 64 /*bad*/, kSrcMac, kDstMac);
3439 status = mNetd->tetherOffloadRuleAdd(rule);
3440 EXPECT_FALSE(status.isOk());
3441 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
3442 status = mNetd->tetherOffloadRuleRemove(rule);
Hungming Chen92571042020-02-20 17:01:31 +08003443 EXPECT_FALSE(status.isOk());
3444 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
3445
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003446 // Invalid interface index
3447 rule = makeTetherOffloadRule(kIfaceExt, 0, kAddr6, 128, kSrcMac, kDstMac);
3448 status = mNetd->tetherOffloadRuleAdd(rule);
3449 EXPECT_FALSE(status.isOk());
3450 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
3451 rule = makeTetherOffloadRule(0, kIfaceInt, kAddr6, 64, kSrcMac, kDstMac);
3452 status = mNetd->tetherOffloadRuleRemove(rule);
3453 EXPECT_FALSE(status.isOk());
3454 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
3455
Hungming Chen92571042020-02-20 17:01:31 +08003456 // Remove non existent rule. Expect that silently return success if the rule did not exist.
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003457 rule = makeTetherOffloadRule(kIfaceNonExistent, kIfaceInt, kAddr6, 128, kSrcMac, kDstMac);
3458 EXPECT_TRUE(mNetd->tetherOffloadRuleRemove(rule).isOk());
Hungming Chen92571042020-02-20 17:01:31 +08003459
3460 // Add and remove rule normally.
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003461 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kSrcMac, kDstMac);
3462 EXPECT_TRUE(mNetd->tetherOffloadRuleAdd(rule).isOk());
3463 EXPECT_TRUE(mNetd->tetherOffloadRuleRemove(rule).isOk());
Hungming Chen92571042020-02-20 17:01:31 +08003464}