1 /*
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
17 #include <cinttypes>
18 #include <regex>
19 #include <set>
20 #include <string>
21
22 #include <android-base/stringprintf.h>
23 #include <android-base/strings.h>
24 #include <netdutils/Stopwatch.h>
25
26 #define LOG_TAG "Netd"
27 #include <log/log.h>
28
29 #include "Controllers.h"
30 #include "IdletimerController.h"
31 #include "NetworkController.h"
32 #include "RouteController.h"
33 #include "XfrmController.h"
34 #include "oem_iptables_hook.h"
35
36 namespace android {
37 namespace net {
38
39 using android::base::StringAppendF;
40 using android::base::StringPrintf;
41 using android::netdutils::Stopwatch;
42
43 auto Controllers::execIptablesRestore = ::execIptablesRestore;
44 auto Controllers::execIptablesRestoreWithOutput = ::execIptablesRestoreWithOutput;
45
46 netdutils::Log gLog("netd");
47 netdutils::Log gUnsolicitedLog("netdUnsolicited");
48
49 namespace {
50
51 /**
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 */
55 static const std::vector<const char*> FILTER_INPUT = {
56 // 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,
60 };
61
62 static const std::vector<const char*> FILTER_FORWARD = {
63 OEM_IPTABLES_FILTER_FORWARD,
64 FirewallController::LOCAL_FORWARD,
65 BandwidthController::LOCAL_FORWARD,
66 TetherController::LOCAL_FORWARD,
67 };
68
69 static const std::vector<const char*> FILTER_OUTPUT = {
70 OEM_IPTABLES_FILTER_OUTPUT,
71 FirewallController::LOCAL_OUTPUT,
72 StrictController::LOCAL_OUTPUT,
73 BandwidthController::LOCAL_OUTPUT,
74 };
75
76 static const std::vector<const char*> RAW_PREROUTING = {
77 ClatdController::LOCAL_RAW_PREROUTING,
78 BandwidthController::LOCAL_RAW_PREROUTING,
79 IdletimerController::LOCAL_RAW_PREROUTING,
80 TetherController::LOCAL_RAW_PREROUTING,
81 };
82
83 static const std::vector<const char*> MANGLE_POSTROUTING = {
84 OEM_IPTABLES_MANGLE_POSTROUTING,
85 BandwidthController::LOCAL_MANGLE_POSTROUTING,
86 IdletimerController::LOCAL_MANGLE_POSTROUTING,
87 };
88
89 static const std::vector<const char*> MANGLE_INPUT = {
90 WakeupController::LOCAL_MANGLE_INPUT,
91 RouteController::LOCAL_MANGLE_INPUT,
92 };
93
94 static const std::vector<const char*> MANGLE_FORWARD = {
95 TetherController::LOCAL_MANGLE_FORWARD,
96 };
97
98 static const std::vector<const char*> NAT_PREROUTING = {
99 OEM_IPTABLES_NAT_PREROUTING,
100 };
101
102 static const std::vector<const char*> NAT_POSTROUTING = {
103 TetherController::LOCAL_NAT_POSTROUTING,
104 };
105
106 // Commands to create child chains and to match created chains in iptables -S output. Keep in sync.
107 static const char* CHILD_CHAIN_TEMPLATE = "-A %s -j %s\n";
108 static const std::regex CHILD_CHAIN_REGEX("^-A ([^ ]+) -j ([^ ]+)$",
109 std::regex_constants::extended);
110
111 } // namespace
112
113 /* static */
findExistingChildChains(const IptablesTarget target,const char * table,const char * parentChain)114 std::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 */
createChildChains(IptablesTarget target,const char * table,const char * parentChain,const std::vector<const char * > & childChains,bool exclusive)154 void Controllers::createChildChains(IptablesTarget target, const char* table,
155 const char* parentChain,
156 const std::vector<const char*>& childChains,
157 bool exclusive) {
158 std::string command = StringPrintf("*%s\n", table);
159
160 // 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 //
171 // TODO: Make all chains exclusive once vendor code uses the oem_* rules.
172 std::set<std::string> existingChildChains;
173 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.
176 StringAppendF(&command, ":%s -\n", parentChain);
177 StringAppendF(&command, "-F %s\n", parentChain);
178 } else {
179 existingChildChains = findExistingChildChains(target, table, parentChain);
180 }
181
182 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);
188 }
189 }
190 command += "COMMIT\n";
191 execIptablesRestore(target, command);
192 }
193
Controllers()194 Controllers::Controllers()
195 : clatdCtrl(&netCtrl),
196 wakeupCtrl(
197 [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) {
211 InterfaceController::initializeAll();
212 }
213
initChildChains()214 void Controllers::initChildChains() {
215 /*
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
225 // Create chains for child modules.
226 createChildChains(V4V6, "filter", "INPUT", FILTER_INPUT, true);
227 createChildChains(V4V6, "filter", "FORWARD", FILTER_FORWARD, true);
228 createChildChains(V4V6, "raw", "PREROUTING", RAW_PREROUTING, true);
229 createChildChains(V4V6, "mangle", "FORWARD", MANGLE_FORWARD, true);
230 createChildChains(V4V6, "mangle", "INPUT", MANGLE_INPUT, true);
231 createChildChains(V4, "nat", "PREROUTING", NAT_PREROUTING, true);
232 createChildChains(V4, "nat", "POSTROUTING", NAT_POSTROUTING, true);
233
234 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);
238 }
239
initIptablesRules()240 void Controllers::initIptablesRules() {
241 Stopwatch s;
242 initChildChains();
243 gLog.info("Creating child chains: %" PRId64 "us", s.getTimeAndResetUs());
244
245 // Let each module setup their child chains
246 setupOemIptablesHook();
247 gLog.info("Setting up OEM hooks: %" PRId64 "us", s.getTimeAndResetUs());
248
249 /* When enabled, DROPs all packets except those matching rules. */
250 firewallCtrl.setupIptablesHooks();
251 gLog.info("Setting up FirewallController hooks: %" PRId64 "us", s.getTimeAndResetUs());
252
253 /* Does DROPs in FORWARD by default */
254 tetherCtrl.setupIptablesHooks();
255 gLog.info("Setting up TetherController hooks: %" PRId64 "us", s.getTimeAndResetUs());
256
257 /*
258 * Does REJECT in INPUT, OUTPUT. Does counting also.
259 * No DROP/REJECT allowed later in netfilter-flow hook order.
260 */
261 bandwidthCtrl.setupIptablesHooks();
262 gLog.info("Setting up BandwidthController hooks: %" PRId64 "us", s.getTimeAndResetUs());
263
264 /*
265 * Counts in nat: PREROUTING, POSTROUTING.
266 * No DROP/REJECT allowed later in netfilter-flow hook order.
267 */
268 idletimerCtrl.setupIptablesHooks();
269 gLog.info("Setting up IdletimerController hooks: %" PRId64 "us", s.getTimeAndResetUs());
270
271 /*
272 * Add rules for detecting IPv6/IPv4 TCP/UDP connections with TLS/DTLS header
273 */
274 strictCtrl.setupIptablesHooks();
275 gLog.info("Setting up StrictController hooks: %" PRId64 "us", s.getTimeAndResetUs());
276 }
277
init()278 void Controllers::init() {
279 initIptablesRules();
280 Stopwatch s;
281
282 clatdCtrl.init();
283 gLog.info("Initializing ClatdController: %" PRId64 "us", s.getTimeAndResetUs());
284
285 netdutils::Status tcStatus = trafficCtrl.start();
286 if (!isOk(tcStatus)) {
287 gLog.error("Failed to start trafficcontroller: (%s)", toString(tcStatus).c_str());
288 }
289 gLog.info("Initializing traffic control: %" PRId64 "us", s.getTimeAndResetUs());
290
291 bandwidthCtrl.setBpfEnabled(trafficCtrl.getBpfEnabled());
292 bandwidthCtrl.enableBandwidthControl();
293 gLog.info("Enabling bandwidth control: %" PRId64 "us", s.getTimeAndResetUs());
294
295 if (int ret = RouteController::Init(NetworkController::LOCAL_NET_ID)) {
296 gLog.error("Failed to initialize RouteController (%s)", strerror(-ret));
297 }
298 gLog.info("Initializing RouteController: %" PRId64 "us", s.getTimeAndResetUs());
299
300 netdutils::Status xStatus = XfrmController::Init();
301 if (!isOk(xStatus)) {
302 gLog.error("Failed to initialize XfrmController (%s)", netdutils::toString(xStatus).c_str());
303 };
304 gLog.info("Initializing XfrmController: %" PRId64 "us", s.getTimeAndResetUs());
305 }
306
307 Controllers* gCtls = nullptr;
308
309 } // namespace net
310 } // namespace android
311