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 <regex>
18 #include <set>
19 #include <string>
20
21 #include <android-base/stringprintf.h>
22 #include <android-base/strings.h>
23 #include <netdutils/Stopwatch.h>
24
25 #define LOG_TAG "Netd"
26 #include <log/log.h>
27
28 #include "Controllers.h"
29 #include "IdletimerController.h"
30 #include "NetworkController.h"
31 #include "RouteController.h"
32 #include "XfrmController.h"
33 #include "oem_iptables_hook.h"
34
35 namespace android {
36 namespace net {
37
38 using android::base::StringAppendF;
39 using android::base::StringPrintf;
40 using android::netdutils::Stopwatch;
41
42 auto Controllers::execIptablesRestore = ::execIptablesRestore;
43 auto Controllers::execIptablesRestoreWithOutput = ::execIptablesRestoreWithOutput;
44
45 netdutils::Log gLog("netd");
46 netdutils::Log gUnsolicitedLog("netdUnsolicited");
47
48 namespace {
49
50 /**
51 * List of module chains to be created, along with explicit ordering. ORDERING
52 * IS CRITICAL, AND SHOULD BE TRIPLE-CHECKED WITH EACH CHANGE.
53 */
54 static const std::vector<const char*> FILTER_INPUT = {
55 // Bandwidth should always be early in input chain, to make sure we
56 // correctly count incoming traffic against data plan.
57 BandwidthController::LOCAL_INPUT,
58 FirewallController::LOCAL_INPUT,
59 };
60
61 static const std::vector<const char*> FILTER_FORWARD = {
62 OEM_IPTABLES_FILTER_FORWARD,
63 FirewallController::LOCAL_FORWARD,
64 BandwidthController::LOCAL_FORWARD,
65 TetherController::LOCAL_FORWARD,
66 };
67
68 static const std::vector<const char*> FILTER_OUTPUT = {
69 OEM_IPTABLES_FILTER_OUTPUT,
70 FirewallController::LOCAL_OUTPUT,
71 StrictController::LOCAL_OUTPUT,
72 BandwidthController::LOCAL_OUTPUT,
73 };
74
75 static const std::vector<const char*> RAW_PREROUTING = {
76 ClatdController::LOCAL_RAW_PREROUTING,
77 BandwidthController::LOCAL_RAW_PREROUTING,
78 IdletimerController::LOCAL_RAW_PREROUTING,
79 TetherController::LOCAL_RAW_PREROUTING,
80 };
81
82 static const std::vector<const char*> MANGLE_POSTROUTING = {
83 OEM_IPTABLES_MANGLE_POSTROUTING,
84 BandwidthController::LOCAL_MANGLE_POSTROUTING,
85 IdletimerController::LOCAL_MANGLE_POSTROUTING,
86 };
87
88 static const std::vector<const char*> MANGLE_INPUT = {
89 WakeupController::LOCAL_MANGLE_INPUT,
90 RouteController::LOCAL_MANGLE_INPUT,
91 };
92
93 static const std::vector<const char*> MANGLE_FORWARD = {
94 TetherController::LOCAL_MANGLE_FORWARD,
95 };
96
97 static const std::vector<const char*> NAT_PREROUTING = {
98 OEM_IPTABLES_NAT_PREROUTING,
99 };
100
101 static const std::vector<const char*> NAT_POSTROUTING = {
102 TetherController::LOCAL_NAT_POSTROUTING,
103 };
104
105 // Commands to create child chains and to match created chains in iptables -S output. Keep in sync.
106 static const char* CHILD_CHAIN_TEMPLATE = "-A %s -j %s\n";
107 static const std::regex CHILD_CHAIN_REGEX("^-A ([^ ]+) -j ([^ ]+)$",
108 std::regex_constants::extended);
109
110 } // namespace
111
112 /* static */
findExistingChildChains(const IptablesTarget target,const char * table,const char * parentChain)113 std::set<std::string> Controllers::findExistingChildChains(const IptablesTarget target,
114 const char* table,
115 const char* parentChain) {
116 if (target == V4V6) {
117 ALOGE("findExistingChildChains only supports one protocol at a time");
118 abort();
119 }
120
121 std::set<std::string> existing;
122
123 // List the current contents of parentChain.
124 //
125 // TODO: there is no guarantee that nothing else modifies the chain in the few milliseconds
126 // between when we list the existing rules and when we delete them. However:
127 // - Since this code is only run on startup, nothing else in netd will be running.
128 // - While vendor code is known to add its own rules to chains created by netd, it should never
129 // be modifying the rules in childChains or the rules that hook said chains into their parent
130 // chains.
131 std::string command = StringPrintf("*%s\n-S %s\nCOMMIT\n", table, parentChain);
132 std::string output;
133 if (Controllers::execIptablesRestoreWithOutput(target, command, &output) == -1) {
134 ALOGE("Error listing chain %s in table %s\n", parentChain, table);
135 return existing;
136 }
137
138 // The only rules added by createChildChains are of the simple form "-A <parent> -j <child>".
139 // Find those rules and add each one's child chain to existing.
140 std::smatch matches;
141 std::stringstream stream(output);
142 std::string rule;
143 while (std::getline(stream, rule, '\n')) {
144 if (std::regex_search(rule, matches, CHILD_CHAIN_REGEX) && matches[1] == parentChain) {
145 existing.insert(matches[2]);
146 }
147 }
148
149 return existing;
150 }
151
152 /* static */
createChildChains(IptablesTarget target,const char * table,const char * parentChain,const std::vector<const char * > & childChains,bool exclusive)153 void Controllers::createChildChains(IptablesTarget target, const char* table,
154 const char* parentChain,
155 const std::vector<const char*>& childChains,
156 bool exclusive) {
157 std::string command = StringPrintf("*%s\n", table);
158
159 // We cannot just clear all the chains we create because vendor code modifies filter OUTPUT and
160 // mangle POSTROUTING directly. So:
161 //
162 // - If we're the exclusive owner of this chain, simply clear it entirely.
163 // - If not, then list the chain's current contents to ensure that if we restart after a crash,
164 // we leave the existing rules alone in the positions they currently occupy. This is faster
165 // than blindly deleting our rules and recreating them, because deleting a rule that doesn't
166 // exists causes iptables-restore to quit, which takes ~30ms per delete. It's also more
167 // correct, because if we delete rules and re-add them, they'll be in the wrong position with
168 // regards to the vendor rules.
169 //
170 // TODO: Make all chains exclusive once vendor code uses the oem_* rules.
171 std::set<std::string> existingChildChains;
172 if (exclusive) {
173 // Just running ":chain -" flushes user-defined chains, but not built-in chains like INPUT.
174 // Since at this point we don't know if parentChain is a built-in chain, do both.
175 StringAppendF(&command, ":%s -\n", parentChain);
176 StringAppendF(&command, "-F %s\n", parentChain);
177 } else {
178 existingChildChains = findExistingChildChains(target, table, parentChain);
179 }
180
181 for (const auto& childChain : childChains) {
182 // Always clear the child chain.
183 StringAppendF(&command, ":%s -\n", childChain);
184 // But only add it to the parent chain if it's not already there.
185 if (existingChildChains.find(childChain) == existingChildChains.end()) {
186 StringAppendF(&command, CHILD_CHAIN_TEMPLATE, parentChain, childChain);
187 }
188 }
189 command += "COMMIT\n";
190 execIptablesRestore(target, command);
191 }
192
Controllers()193 Controllers::Controllers()
194 : clatdCtrl(&netCtrl),
195 wakeupCtrl(
196 [this](const WakeupController::ReportArgs& args) {
197 const auto listener = eventReporter.getNetdEventListener();
198 if (listener == nullptr) {
199 gLog.error("getNetdEventListener() returned nullptr. dropping wakeup event");
200 return;
201 }
202 String16 prefix = String16(args.prefix.c_str());
203 String16 srcIp = String16(args.srcIp.c_str());
204 String16 dstIp = String16(args.dstIp.c_str());
205 listener->onWakeupEvent(prefix, args.uid, args.ethertype, args.ipNextHeader,
206 args.dstHw, srcIp, dstIp, args.srcPort, args.dstPort,
207 args.timestampNs);
208 },
209 &iptablesRestoreCtrl) {
210 InterfaceController::initializeAll();
211 }
212
initChildChains()213 void Controllers::initChildChains() {
214 /*
215 * This is the only time we touch top-level chains in iptables; controllers
216 * should only mutate rules inside of their children chains, as created by
217 * the constants above.
218 *
219 * Modules should never ACCEPT packets (except in well-justified cases);
220 * they should instead defer to any remaining modules using RETURN, or
221 * otherwise DROP/REJECT.
222 */
223
224 // Create chains for child modules.
225 createChildChains(V4V6, "filter", "INPUT", FILTER_INPUT, true);
226 createChildChains(V4V6, "filter", "FORWARD", FILTER_FORWARD, true);
227 createChildChains(V4V6, "raw", "PREROUTING", RAW_PREROUTING, true);
228 createChildChains(V4V6, "mangle", "FORWARD", MANGLE_FORWARD, true);
229 createChildChains(V4V6, "mangle", "INPUT", MANGLE_INPUT, true);
230 createChildChains(V4, "nat", "PREROUTING", NAT_PREROUTING, true);
231 createChildChains(V4, "nat", "POSTROUTING", NAT_POSTROUTING, true);
232
233 createChildChains(V4, "filter", "OUTPUT", FILTER_OUTPUT, false);
234 createChildChains(V6, "filter", "OUTPUT", FILTER_OUTPUT, false);
235 createChildChains(V4, "mangle", "POSTROUTING", MANGLE_POSTROUTING, false);
236 createChildChains(V6, "mangle", "POSTROUTING", MANGLE_POSTROUTING, false);
237 }
238
initIptablesRules()239 void Controllers::initIptablesRules() {
240 Stopwatch s;
241 initChildChains();
242 gLog.info("Creating child chains: %.1fms", s.getTimeAndReset());
243
244 // Let each module setup their child chains
245 setupOemIptablesHook();
246 gLog.info("Setting up OEM hooks: %.1fms", s.getTimeAndReset());
247
248 /* When enabled, DROPs all packets except those matching rules. */
249 firewallCtrl.setupIptablesHooks();
250 gLog.info("Setting up FirewallController hooks: %.1fms", s.getTimeAndReset());
251
252 /* Does DROPs in FORWARD by default */
253 tetherCtrl.setupIptablesHooks();
254 gLog.info("Setting up TetherController hooks: %.1fms", s.getTimeAndReset());
255
256 /*
257 * Does REJECT in INPUT, OUTPUT. Does counting also.
258 * No DROP/REJECT allowed later in netfilter-flow hook order.
259 */
260 bandwidthCtrl.setupIptablesHooks();
261 gLog.info("Setting up BandwidthController hooks: %.1fms", s.getTimeAndReset());
262
263 /*
264 * Counts in nat: PREROUTING, POSTROUTING.
265 * No DROP/REJECT allowed later in netfilter-flow hook order.
266 */
267 idletimerCtrl.setupIptablesHooks();
268 gLog.info("Setting up IdletimerController hooks: %.1fms", s.getTimeAndReset());
269
270 /*
271 * Add rules for detecting IPv6/IPv4 TCP/UDP connections with TLS/DTLS header
272 */
273 strictCtrl.setupIptablesHooks();
274 gLog.info("Setting up StrictController hooks: %.1fms", s.getTimeAndReset());
275 }
276
init()277 void Controllers::init() {
278 initIptablesRules();
279 Stopwatch s;
280
281 clatdCtrl.init();
282 gLog.info("Initializing ClatdController: %.1fms", s.getTimeAndReset());
283
284 netdutils::Status tcStatus = trafficCtrl.start();
285 if (!isOk(tcStatus)) {
286 gLog.error("Failed to start trafficcontroller: (%s)", toString(tcStatus).c_str());
287 }
288 gLog.info("Initializing traffic control: %.1fms", s.getTimeAndReset());
289
290 bandwidthCtrl.setBpfEnabled(trafficCtrl.getBpfLevel() != android::bpf::BpfLevel::NONE);
291 bandwidthCtrl.enableBandwidthControl();
292 gLog.info("Enabling bandwidth control: %.1fms", s.getTimeAndReset());
293
294 if (int ret = RouteController::Init(NetworkController::LOCAL_NET_ID)) {
295 gLog.error("Failed to initialize RouteController (%s)", strerror(-ret));
296 }
297 gLog.info("Initializing RouteController: %.1fms", s.getTimeAndReset());
298
299 netdutils::Status xStatus = XfrmController::Init();
300 if (!isOk(xStatus)) {
301 gLog.error("Failed to initialize XfrmController (%s)", netdutils::toString(xStatus).c_str());
302 };
303 gLog.info("Initializing XfrmController: %.1fms", s.getTimeAndReset());
304 }
305
306 Controllers* gCtls = nullptr;
307
308 } // namespace net
309 } // namespace android
310