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