blob: 0270fc2b10bfc3427c96fc8d5a4fc5074d1f9209 [file] [log] [blame]
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001/*
2 * Copyright (C) 2022 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
17package com.android.server;
18
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000019import static android.net.ConnectivityManager.FIREWALL_CHAIN_DOZABLE;
20import static android.net.ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY;
21import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1;
22import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2;
23import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3;
24import static android.net.ConnectivityManager.FIREWALL_CHAIN_POWERSAVE;
25import static android.net.ConnectivityManager.FIREWALL_CHAIN_RESTRICTED;
26import static android.net.ConnectivityManager.FIREWALL_CHAIN_STANDBY;
Motomu Utsumi40230be2022-07-05 03:27:35 +000027import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
28import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Motomu Utsumi18b287d2022-06-19 10:45:30 +000029import static android.system.OsConstants.EINVAL;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000030import static android.system.OsConstants.ENODEV;
Motomu Utsumi60ed3be2022-06-24 10:38:57 +000031import static android.system.OsConstants.ENOENT;
Ken Chene6d511f2022-01-25 11:10:42 +080032import static android.system.OsConstants.EOPNOTSUPP;
33
Motomu Utsumif688eeb2022-07-22 03:47:35 +000034import android.content.Context;
Wayne Ma2fde98c2022-01-17 18:04:05 +080035import android.net.INetd;
36import android.os.RemoteException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080037import android.os.ServiceSpecificException;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000038import android.provider.DeviceConfig;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000039import android.system.ErrnoException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080040import android.system.Os;
41import android.util.Log;
42
Motomu Utsumi5a68a212022-06-24 10:14:31 +000043import com.android.internal.annotations.GuardedBy;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000044import com.android.internal.annotations.VisibleForTesting;
Ken Chenf5f51332022-01-28 10:08:16 +080045import com.android.modules.utils.build.SdkLevel;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000046import com.android.net.module.util.BpfMap;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000047import com.android.net.module.util.DeviceConfigUtils;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000048import com.android.net.module.util.Struct.U32;
Ken Chenf5f51332022-01-28 10:08:16 +080049
Ken Chene6d511f2022-01-25 11:10:42 +080050import java.io.FileDescriptor;
51import java.io.IOException;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000052import java.util.Arrays;
53import java.util.HashSet;
54import java.util.Set;
55import java.util.stream.Collectors;
Ken Chene6d511f2022-01-25 11:10:42 +080056
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080057/**
58 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
59 *
60 * {@hide}
61 */
62public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000063 private static final boolean PRE_T = !SdkLevel.isAtLeastT();
64 static {
65 if (!PRE_T) {
66 System.loadLibrary("service-connectivity");
67 }
68 }
69
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080070 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +080071 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000072 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +080073 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +080074 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080075
Motomu Utsumif688eeb2022-07-22 03:47:35 +000076 private static Boolean sEnableJavaBpfMap = null;
77 private static final String BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP =
78 "bpf_net_maps_enable_java_bpf_map";
79
Motomu Utsumi18b287d2022-06-19 10:45:30 +000080 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
81 // This entry is not accessed by others.
82 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
83 private static final Object sUidRulesConfigBpfMapLock = new Object();
84
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000085 private static final String CONFIGURATION_MAP_PATH =
86 "/sys/fs/bpf/netd_shared/map_netd_configuration_map";
Motomu Utsumi5a68a212022-06-24 10:14:31 +000087 private static final String UID_OWNER_MAP_PATH =
88 "/sys/fs/bpf/netd_shared/map_netd_uid_owner_map";
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000089 private static final U32 UID_RULES_CONFIGURATION_KEY = new U32(0);
90 private static BpfMap<U32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +000091 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
92 private static BpfMap<U32, UidOwnerValue> sUidOwnerMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000093
94 // LINT.IfChange(match_type)
Motomu Utsumi60ed3be2022-06-24 10:38:57 +000095 @VisibleForTesting public static final long NO_MATCH = 0;
96 @VisibleForTesting public static final long HAPPY_BOX_MATCH = (1 << 0);
97 @VisibleForTesting public static final long PENALTY_BOX_MATCH = (1 << 1);
98 @VisibleForTesting public static final long DOZABLE_MATCH = (1 << 2);
99 @VisibleForTesting public static final long STANDBY_MATCH = (1 << 3);
100 @VisibleForTesting public static final long POWERSAVE_MATCH = (1 << 4);
101 @VisibleForTesting public static final long RESTRICTED_MATCH = (1 << 5);
102 @VisibleForTesting public static final long LOW_POWER_STANDBY_MATCH = (1 << 6);
103 @VisibleForTesting public static final long IIF_MATCH = (1 << 7);
104 @VisibleForTesting public static final long LOCKDOWN_VPN_MATCH = (1 << 8);
105 @VisibleForTesting public static final long OEM_DENY_1_MATCH = (1 << 9);
106 @VisibleForTesting public static final long OEM_DENY_2_MATCH = (1 << 10);
107 @VisibleForTesting public static final long OEM_DENY_3_MATCH = (1 << 11);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000108 // LINT.ThenChange(packages/modules/Connectivity/bpf_progs/bpf_shared.h)
109
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000110 /**
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000111 * Set sEnableJavaBpfMap for test.
112 */
113 @VisibleForTesting
114 public static void setEnableJavaBpfMapForTest(boolean enable) {
115 sEnableJavaBpfMap = enable;
116 }
117
118 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000119 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000120 */
121 @VisibleForTesting
Motomu Utsumi305975f2022-06-27 09:24:32 +0000122 public static void setConfigurationMapForTest(BpfMap<U32, U32> configurationMap) {
123 sConfigurationMap = configurationMap;
124 }
125
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000126 /**
127 * Set uidOwnerMap for test.
128 */
129 @VisibleForTesting
130 public static void setUidOwnerMapForTest(BpfMap<U32, UidOwnerValue> uidOwnerMap) {
131 sUidOwnerMap = uidOwnerMap;
132 }
133
Motomu Utsumi305975f2022-06-27 09:24:32 +0000134 private static BpfMap<U32, U32> getConfigurationMap() {
135 try {
136 return new BpfMap<>(
137 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, U32.class);
138 } catch (ErrnoException e) {
139 throw new IllegalStateException("Cannot open netd configuration map", e);
140 }
141 }
142
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000143 private static BpfMap<U32, UidOwnerValue> getUidOwnerMap() {
144 try {
145 return new BpfMap<>(
146 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, UidOwnerValue.class);
147 } catch (ErrnoException e) {
148 throw new IllegalStateException("Cannot open uid owner map", e);
149 }
150 }
151
Motomu Utsumi305975f2022-06-27 09:24:32 +0000152 private static void setBpfMaps() {
153 if (sConfigurationMap == null) {
154 sConfigurationMap = getConfigurationMap();
155 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000156 if (sUidOwnerMap == null) {
157 sUidOwnerMap = getUidOwnerMap();
158 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000159 }
160
Ken Chenf5f51332022-01-28 10:08:16 +0800161 /**
162 * Initializes the class if it is not already initialized. This method will open maps but not
163 * cause any other effects. This method may be called multiple times on any thread.
164 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000165 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800166 if (sInitialized) return;
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000167 if (sEnableJavaBpfMap == null) {
168 sEnableJavaBpfMap = DeviceConfigUtils.isFeatureEnabled(context,
169 DeviceConfig.NAMESPACE_TETHERING, BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP,
170 SdkLevel.isAtLeastU() /* defaultValue */);
171 }
172 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
173
Motomu Utsumi305975f2022-06-27 09:24:32 +0000174 setBpfMaps();
175 native_init();
Ken Chenf5f51332022-01-28 10:08:16 +0800176 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800177 }
178
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000179 /**
180 * Dependencies of BpfNetMaps, for injection in tests.
181 */
182 @VisibleForTesting
183 public static class Dependencies {
184 /**
185 * Get interface index.
186 */
187 public int getIfIndex(final String ifName) {
188 return Os.if_nametoindex(ifName);
189 }
190 }
191
markchien49e944c2022-03-01 15:22:20 +0800192 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000193 public BpfNetMaps(final Context context) {
194 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800195
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000196 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800197 }
198
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000199 public BpfNetMaps(final Context context, final INetd netd) {
200 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000201 }
202
203 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000204 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000205 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000206 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000207 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800208 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000209 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800210 }
211
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000212 /**
213 * Get corresponding match from firewall chain.
214 */
215 @VisibleForTesting
216 public long getMatchByFirewallChain(final int chain) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000217 switch (chain) {
218 case FIREWALL_CHAIN_DOZABLE:
219 return DOZABLE_MATCH;
220 case FIREWALL_CHAIN_STANDBY:
221 return STANDBY_MATCH;
222 case FIREWALL_CHAIN_POWERSAVE:
223 return POWERSAVE_MATCH;
224 case FIREWALL_CHAIN_RESTRICTED:
225 return RESTRICTED_MATCH;
226 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
227 return LOW_POWER_STANDBY_MATCH;
228 case FIREWALL_CHAIN_OEM_DENY_1:
229 return OEM_DENY_1_MATCH;
230 case FIREWALL_CHAIN_OEM_DENY_2:
231 return OEM_DENY_2_MATCH;
232 case FIREWALL_CHAIN_OEM_DENY_3:
233 return OEM_DENY_3_MATCH;
234 default:
235 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000236 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000237 }
238
239 /**
240 * Get if the chain is allow list or not.
241 *
242 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
243 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
244 */
245 @VisibleForTesting
246 public boolean isFirewallAllowList(final int chain) {
247 switch (chain) {
248 case FIREWALL_CHAIN_DOZABLE:
249 case FIREWALL_CHAIN_POWERSAVE:
250 case FIREWALL_CHAIN_RESTRICTED:
251 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
252 return true;
253 case FIREWALL_CHAIN_STANDBY:
254 case FIREWALL_CHAIN_OEM_DENY_1:
255 case FIREWALL_CHAIN_OEM_DENY_2:
256 case FIREWALL_CHAIN_OEM_DENY_3:
257 return false;
258 default:
259 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
260 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000261 }
262
Ken Chenf5f51332022-01-28 10:08:16 +0800263 private void maybeThrow(final int err, final String msg) {
264 if (err != 0) {
265 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
266 }
267 }
268
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000269 private void throwIfPreT(final String msg) {
270 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000271 throw new UnsupportedOperationException(msg);
272 }
273 }
274
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000275 private void removeRule(final int uid, final long match, final String caller) {
276 try {
277 synchronized (sUidOwnerMap) {
278 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
279
280 if (oldMatch == null) {
281 throw new ServiceSpecificException(ENOENT,
282 "sUidOwnerMap does not have entry for uid: " + uid);
283 }
284
285 final UidOwnerValue newMatch = new UidOwnerValue(
286 (match == IIF_MATCH) ? 0 : oldMatch.iif,
287 oldMatch.rule & ~match
288 );
289
290 if (newMatch.rule == 0) {
291 sUidOwnerMap.deleteEntry(new U32(uid));
292 } else {
293 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
294 }
295 }
296 } catch (ErrnoException e) {
297 throw new ServiceSpecificException(e.errno,
298 caller + " failed to remove rule: " + Os.strerror(e.errno));
299 }
300 }
301
Motomu Utsumi389278e2022-06-28 07:05:05 +0000302 private void addRule(final int uid, final long match, final long iif, final String caller) {
303 if (match != IIF_MATCH && iif != 0) {
304 throw new ServiceSpecificException(EINVAL,
305 "Non-interface match must have zero interface index");
306 }
307
308 try {
309 synchronized (sUidOwnerMap) {
310 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
311
312 final UidOwnerValue newMatch;
313 if (oldMatch != null) {
314 newMatch = new UidOwnerValue(
315 (match == IIF_MATCH) ? iif : oldMatch.iif,
316 oldMatch.rule | match
317 );
318 } else {
319 newMatch = new UidOwnerValue(
320 iif,
321 match
322 );
323 }
324 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
325 }
326 } catch (ErrnoException e) {
327 throw new ServiceSpecificException(e.errno,
328 caller + " failed to add rule: " + Os.strerror(e.errno));
329 }
330 }
331
332 private void addRule(final int uid, final long match, final String caller) {
333 addRule(uid, match, 0 /* iif */, caller);
334 }
335
Ken Chenf5f51332022-01-28 10:08:16 +0800336 /**
337 * Add naughty app bandwidth rule for specific app
338 *
339 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800340 * @throws ServiceSpecificException in case of failure, with an error code indicating the
341 * cause of the failure.
342 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900343 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000344 throwIfPreT("addNaughtyApp is not available on pre-T devices");
345 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800346 }
347
Ken Chenf5f51332022-01-28 10:08:16 +0800348 /**
349 * Remove naughty app bandwidth rule for specific app
350 *
351 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800352 * @throws ServiceSpecificException in case of failure, with an error code indicating the
353 * cause of the failure.
354 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900355 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000356 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
357 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800358 }
359
Ken Chenf5f51332022-01-28 10:08:16 +0800360 /**
361 * Add nice app bandwidth rule for specific app
362 *
363 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800364 * @throws ServiceSpecificException in case of failure, with an error code indicating the
365 * cause of the failure.
366 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900367 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000368 throwIfPreT("addNiceApp is not available on pre-T devices");
369 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800370 }
371
Ken Chenf5f51332022-01-28 10:08:16 +0800372 /**
373 * Remove nice app bandwidth rule for specific app
374 *
375 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800376 * @throws ServiceSpecificException in case of failure, with an error code indicating the
377 * cause of the failure.
378 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900379 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000380 throwIfPreT("removeNiceApp is not available on pre-T devices");
381 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800382 }
383
Ken Chenf5f51332022-01-28 10:08:16 +0800384 /**
385 * Set target firewall child chain
386 *
387 * @param childChain target chain to enable
388 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000389 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800390 * @throws ServiceSpecificException in case of failure, with an error code indicating the
391 * cause of the failure.
392 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900393 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000394 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000395
396 final long match = getMatchByFirewallChain(childChain);
397 try {
398 synchronized (sUidRulesConfigBpfMapLock) {
399 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000400 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000401 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
402 }
403 } catch (ErrnoException e) {
404 throw new ServiceSpecificException(e.errno,
405 "Unable to set child chain: " + Os.strerror(e.errno));
406 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800407 }
408
409 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000410 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000411 *
412 * @param childChain target chain
413 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
414 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000415 * @throws ServiceSpecificException in case of failure, with an error code indicating the
416 * cause of the failure.
417 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000418 public boolean isChainEnabled(final int childChain) {
419 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000420
421 final long match = getMatchByFirewallChain(childChain);
422 try {
423 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000424 return (config.val & match) != 0;
425 } catch (ErrnoException e) {
426 throw new ServiceSpecificException(e.errno,
427 "Unable to get firewall chain status: " + Os.strerror(e.errno));
428 }
429 }
430
431 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800432 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000433 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800434 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000435 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800436 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000437 * @throws UnsupportedOperationException if called on pre-T devices.
438 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800439 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000440 public void replaceUidChain(final int chain, final int[] uids) {
441 throwIfPreT("replaceUidChain is not available on pre-T devices");
442
443 final long match;
444 try {
445 match = getMatchByFirewallChain(chain);
446 } catch (ServiceSpecificException e) {
447 // Throws IllegalArgumentException to keep the behavior of
448 // ConnectivityManager#replaceFirewallChain API
449 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
450 }
451 final Set<Integer> uidSet = Arrays.stream(uids).boxed().collect(Collectors.toSet());
452 final Set<Integer> uidSetToRemoveRule = new HashSet<>();
453 try {
454 synchronized (sUidOwnerMap) {
455 sUidOwnerMap.forEach((uid, config) -> {
456 // config could be null if there is a concurrent entry deletion.
457 // http://b/220084230.
458 if (config != null
459 && !uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
460 uidSetToRemoveRule.add((int) uid.val);
461 }
462 });
463
464 for (final int uid : uidSetToRemoveRule) {
465 removeRule(uid, match, "replaceUidChain");
466 }
467 for (final int uid : uids) {
468 addRule(uid, match, "replaceUidChain");
469 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000470 }
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000471 } catch (ErrnoException | ServiceSpecificException e) {
472 Log.e(TAG, "replaceUidChain failed: " + e);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800473 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800474 }
475
Ken Chenf5f51332022-01-28 10:08:16 +0800476 /**
477 * Set firewall rule for uid
478 *
479 * @param childChain target chain
480 * @param uid uid to allow/deny
481 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800482 * @throws ServiceSpecificException in case of failure, with an error code indicating the
483 * cause of the failure.
484 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900485 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000486 throwIfPreT("setUidRule is not available on pre-T devices");
487
488 final long match = getMatchByFirewallChain(childChain);
489 final boolean isAllowList = isFirewallAllowList(childChain);
490 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
491 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
492
493 if (add) {
494 addRule(uid, match, "setUidRule");
495 } else {
496 removeRule(uid, match, "setUidRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000497 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800498 }
499
500 /**
501 * Add ingress interface filtering rules to a list of UIDs
502 *
503 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
504 * allowed interface and loopback to be sent to the list of UIDs.
505 *
506 * Calling this method on one or more UIDs with an existing filtering rule but a different
507 * interface name will result in the filtering rule being updated to allow the new interface
508 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
509 *
510 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800511 * be received.
512 * @param uids an array of UIDs which the filtering rules will be set
513 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800514 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800515 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800516 */
Ken Chenf5f51332022-01-28 10:08:16 +0800517 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000518 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800519 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800520 return;
521 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000522 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and ifIndex
523 // is set to 0.
524 final int ifIndex;
525 if (ifName == null) {
526 ifIndex = 0;
527 } else {
528 ifIndex = mDeps.getIfIndex(ifName);
529 if (ifIndex == 0) {
530 throw new ServiceSpecificException(ENODEV,
531 "Failed to get index of interface " + ifName);
532 }
533 }
534 for (final int uid: uids) {
535 try {
536 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
537 } catch (ServiceSpecificException e) {
538 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
539 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000540 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800541 }
542
543 /**
544 * Remove ingress interface filtering rules from a list of UIDs
545 *
546 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
547 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
548 *
549 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800550 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800551 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800552 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800553 */
Ken Chenf5f51332022-01-28 10:08:16 +0800554 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000555 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800556 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800557 return;
558 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000559 for (final int uid: uids) {
560 try {
561 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
562 } catch (ServiceSpecificException e) {
563 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
564 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000565 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800566 }
567
Ken Chenf5f51332022-01-28 10:08:16 +0800568 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000569 * Update lockdown rule for uid
570 *
571 * @param uid target uid to add/remove the rule
572 * @param add {@code true} to add the rule, {@code false} to remove the rule.
573 * @throws ServiceSpecificException in case of failure, with an error code indicating the
574 * cause of the failure.
575 */
576 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000577 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
578 if (add) {
579 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
580 } else {
581 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000582 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000583 }
584
585 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800586 * Request netd to change the current active network stats map.
587 *
Ken Chenf5f51332022-01-28 10:08:16 +0800588 * @throws ServiceSpecificException in case of failure, with an error code indicating the
589 * cause of the failure.
590 */
markchien49e944c2022-03-01 15:22:20 +0800591 public void swapActiveStatsMap() {
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800592 final int err = native_swapActiveStatsMap();
Ken Chenf5f51332022-01-28 10:08:16 +0800593 maybeThrow(err, "Unable to swap active stats map");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800594 }
595
Ken Chenf5f51332022-01-28 10:08:16 +0800596 /**
597 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
598 * specified. Or remove all permissions from the uids.
599 *
600 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
601 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
602 * revoke all permissions for the uids.
603 * @param uids uid of users to grant permission
604 * @throws RemoteException when netd has crashed.
605 */
606 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000607 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800608 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800609 return;
610 }
611 native_setPermissionForUids(permissions, uids);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800612 }
613
Ken Chene6d511f2022-01-25 11:10:42 +0800614 /**
615 * Dump BPF maps
616 *
617 * @param fd file descriptor to output
618 * @throws IOException when file descriptor is invalid.
619 * @throws ServiceSpecificException when the method is called on an unsupported device.
620 */
621 public void dump(final FileDescriptor fd, boolean verbose)
622 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000623 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +0800624 throw new ServiceSpecificException(
625 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
626 + " devices, use dumpsys netd trafficcontroller instead.");
627 }
628 native_dump(fd, verbose);
629 }
630
Wayne Ma790c83e2022-01-13 10:35:05 +0800631 private static native void native_init();
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000632 @GuardedBy("sUidOwnerMap")
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800633 private native int native_addNaughtyApp(int uid);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000634 @GuardedBy("sUidOwnerMap")
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800635 private native int native_removeNaughtyApp(int uid);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000636 @GuardedBy("sUidOwnerMap")
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800637 private native int native_addNiceApp(int uid);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000638 @GuardedBy("sUidOwnerMap")
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800639 private native int native_removeNiceApp(int uid);
Motomu Utsumi114cd9c2022-08-01 02:08:35 +0000640 private native int native_setChildChain(int childChain, boolean enable);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000641 @GuardedBy("sUidOwnerMap")
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800642 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000643 @GuardedBy("sUidOwnerMap")
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800644 private native int native_setUidRule(int childChain, int uid, int firewallRule);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000645 @GuardedBy("sUidOwnerMap")
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800646 private native int native_addUidInterfaceRules(String ifName, int[] uids);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000647 @GuardedBy("sUidOwnerMap")
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800648 private native int native_removeUidInterfaceRules(int[] uids);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000649 @GuardedBy("sUidOwnerMap")
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000650 private native int native_updateUidLockdownRule(int uid, boolean add);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800651 private native int native_swapActiveStatsMap();
Wayne Ma2fde98c2022-01-17 18:04:05 +0800652 private native void native_setPermissionForUids(int permissions, int[] uids);
Ken Chene6d511f2022-01-25 11:10:42 +0800653 private native void native_dump(FileDescriptor fd, boolean verbose);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800654}