blob: 231a47f407f76ea2e7b1ad5e9a8f042224bcc6e6 [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 Utsumi65271202022-07-05 08:21:41 +000029import static android.net.INetd.PERMISSION_INTERNET;
30import static android.net.INetd.PERMISSION_UNINSTALLED;
Motomu Utsumi18b287d2022-06-19 10:45:30 +000031import static android.system.OsConstants.EINVAL;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000032import static android.system.OsConstants.ENODEV;
Motomu Utsumi60ed3be2022-06-24 10:38:57 +000033import static android.system.OsConstants.ENOENT;
Ken Chene6d511f2022-01-25 11:10:42 +080034import static android.system.OsConstants.EOPNOTSUPP;
35
Motomu Utsumif688eeb2022-07-22 03:47:35 +000036import android.content.Context;
Wayne Ma2fde98c2022-01-17 18:04:05 +080037import android.net.INetd;
38import android.os.RemoteException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080039import android.os.ServiceSpecificException;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000040import android.provider.DeviceConfig;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000041import android.system.ErrnoException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080042import android.system.Os;
43import android.util.Log;
44
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000045import com.android.internal.annotations.VisibleForTesting;
Ken Chenf5f51332022-01-28 10:08:16 +080046import com.android.modules.utils.build.SdkLevel;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000047import com.android.net.module.util.BpfMap;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000048import com.android.net.module.util.DeviceConfigUtils;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000049import com.android.net.module.util.Struct.U32;
Motomu Utsumi65271202022-07-05 08:21:41 +000050import com.android.net.module.util.Struct.U8;
Ken Chenf5f51332022-01-28 10:08:16 +080051
Ken Chene6d511f2022-01-25 11:10:42 +080052import java.io.FileDescriptor;
53import java.io.IOException;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000054import java.util.Arrays;
55import java.util.HashSet;
56import java.util.Set;
57import java.util.stream.Collectors;
Ken Chene6d511f2022-01-25 11:10:42 +080058
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080059/**
60 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
61 *
62 * {@hide}
63 */
64public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000065 private static final boolean PRE_T = !SdkLevel.isAtLeastT();
66 static {
67 if (!PRE_T) {
68 System.loadLibrary("service-connectivity");
69 }
70 }
71
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080072 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +080073 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000074 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +080075 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +080076 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080077
Motomu Utsumif688eeb2022-07-22 03:47:35 +000078 private static Boolean sEnableJavaBpfMap = null;
79 private static final String BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP =
80 "bpf_net_maps_enable_java_bpf_map";
81
Motomu Utsumi18b287d2022-06-19 10:45:30 +000082 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
83 // This entry is not accessed by others.
84 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
85 private static final Object sUidRulesConfigBpfMapLock = new Object();
86
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000087 private static final String CONFIGURATION_MAP_PATH =
88 "/sys/fs/bpf/netd_shared/map_netd_configuration_map";
Motomu Utsumi5a68a212022-06-24 10:14:31 +000089 private static final String UID_OWNER_MAP_PATH =
90 "/sys/fs/bpf/netd_shared/map_netd_uid_owner_map";
Motomu Utsumi65271202022-07-05 08:21:41 +000091 private static final String UID_PERMISSION_MAP_PATH =
92 "/sys/fs/bpf/netd_shared/map_netd_uid_permission_map";
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000093 private static final U32 UID_RULES_CONFIGURATION_KEY = new U32(0);
Motomu Utsumiba2fa152022-07-25 01:57:23 +000094 private static final U32 CURRENT_STATS_MAP_CONFIGURATION_KEY = new U32(1);
95 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
96 private static final long STATS_SELECT_MAP_A = 0;
97 private static final long STATS_SELECT_MAP_B = 1;
98
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000099 private static BpfMap<U32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000100 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
101 private static BpfMap<U32, UidOwnerValue> sUidOwnerMap = null;
Motomu Utsumi65271202022-07-05 08:21:41 +0000102 private static BpfMap<U32, U8> sUidPermissionMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000103
104 // LINT.IfChange(match_type)
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000105 @VisibleForTesting public static final long NO_MATCH = 0;
106 @VisibleForTesting public static final long HAPPY_BOX_MATCH = (1 << 0);
107 @VisibleForTesting public static final long PENALTY_BOX_MATCH = (1 << 1);
108 @VisibleForTesting public static final long DOZABLE_MATCH = (1 << 2);
109 @VisibleForTesting public static final long STANDBY_MATCH = (1 << 3);
110 @VisibleForTesting public static final long POWERSAVE_MATCH = (1 << 4);
111 @VisibleForTesting public static final long RESTRICTED_MATCH = (1 << 5);
112 @VisibleForTesting public static final long LOW_POWER_STANDBY_MATCH = (1 << 6);
113 @VisibleForTesting public static final long IIF_MATCH = (1 << 7);
114 @VisibleForTesting public static final long LOCKDOWN_VPN_MATCH = (1 << 8);
115 @VisibleForTesting public static final long OEM_DENY_1_MATCH = (1 << 9);
116 @VisibleForTesting public static final long OEM_DENY_2_MATCH = (1 << 10);
117 @VisibleForTesting public static final long OEM_DENY_3_MATCH = (1 << 11);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000118 // LINT.ThenChange(packages/modules/Connectivity/bpf_progs/bpf_shared.h)
119
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000120 /**
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000121 * Set sEnableJavaBpfMap for test.
122 */
123 @VisibleForTesting
124 public static void setEnableJavaBpfMapForTest(boolean enable) {
125 sEnableJavaBpfMap = enable;
126 }
127
128 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000129 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000130 */
131 @VisibleForTesting
Motomu Utsumi305975f2022-06-27 09:24:32 +0000132 public static void setConfigurationMapForTest(BpfMap<U32, U32> configurationMap) {
133 sConfigurationMap = configurationMap;
134 }
135
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000136 /**
137 * Set uidOwnerMap for test.
138 */
139 @VisibleForTesting
140 public static void setUidOwnerMapForTest(BpfMap<U32, UidOwnerValue> uidOwnerMap) {
141 sUidOwnerMap = uidOwnerMap;
142 }
143
Motomu Utsumi65271202022-07-05 08:21:41 +0000144 /**
145 * Set uidPermissionMap for test.
146 */
147 @VisibleForTesting
148 public static void setUidPermissionMapForTest(BpfMap<U32, U8> uidPermissionMap) {
149 sUidPermissionMap = uidPermissionMap;
150 }
151
Motomu Utsumi305975f2022-06-27 09:24:32 +0000152 private static BpfMap<U32, U32> getConfigurationMap() {
153 try {
154 return new BpfMap<>(
155 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, U32.class);
156 } catch (ErrnoException e) {
157 throw new IllegalStateException("Cannot open netd configuration map", e);
158 }
159 }
160
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000161 private static BpfMap<U32, UidOwnerValue> getUidOwnerMap() {
162 try {
163 return new BpfMap<>(
164 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, UidOwnerValue.class);
165 } catch (ErrnoException e) {
166 throw new IllegalStateException("Cannot open uid owner map", e);
167 }
168 }
169
Motomu Utsumi65271202022-07-05 08:21:41 +0000170 private static BpfMap<U32, U8> getUidPermissionMap() {
171 try {
172 return new BpfMap<>(
173 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, U8.class);
174 } catch (ErrnoException e) {
175 throw new IllegalStateException("Cannot open uid permission map", e);
176 }
177 }
178
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000179 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000180 if (sConfigurationMap == null) {
181 sConfigurationMap = getConfigurationMap();
182 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000183 try {
184 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
185 new U32(UID_RULES_DEFAULT_CONFIGURATION));
186 } catch (ErrnoException e) {
187 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
188 }
189 try {
190 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
191 new U32(STATS_SELECT_MAP_A));
192 } catch (ErrnoException e) {
193 throw new IllegalStateException("Failed to initialize current stats configuration", e);
194 }
195
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000196 if (sUidOwnerMap == null) {
197 sUidOwnerMap = getUidOwnerMap();
198 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000199 try {
200 sUidOwnerMap.clear();
201 } catch (ErrnoException e) {
202 throw new IllegalStateException("Failed to initialize uid owner map", e);
203 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000204
205 if (sUidPermissionMap == null) {
206 sUidPermissionMap = getUidPermissionMap();
207 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000208 }
209
Ken Chenf5f51332022-01-28 10:08:16 +0800210 /**
211 * Initializes the class if it is not already initialized. This method will open maps but not
212 * cause any other effects. This method may be called multiple times on any thread.
213 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000214 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800215 if (sInitialized) return;
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000216 if (sEnableJavaBpfMap == null) {
217 sEnableJavaBpfMap = DeviceConfigUtils.isFeatureEnabled(context,
218 DeviceConfig.NAMESPACE_TETHERING, BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP,
219 SdkLevel.isAtLeastU() /* defaultValue */);
220 }
221 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
222
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000223 initBpfMaps();
Motomu Utsumi305975f2022-06-27 09:24:32 +0000224 native_init();
Ken Chenf5f51332022-01-28 10:08:16 +0800225 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800226 }
227
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000228 /**
229 * Dependencies of BpfNetMaps, for injection in tests.
230 */
231 @VisibleForTesting
232 public static class Dependencies {
233 /**
234 * Get interface index.
235 */
236 public int getIfIndex(final String ifName) {
237 return Os.if_nametoindex(ifName);
238 }
239 }
240
markchien49e944c2022-03-01 15:22:20 +0800241 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000242 public BpfNetMaps(final Context context) {
243 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800244
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000245 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800246 }
247
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000248 public BpfNetMaps(final Context context, final INetd netd) {
249 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000250 }
251
252 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000253 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000254 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000255 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000256 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800257 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000258 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800259 }
260
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000261 /**
262 * Get corresponding match from firewall chain.
263 */
264 @VisibleForTesting
265 public long getMatchByFirewallChain(final int chain) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000266 switch (chain) {
267 case FIREWALL_CHAIN_DOZABLE:
268 return DOZABLE_MATCH;
269 case FIREWALL_CHAIN_STANDBY:
270 return STANDBY_MATCH;
271 case FIREWALL_CHAIN_POWERSAVE:
272 return POWERSAVE_MATCH;
273 case FIREWALL_CHAIN_RESTRICTED:
274 return RESTRICTED_MATCH;
275 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
276 return LOW_POWER_STANDBY_MATCH;
277 case FIREWALL_CHAIN_OEM_DENY_1:
278 return OEM_DENY_1_MATCH;
279 case FIREWALL_CHAIN_OEM_DENY_2:
280 return OEM_DENY_2_MATCH;
281 case FIREWALL_CHAIN_OEM_DENY_3:
282 return OEM_DENY_3_MATCH;
283 default:
284 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000285 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000286 }
287
288 /**
289 * Get if the chain is allow list or not.
290 *
291 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
292 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
293 */
294 @VisibleForTesting
295 public boolean isFirewallAllowList(final int chain) {
296 switch (chain) {
297 case FIREWALL_CHAIN_DOZABLE:
298 case FIREWALL_CHAIN_POWERSAVE:
299 case FIREWALL_CHAIN_RESTRICTED:
300 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
301 return true;
302 case FIREWALL_CHAIN_STANDBY:
303 case FIREWALL_CHAIN_OEM_DENY_1:
304 case FIREWALL_CHAIN_OEM_DENY_2:
305 case FIREWALL_CHAIN_OEM_DENY_3:
306 return false;
307 default:
308 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
309 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000310 }
311
Ken Chenf5f51332022-01-28 10:08:16 +0800312 private void maybeThrow(final int err, final String msg) {
313 if (err != 0) {
314 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
315 }
316 }
317
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000318 private void throwIfPreT(final String msg) {
319 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000320 throw new UnsupportedOperationException(msg);
321 }
322 }
323
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000324 private void removeRule(final int uid, final long match, final String caller) {
325 try {
326 synchronized (sUidOwnerMap) {
327 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
328
329 if (oldMatch == null) {
330 throw new ServiceSpecificException(ENOENT,
331 "sUidOwnerMap does not have entry for uid: " + uid);
332 }
333
334 final UidOwnerValue newMatch = new UidOwnerValue(
335 (match == IIF_MATCH) ? 0 : oldMatch.iif,
336 oldMatch.rule & ~match
337 );
338
339 if (newMatch.rule == 0) {
340 sUidOwnerMap.deleteEntry(new U32(uid));
341 } else {
342 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
343 }
344 }
345 } catch (ErrnoException e) {
346 throw new ServiceSpecificException(e.errno,
347 caller + " failed to remove rule: " + Os.strerror(e.errno));
348 }
349 }
350
Motomu Utsumi389278e2022-06-28 07:05:05 +0000351 private void addRule(final int uid, final long match, final long iif, final String caller) {
352 if (match != IIF_MATCH && iif != 0) {
353 throw new ServiceSpecificException(EINVAL,
354 "Non-interface match must have zero interface index");
355 }
356
357 try {
358 synchronized (sUidOwnerMap) {
359 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
360
361 final UidOwnerValue newMatch;
362 if (oldMatch != null) {
363 newMatch = new UidOwnerValue(
364 (match == IIF_MATCH) ? iif : oldMatch.iif,
365 oldMatch.rule | match
366 );
367 } else {
368 newMatch = new UidOwnerValue(
369 iif,
370 match
371 );
372 }
373 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
374 }
375 } catch (ErrnoException e) {
376 throw new ServiceSpecificException(e.errno,
377 caller + " failed to add rule: " + Os.strerror(e.errno));
378 }
379 }
380
381 private void addRule(final int uid, final long match, final String caller) {
382 addRule(uid, match, 0 /* iif */, caller);
383 }
384
Ken Chenf5f51332022-01-28 10:08:16 +0800385 /**
386 * Add naughty app bandwidth rule for specific app
387 *
388 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800389 * @throws ServiceSpecificException in case of failure, with an error code indicating the
390 * cause of the failure.
391 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900392 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000393 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000394
395 if (sEnableJavaBpfMap) {
396 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
397 } else {
398 final int err = native_addNaughtyApp(uid);
399 maybeThrow(err, "Unable to add naughty app");
400 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800401 }
402
Ken Chenf5f51332022-01-28 10:08:16 +0800403 /**
404 * Remove naughty app bandwidth rule for specific app
405 *
406 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800407 * @throws ServiceSpecificException in case of failure, with an error code indicating the
408 * cause of the failure.
409 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900410 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000411 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000412
413 if (sEnableJavaBpfMap) {
414 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
415 } else {
416 final int err = native_removeNaughtyApp(uid);
417 maybeThrow(err, "Unable to remove naughty app");
418 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800419 }
420
Ken Chenf5f51332022-01-28 10:08:16 +0800421 /**
422 * Add nice app bandwidth rule for specific app
423 *
424 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800425 * @throws ServiceSpecificException in case of failure, with an error code indicating the
426 * cause of the failure.
427 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900428 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000429 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000430
431 if (sEnableJavaBpfMap) {
432 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
433 } else {
434 final int err = native_addNiceApp(uid);
435 maybeThrow(err, "Unable to add nice app");
436 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800437 }
438
Ken Chenf5f51332022-01-28 10:08:16 +0800439 /**
440 * Remove nice app bandwidth rule for specific app
441 *
442 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800443 * @throws ServiceSpecificException in case of failure, with an error code indicating the
444 * cause of the failure.
445 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900446 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000447 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000448
449 if (sEnableJavaBpfMap) {
450 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
451 } else {
452 final int err = native_removeNiceApp(uid);
453 maybeThrow(err, "Unable to remove nice app");
454 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800455 }
456
Ken Chenf5f51332022-01-28 10:08:16 +0800457 /**
458 * Set target firewall child chain
459 *
460 * @param childChain target chain to enable
461 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000462 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800463 * @throws ServiceSpecificException in case of failure, with an error code indicating the
464 * cause of the failure.
465 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900466 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000467 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000468
Motomu Utsumie057dd42022-08-03 01:23:49 +0000469 if (sEnableJavaBpfMap) {
470 final long match = getMatchByFirewallChain(childChain);
471 try {
472 synchronized (sUidRulesConfigBpfMapLock) {
473 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
474 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
475 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
476 }
477 } catch (ErrnoException e) {
478 throw new ServiceSpecificException(e.errno,
479 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000480 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000481 } else {
482 final int err = native_setChildChain(childChain, enable);
483 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000484 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800485 }
486
487 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000488 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000489 *
490 * @param childChain target chain
491 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
492 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000493 * @throws ServiceSpecificException in case of failure, with an error code indicating the
494 * cause of the failure.
495 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000496 public boolean isChainEnabled(final int childChain) {
497 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000498
499 final long match = getMatchByFirewallChain(childChain);
500 try {
501 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000502 return (config.val & match) != 0;
503 } catch (ErrnoException e) {
504 throw new ServiceSpecificException(e.errno,
505 "Unable to get firewall chain status: " + Os.strerror(e.errno));
506 }
507 }
508
509 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800510 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000511 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800512 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000513 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800514 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000515 * @throws UnsupportedOperationException if called on pre-T devices.
516 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800517 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000518 public void replaceUidChain(final int chain, final int[] uids) {
519 throwIfPreT("replaceUidChain is not available on pre-T devices");
520
Motomu Utsumic7c16852022-08-03 06:51:41 +0000521 if (sEnableJavaBpfMap) {
522 final long match;
523 try {
524 match = getMatchByFirewallChain(chain);
525 } catch (ServiceSpecificException e) {
526 // Throws IllegalArgumentException to keep the behavior of
527 // ConnectivityManager#replaceFirewallChain API
528 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000529 }
Motomu Utsumic7c16852022-08-03 06:51:41 +0000530 final Set<Integer> uidSet = Arrays.stream(uids).boxed().collect(Collectors.toSet());
531 final Set<Integer> uidSetToRemoveRule = new HashSet<>();
532 try {
533 synchronized (sUidOwnerMap) {
534 sUidOwnerMap.forEach((uid, config) -> {
535 // config could be null if there is a concurrent entry deletion.
536 // http://b/220084230.
537 if (config != null
538 && !uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
539 uidSetToRemoveRule.add((int) uid.val);
540 }
541 });
542
543 for (final int uid : uidSetToRemoveRule) {
544 removeRule(uid, match, "replaceUidChain");
545 }
546 for (final int uid : uids) {
547 addRule(uid, match, "replaceUidChain");
548 }
549 }
550 } catch (ErrnoException | ServiceSpecificException e) {
551 Log.e(TAG, "replaceUidChain failed: " + e);
552 }
553 } else {
554 final int err;
555 switch (chain) {
556 case FIREWALL_CHAIN_DOZABLE:
557 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
558 break;
559 case FIREWALL_CHAIN_STANDBY:
560 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
561 break;
562 case FIREWALL_CHAIN_POWERSAVE:
563 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
564 break;
565 case FIREWALL_CHAIN_RESTRICTED:
566 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
567 break;
568 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
569 err = native_replaceUidChain(
570 "fw_low_power_standby", true /* isAllowList */, uids);
571 break;
572 case FIREWALL_CHAIN_OEM_DENY_1:
573 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
574 break;
575 case FIREWALL_CHAIN_OEM_DENY_2:
576 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
577 break;
578 case FIREWALL_CHAIN_OEM_DENY_3:
579 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
580 break;
581 default:
582 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
583 + chain);
584 }
585 if (err != 0) {
586 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
587 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800588 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800589 }
590
Ken Chenf5f51332022-01-28 10:08:16 +0800591 /**
592 * Set firewall rule for uid
593 *
594 * @param childChain target chain
595 * @param uid uid to allow/deny
596 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800597 * @throws ServiceSpecificException in case of failure, with an error code indicating the
598 * cause of the failure.
599 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900600 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000601 throwIfPreT("setUidRule is not available on pre-T devices");
602
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000603 if (sEnableJavaBpfMap) {
604 final long match = getMatchByFirewallChain(childChain);
605 final boolean isAllowList = isFirewallAllowList(childChain);
606 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
607 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000608
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000609 if (add) {
610 addRule(uid, match, "setUidRule");
611 } else {
612 removeRule(uid, match, "setUidRule");
613 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000614 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000615 final int err = native_setUidRule(childChain, uid, firewallRule);
616 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000617 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800618 }
619
620 /**
621 * Add ingress interface filtering rules to a list of UIDs
622 *
623 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
624 * allowed interface and loopback to be sent to the list of UIDs.
625 *
626 * Calling this method on one or more UIDs with an existing filtering rule but a different
627 * interface name will result in the filtering rule being updated to allow the new interface
628 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
629 *
630 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800631 * be received.
632 * @param uids an array of UIDs which the filtering rules will be set
633 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800634 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800635 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800636 */
Ken Chenf5f51332022-01-28 10:08:16 +0800637 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000638 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800639 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800640 return;
641 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000642
643 if (sEnableJavaBpfMap) {
644 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
645 // ifIndex is set to 0.
646 final int ifIndex;
647 if (ifName == null) {
648 ifIndex = 0;
649 } else {
650 ifIndex = mDeps.getIfIndex(ifName);
651 if (ifIndex == 0) {
652 throw new ServiceSpecificException(ENODEV,
653 "Failed to get index of interface " + ifName);
654 }
655 }
656 for (final int uid : uids) {
657 try {
658 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
659 } catch (ServiceSpecificException e) {
660 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
661 }
662 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000663 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000664 final int err = native_addUidInterfaceRules(ifName, uids);
665 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000666 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800667 }
668
669 /**
670 * Remove ingress interface filtering rules from a list of UIDs
671 *
672 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
673 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
674 *
675 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800676 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800677 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800678 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800679 */
Ken Chenf5f51332022-01-28 10:08:16 +0800680 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000681 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800682 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800683 return;
684 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000685
686 if (sEnableJavaBpfMap) {
687 for (final int uid : uids) {
688 try {
689 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
690 } catch (ServiceSpecificException e) {
691 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
692 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000693 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000694 } else {
695 final int err = native_removeUidInterfaceRules(uids);
696 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000697 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800698 }
699
Ken Chenf5f51332022-01-28 10:08:16 +0800700 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000701 * Update lockdown rule for uid
702 *
703 * @param uid target uid to add/remove the rule
704 * @param add {@code true} to add the rule, {@code false} to remove the rule.
705 * @throws ServiceSpecificException in case of failure, with an error code indicating the
706 * cause of the failure.
707 */
708 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000709 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000710
711 if (sEnableJavaBpfMap) {
712 if (add) {
713 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
714 } else {
715 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
716 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000717 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000718 final int err = native_updateUidLockdownRule(uid, add);
719 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000720 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000721 }
722
723 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800724 * Request netd to change the current active network stats map.
725 *
Ken Chenf5f51332022-01-28 10:08:16 +0800726 * @throws ServiceSpecificException in case of failure, with an error code indicating the
727 * cause of the failure.
728 */
markchien49e944c2022-03-01 15:22:20 +0800729 public void swapActiveStatsMap() {
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800730 final int err = native_swapActiveStatsMap();
Ken Chenf5f51332022-01-28 10:08:16 +0800731 maybeThrow(err, "Unable to swap active stats map");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800732 }
733
Ken Chenf5f51332022-01-28 10:08:16 +0800734 /**
735 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
736 * specified. Or remove all permissions from the uids.
737 *
738 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
739 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
740 * revoke all permissions for the uids.
741 * @param uids uid of users to grant permission
742 * @throws RemoteException when netd has crashed.
743 */
744 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000745 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800746 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800747 return;
748 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000749
750 if (sEnableJavaBpfMap) {
751 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
752 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
753 for (final int uid : uids) {
754 try {
755 sUidPermissionMap.deleteEntry(new U32(uid));
756 } catch (ErrnoException e) {
757 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
758 }
759 }
760 return;
761 }
762
763 for (final int uid : uids) {
764 try {
765 sUidPermissionMap.updateEntry(new U32(uid), new U8((short) permissions));
766 } catch (ErrnoException e) {
767 Log.e(TAG, "Failed to set permission "
768 + permissions + " to uid " + uid + ": " + e);
769 }
770 }
771 } else {
772 native_setPermissionForUids(permissions, uids);
773 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800774 }
775
Ken Chene6d511f2022-01-25 11:10:42 +0800776 /**
777 * Dump BPF maps
778 *
779 * @param fd file descriptor to output
780 * @throws IOException when file descriptor is invalid.
781 * @throws ServiceSpecificException when the method is called on an unsupported device.
782 */
783 public void dump(final FileDescriptor fd, boolean verbose)
784 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000785 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +0800786 throw new ServiceSpecificException(
787 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
788 + " devices, use dumpsys netd trafficcontroller instead.");
789 }
790 native_dump(fd, verbose);
791 }
792
Wayne Ma790c83e2022-01-13 10:35:05 +0800793 private static native void native_init();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800794 private native int native_addNaughtyApp(int uid);
795 private native int native_removeNaughtyApp(int uid);
796 private native int native_addNiceApp(int uid);
797 private native int native_removeNiceApp(int uid);
Motomu Utsumi114cd9c2022-08-01 02:08:35 +0000798 private native int native_setChildChain(int childChain, boolean enable);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800799 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
800 private native int native_setUidRule(int childChain, int uid, int firewallRule);
801 private native int native_addUidInterfaceRules(String ifName, int[] uids);
802 private native int native_removeUidInterfaceRules(int[] uids);
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000803 private native int native_updateUidLockdownRule(int uid, boolean add);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800804 private native int native_swapActiveStatsMap();
Wayne Ma2fde98c2022-01-17 18:04:05 +0800805 private native void native_setPermissionForUids(int permissions, int[] uids);
Ken Chene6d511f2022-01-25 11:10:42 +0800806 private native void native_dump(FileDescriptor fd, boolean verbose);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800807}