blob: f844544aadebc4f6782ef040fb0c2504c4e964d2 [file] [log] [blame]
Pierre Imai1cfa5432016-02-24 18:00:03 +09001/*
2 * Copyright (C) 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
Bernie Innocenti196f1b82019-05-20 16:34:16 +090017#include <cinttypes>
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090018#include <regex>
19#include <set>
20#include <string>
21
Lorenzo Colitti05306fb2017-02-09 04:56:00 +090022#include <android-base/stringprintf.h>
Mike Yue7e332f2019-03-13 17:15:48 +080023#include <android-base/strings.h>
24#include <netdutils/Stopwatch.h>
Lorenzo Colitti05306fb2017-02-09 04:56:00 +090025
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090026#define LOG_TAG "Netd"
Logan Chien3f461482018-04-23 14:31:32 +080027#include <log/log.h>
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090028
Pierre Imai1cfa5432016-02-24 18:00:03 +090029#include "Controllers.h"
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090030#include "IdletimerController.h"
31#include "NetworkController.h"
32#include "RouteController.h"
Nathan Harold21299f72018-03-16 20:13:03 -070033#include "XfrmController.h"
Mike Yue7e332f2019-03-13 17:15:48 +080034#include "oem_iptables_hook.h"
Pierre Imai1cfa5432016-02-24 18:00:03 +090035
36namespace android {
37namespace net {
38
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090039using android::base::StringAppendF;
Mike Yue7e332f2019-03-13 17:15:48 +080040using android::base::StringPrintf;
41using android::netdutils::Stopwatch;
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090042
Lorenzo Colitti341d3a02017-08-08 17:31:35 +090043auto Controllers::execIptablesRestore = ::execIptablesRestore;
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090044auto Controllers::execIptablesRestoreWithOutput = ::execIptablesRestoreWithOutput;
Lorenzo Colitti341d3a02017-08-08 17:31:35 +090045
Erik Klineb31fd692018-06-06 20:50:11 +090046netdutils::Log gLog("netd");
Luke Huang528af602018-08-29 19:06:05 +080047netdutils::Log gUnsolicitedLog("netdUnsolicited");
Erik Klineb31fd692018-06-06 20:50:11 +090048
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090049namespace {
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090050
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090051/**
52 * List of module chains to be created, along with explicit ordering. ORDERING
53 * IS CRITICAL, AND SHOULD BE TRIPLE-CHECKED WITH EACH CHANGE.
54 */
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090055static const std::vector<const char*> FILTER_INPUT = {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090056 // Bandwidth should always be early in input chain, to make sure we
57 // correctly count incoming traffic against data plan.
58 BandwidthController::LOCAL_INPUT,
59 FirewallController::LOCAL_INPUT,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090060};
61
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090062static const std::vector<const char*> FILTER_FORWARD = {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090063 OEM_IPTABLES_FILTER_FORWARD,
64 FirewallController::LOCAL_FORWARD,
65 BandwidthController::LOCAL_FORWARD,
Lorenzo Colittia93126d2017-08-24 13:28:19 +090066 TetherController::LOCAL_FORWARD,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090067};
68
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090069static const std::vector<const char*> FILTER_OUTPUT = {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090070 OEM_IPTABLES_FILTER_OUTPUT,
71 FirewallController::LOCAL_OUTPUT,
72 StrictController::LOCAL_OUTPUT,
73 BandwidthController::LOCAL_OUTPUT,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090074};
75
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090076static const std::vector<const char*> RAW_PREROUTING = {
Lorenzo Colitti91fd5802019-06-28 19:22:01 +090077 ClatdController::LOCAL_RAW_PREROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090078 BandwidthController::LOCAL_RAW_PREROUTING,
79 IdletimerController::LOCAL_RAW_PREROUTING,
Lorenzo Colittia93126d2017-08-24 13:28:19 +090080 TetherController::LOCAL_RAW_PREROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090081};
82
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090083static const std::vector<const char*> MANGLE_POSTROUTING = {
Lorenzo Colitti05306fb2017-02-09 04:56:00 +090084 OEM_IPTABLES_MANGLE_POSTROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090085 BandwidthController::LOCAL_MANGLE_POSTROUTING,
86 IdletimerController::LOCAL_MANGLE_POSTROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090087};
88
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090089static const std::vector<const char*> MANGLE_INPUT = {
Joel Scherpelz08b84cd2017-05-22 13:11:54 +090090 WakeupController::LOCAL_MANGLE_INPUT,
Lorenzo Colittid78843e2017-03-27 05:52:31 +090091 RouteController::LOCAL_MANGLE_INPUT,
Lorenzo Colittid78843e2017-03-27 05:52:31 +090092};
93
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090094static const std::vector<const char*> MANGLE_FORWARD = {
Lorenzo Colittia93126d2017-08-24 13:28:19 +090095 TetherController::LOCAL_MANGLE_FORWARD,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090096};
97
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090098static const std::vector<const char*> NAT_PREROUTING = {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090099 OEM_IPTABLES_NAT_PREROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900100};
101
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900102static const std::vector<const char*> NAT_POSTROUTING = {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900103 TetherController::LOCAL_NAT_POSTROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900104};
105
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900106// Commands to create child chains and to match created chains in iptables -S output. Keep in sync.
107static const char* CHILD_CHAIN_TEMPLATE = "-A %s -j %s\n";
108static const std::regex CHILD_CHAIN_REGEX("^-A ([^ ]+) -j ([^ ]+)$",
109 std::regex_constants::extended);
110
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900111} // namespace
112
113/* static */
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900114std::set<std::string> Controllers::findExistingChildChains(const IptablesTarget target,
115 const char* table,
116 const char* parentChain) {
117 if (target == V4V6) {
118 ALOGE("findExistingChildChains only supports one protocol at a time");
119 abort();
120 }
121
122 std::set<std::string> existing;
123
124 // List the current contents of parentChain.
125 //
126 // TODO: there is no guarantee that nothing else modifies the chain in the few milliseconds
127 // between when we list the existing rules and when we delete them. However:
128 // - Since this code is only run on startup, nothing else in netd will be running.
129 // - While vendor code is known to add its own rules to chains created by netd, it should never
130 // be modifying the rules in childChains or the rules that hook said chains into their parent
131 // chains.
132 std::string command = StringPrintf("*%s\n-S %s\nCOMMIT\n", table, parentChain);
133 std::string output;
134 if (Controllers::execIptablesRestoreWithOutput(target, command, &output) == -1) {
135 ALOGE("Error listing chain %s in table %s\n", parentChain, table);
136 return existing;
137 }
138
139 // The only rules added by createChildChains are of the simple form "-A <parent> -j <child>".
140 // Find those rules and add each one's child chain to existing.
141 std::smatch matches;
142 std::stringstream stream(output);
143 std::string rule;
144 while (std::getline(stream, rule, '\n')) {
145 if (std::regex_search(rule, matches, CHILD_CHAIN_REGEX) && matches[1] == parentChain) {
146 existing.insert(matches[2]);
147 }
148 }
149
150 return existing;
151}
152
153/* static */
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900154void Controllers::createChildChains(IptablesTarget target, const char* table,
155 const char* parentChain,
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900156 const std::vector<const char*>& childChains,
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900157 bool exclusive) {
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900158 std::string command = StringPrintf("*%s\n", table);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900159
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900160 // We cannot just clear all the chains we create because vendor code modifies filter OUTPUT and
161 // mangle POSTROUTING directly. So:
162 //
163 // - If we're the exclusive owner of this chain, simply clear it entirely.
164 // - If not, then list the chain's current contents to ensure that if we restart after a crash,
165 // we leave the existing rules alone in the positions they currently occupy. This is faster
166 // than blindly deleting our rules and recreating them, because deleting a rule that doesn't
167 // exists causes iptables-restore to quit, which takes ~30ms per delete. It's also more
168 // correct, because if we delete rules and re-add them, they'll be in the wrong position with
169 // regards to the vendor rules.
170 //
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900171 // TODO: Make all chains exclusive once vendor code uses the oem_* rules.
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900172 std::set<std::string> existingChildChains;
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900173 if (exclusive) {
174 // Just running ":chain -" flushes user-defined chains, but not built-in chains like INPUT.
175 // Since at this point we don't know if parentChain is a built-in chain, do both.
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900176 StringAppendF(&command, ":%s -\n", parentChain);
177 StringAppendF(&command, "-F %s\n", parentChain);
178 } else {
179 existingChildChains = findExistingChildChains(target, table, parentChain);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900180 }
181
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900182 for (const auto& childChain : childChains) {
183 // Always clear the child chain.
184 StringAppendF(&command, ":%s -\n", childChain);
185 // But only add it to the parent chain if it's not already there.
186 if (existingChildChains.find(childChain) == existingChildChains.end()) {
187 StringAppendF(&command, CHILD_CHAIN_TEMPLATE, parentChain, childChain);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900188 }
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900189 }
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900190 command += "COMMIT\n";
Lorenzo Colitti05306fb2017-02-09 04:56:00 +0900191 execIptablesRestore(target, command);
192}
193
Joel Scherpelz08b84cd2017-05-22 13:11:54 +0900194Controllers::Controllers()
Luke Huangf29fe682019-03-26 15:15:44 +0800195 : clatdCtrl(&netCtrl),
Joel Scherpelz08b84cd2017-05-22 13:11:54 +0900196 wakeupCtrl(
Erik Klineb31fd692018-06-06 20:50:11 +0900197 [this](const WakeupController::ReportArgs& args) {
198 const auto listener = eventReporter.getNetdEventListener();
199 if (listener == nullptr) {
200 gLog.error("getNetdEventListener() returned nullptr. dropping wakeup event");
201 return;
202 }
203 String16 prefix = String16(args.prefix.c_str());
204 String16 srcIp = String16(args.srcIp.c_str());
205 String16 dstIp = String16(args.dstIp.c_str());
206 listener->onWakeupEvent(prefix, args.uid, args.ethertype, args.ipNextHeader,
207 args.dstHw, srcIp, dstIp, args.srcPort, args.dstPort,
208 args.timestampNs);
209 },
210 &iptablesRestoreCtrl) {
Erik Kline2c5aaa12016-06-08 13:24:45 +0900211 InterfaceController::initializeAll();
212}
Pierre Imai1cfa5432016-02-24 18:00:03 +0900213
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900214void Controllers::initChildChains() {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900215 /*
216 * This is the only time we touch top-level chains in iptables; controllers
217 * should only mutate rules inside of their children chains, as created by
218 * the constants above.
219 *
220 * Modules should never ACCEPT packets (except in well-justified cases);
221 * they should instead defer to any remaining modules using RETURN, or
222 * otherwise DROP/REJECT.
223 */
224
Lorenzo Colitti05306fb2017-02-09 04:56:00 +0900225 // Create chains for child modules.
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900226 createChildChains(V4V6, "filter", "INPUT", FILTER_INPUT, true);
227 createChildChains(V4V6, "filter", "FORWARD", FILTER_FORWARD, true);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900228 createChildChains(V4V6, "raw", "PREROUTING", RAW_PREROUTING, true);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900229 createChildChains(V4V6, "mangle", "FORWARD", MANGLE_FORWARD, true);
Lorenzo Colittid78843e2017-03-27 05:52:31 +0900230 createChildChains(V4V6, "mangle", "INPUT", MANGLE_INPUT, true);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900231 createChildChains(V4, "nat", "PREROUTING", NAT_PREROUTING, true);
232 createChildChains(V4, "nat", "POSTROUTING", NAT_POSTROUTING, true);
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900233
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900234 createChildChains(V4, "filter", "OUTPUT", FILTER_OUTPUT, false);
235 createChildChains(V6, "filter", "OUTPUT", FILTER_OUTPUT, false);
236 createChildChains(V4, "mangle", "POSTROUTING", MANGLE_POSTROUTING, false);
237 createChildChains(V6, "mangle", "POSTROUTING", MANGLE_POSTROUTING, false);
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900238}
239
240void Controllers::initIptablesRules() {
241 Stopwatch s;
242 initChildChains();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900243 gLog.info("Creating child chains: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900244
245 // Let each module setup their child chains
246 setupOemIptablesHook();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900247 gLog.info("Setting up OEM hooks: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900248
249 /* When enabled, DROPs all packets except those matching rules. */
250 firewallCtrl.setupIptablesHooks();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900251 gLog.info("Setting up FirewallController hooks: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900252
253 /* Does DROPs in FORWARD by default */
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900254 tetherCtrl.setupIptablesHooks();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900255 gLog.info("Setting up TetherController hooks: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +0900256
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900257 /*
258 * Does REJECT in INPUT, OUTPUT. Does counting also.
259 * No DROP/REJECT allowed later in netfilter-flow hook order.
260 */
261 bandwidthCtrl.setupIptablesHooks();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900262 gLog.info("Setting up BandwidthController hooks: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +0900263
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900264 /*
265 * Counts in nat: PREROUTING, POSTROUTING.
266 * No DROP/REJECT allowed later in netfilter-flow hook order.
267 */
268 idletimerCtrl.setupIptablesHooks();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900269 gLog.info("Setting up IdletimerController hooks: %" PRId64 "us", s.getTimeAndResetUs());
Luke Huanga67dd562018-07-17 19:58:25 +0800270
271 /*
272 * Add rules for detecting IPv6/IPv4 TCP/UDP connections with TLS/DTLS header
273 */
274 strictCtrl.setupIptablesHooks();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900275 gLog.info("Setting up StrictController hooks: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900276}
277
278void Controllers::init() {
279 initIptablesRules();
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +0900280 Stopwatch s;
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700281
Maciej Żenczykowski56280272019-03-30 03:32:51 -0700282 clatdCtrl.init();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900283 gLog.info("Initializing ClatdController: %" PRId64 "us", s.getTimeAndResetUs());
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700284
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800285 netdutils::Status tcStatus = trafficCtrl.start();
286 if (!isOk(tcStatus)) {
Erik Klineb31fd692018-06-06 20:50:11 +0900287 gLog.error("Failed to start trafficcontroller: (%s)", toString(tcStatus).c_str());
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800288 }
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900289 gLog.info("Initializing traffic control: %" PRId64 "us", s.getTimeAndResetUs());
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800290
Chenbo Feng47dd0732018-12-11 12:23:24 -0800291 bandwidthCtrl.setBpfEnabled(trafficCtrl.getBpfLevel() != android::bpf::BpfLevel::NONE);
Luke Huangf44a3c12018-09-07 12:10:12 +0800292 bandwidthCtrl.enableBandwidthControl();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900293 gLog.info("Enabling bandwidth control: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900294
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800295 if (int ret = RouteController::Init(NetworkController::LOCAL_NET_ID)) {
Erik Klineb31fd692018-06-06 20:50:11 +0900296 gLog.error("Failed to initialize RouteController (%s)", strerror(-ret));
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900297 }
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900298 gLog.info("Initializing RouteController: %" PRId64 "us", s.getTimeAndResetUs());
Nathan Harold21299f72018-03-16 20:13:03 -0700299
300 netdutils::Status xStatus = XfrmController::Init();
301 if (!isOk(xStatus)) {
Erik Klineb31fd692018-06-06 20:50:11 +0900302 gLog.error("Failed to initialize XfrmController (%s)", netdutils::toString(xStatus).c_str());
Nathan Harold21299f72018-03-16 20:13:03 -0700303 };
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900304 gLog.info("Initializing XfrmController: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900305}
306
Pierre Imai1cfa5432016-02-24 18:00:03 +0900307Controllers* gCtls = nullptr;
308
309} // namespace net
310} // namespace android