blob: 7387483470aacf59d7d447e3e7ff440fc7f51eb8 [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 Utsumi7abeaa42022-07-20 07:54:18 +000087 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
88 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
89 // BpfNetMaps is an only writer of this entry.
90 private static final Object sCurrentStatsMapConfigLock = new Object();
91
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000092 private static final String CONFIGURATION_MAP_PATH =
93 "/sys/fs/bpf/netd_shared/map_netd_configuration_map";
Motomu Utsumi5a68a212022-06-24 10:14:31 +000094 private static final String UID_OWNER_MAP_PATH =
95 "/sys/fs/bpf/netd_shared/map_netd_uid_owner_map";
Motomu Utsumi65271202022-07-05 08:21:41 +000096 private static final String UID_PERMISSION_MAP_PATH =
97 "/sys/fs/bpf/netd_shared/map_netd_uid_permission_map";
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000098 private static final U32 UID_RULES_CONFIGURATION_KEY = new U32(0);
Motomu Utsumiba2fa152022-07-25 01:57:23 +000099 private static final U32 CURRENT_STATS_MAP_CONFIGURATION_KEY = new U32(1);
100 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
101 private static final long STATS_SELECT_MAP_A = 0;
102 private static final long STATS_SELECT_MAP_B = 1;
103
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000104 private static BpfMap<U32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000105 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
106 private static BpfMap<U32, UidOwnerValue> sUidOwnerMap = null;
Motomu Utsumi65271202022-07-05 08:21:41 +0000107 private static BpfMap<U32, U8> sUidPermissionMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000108
109 // LINT.IfChange(match_type)
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000110 @VisibleForTesting public static final long NO_MATCH = 0;
111 @VisibleForTesting public static final long HAPPY_BOX_MATCH = (1 << 0);
112 @VisibleForTesting public static final long PENALTY_BOX_MATCH = (1 << 1);
113 @VisibleForTesting public static final long DOZABLE_MATCH = (1 << 2);
114 @VisibleForTesting public static final long STANDBY_MATCH = (1 << 3);
115 @VisibleForTesting public static final long POWERSAVE_MATCH = (1 << 4);
116 @VisibleForTesting public static final long RESTRICTED_MATCH = (1 << 5);
117 @VisibleForTesting public static final long LOW_POWER_STANDBY_MATCH = (1 << 6);
118 @VisibleForTesting public static final long IIF_MATCH = (1 << 7);
119 @VisibleForTesting public static final long LOCKDOWN_VPN_MATCH = (1 << 8);
120 @VisibleForTesting public static final long OEM_DENY_1_MATCH = (1 << 9);
121 @VisibleForTesting public static final long OEM_DENY_2_MATCH = (1 << 10);
122 @VisibleForTesting public static final long OEM_DENY_3_MATCH = (1 << 11);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000123 // LINT.ThenChange(packages/modules/Connectivity/bpf_progs/bpf_shared.h)
124
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000125 /**
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000126 * Set sEnableJavaBpfMap for test.
127 */
128 @VisibleForTesting
129 public static void setEnableJavaBpfMapForTest(boolean enable) {
130 sEnableJavaBpfMap = enable;
131 }
132
133 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000134 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000135 */
136 @VisibleForTesting
Motomu Utsumi305975f2022-06-27 09:24:32 +0000137 public static void setConfigurationMapForTest(BpfMap<U32, U32> configurationMap) {
138 sConfigurationMap = configurationMap;
139 }
140
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000141 /**
142 * Set uidOwnerMap for test.
143 */
144 @VisibleForTesting
145 public static void setUidOwnerMapForTest(BpfMap<U32, UidOwnerValue> uidOwnerMap) {
146 sUidOwnerMap = uidOwnerMap;
147 }
148
Motomu Utsumi65271202022-07-05 08:21:41 +0000149 /**
150 * Set uidPermissionMap for test.
151 */
152 @VisibleForTesting
153 public static void setUidPermissionMapForTest(BpfMap<U32, U8> uidPermissionMap) {
154 sUidPermissionMap = uidPermissionMap;
155 }
156
Motomu Utsumi305975f2022-06-27 09:24:32 +0000157 private static BpfMap<U32, U32> getConfigurationMap() {
158 try {
159 return new BpfMap<>(
160 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, U32.class);
161 } catch (ErrnoException e) {
162 throw new IllegalStateException("Cannot open netd configuration map", e);
163 }
164 }
165
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000166 private static BpfMap<U32, UidOwnerValue> getUidOwnerMap() {
167 try {
168 return new BpfMap<>(
169 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, UidOwnerValue.class);
170 } catch (ErrnoException e) {
171 throw new IllegalStateException("Cannot open uid owner map", e);
172 }
173 }
174
Motomu Utsumi65271202022-07-05 08:21:41 +0000175 private static BpfMap<U32, U8> getUidPermissionMap() {
176 try {
177 return new BpfMap<>(
178 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, U8.class);
179 } catch (ErrnoException e) {
180 throw new IllegalStateException("Cannot open uid permission map", e);
181 }
182 }
183
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000184 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000185 if (sConfigurationMap == null) {
186 sConfigurationMap = getConfigurationMap();
187 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000188 try {
189 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
190 new U32(UID_RULES_DEFAULT_CONFIGURATION));
191 } catch (ErrnoException e) {
192 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
193 }
194 try {
195 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
196 new U32(STATS_SELECT_MAP_A));
197 } catch (ErrnoException e) {
198 throw new IllegalStateException("Failed to initialize current stats configuration", e);
199 }
200
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000201 if (sUidOwnerMap == null) {
202 sUidOwnerMap = getUidOwnerMap();
203 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000204 try {
205 sUidOwnerMap.clear();
206 } catch (ErrnoException e) {
207 throw new IllegalStateException("Failed to initialize uid owner map", e);
208 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000209
210 if (sUidPermissionMap == null) {
211 sUidPermissionMap = getUidPermissionMap();
212 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000213 }
214
Ken Chenf5f51332022-01-28 10:08:16 +0800215 /**
216 * Initializes the class if it is not already initialized. This method will open maps but not
217 * cause any other effects. This method may be called multiple times on any thread.
218 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000219 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800220 if (sInitialized) return;
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000221 if (sEnableJavaBpfMap == null) {
222 sEnableJavaBpfMap = DeviceConfigUtils.isFeatureEnabled(context,
223 DeviceConfig.NAMESPACE_TETHERING, BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP,
224 SdkLevel.isAtLeastU() /* defaultValue */);
225 }
226 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
227
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000228 initBpfMaps();
Motomu Utsumi305975f2022-06-27 09:24:32 +0000229 native_init();
Ken Chenf5f51332022-01-28 10:08:16 +0800230 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800231 }
232
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000233 /**
234 * Dependencies of BpfNetMaps, for injection in tests.
235 */
236 @VisibleForTesting
237 public static class Dependencies {
238 /**
239 * Get interface index.
240 */
241 public int getIfIndex(final String ifName) {
242 return Os.if_nametoindex(ifName);
243 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000244
245 /**
246 * Call synchronize_rcu()
247 */
248 public int synchronizeKernelRCU() {
249 return native_synchronizeKernelRCU();
250 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000251 }
252
markchien49e944c2022-03-01 15:22:20 +0800253 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000254 public BpfNetMaps(final Context context) {
255 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800256
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000257 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800258 }
259
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000260 public BpfNetMaps(final Context context, final INetd netd) {
261 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000262 }
263
264 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000265 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000266 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000267 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000268 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800269 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000270 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800271 }
272
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000273 /**
274 * Get corresponding match from firewall chain.
275 */
276 @VisibleForTesting
277 public long getMatchByFirewallChain(final int chain) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000278 switch (chain) {
279 case FIREWALL_CHAIN_DOZABLE:
280 return DOZABLE_MATCH;
281 case FIREWALL_CHAIN_STANDBY:
282 return STANDBY_MATCH;
283 case FIREWALL_CHAIN_POWERSAVE:
284 return POWERSAVE_MATCH;
285 case FIREWALL_CHAIN_RESTRICTED:
286 return RESTRICTED_MATCH;
287 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
288 return LOW_POWER_STANDBY_MATCH;
289 case FIREWALL_CHAIN_OEM_DENY_1:
290 return OEM_DENY_1_MATCH;
291 case FIREWALL_CHAIN_OEM_DENY_2:
292 return OEM_DENY_2_MATCH;
293 case FIREWALL_CHAIN_OEM_DENY_3:
294 return OEM_DENY_3_MATCH;
295 default:
296 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000297 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000298 }
299
300 /**
301 * Get if the chain is allow list or not.
302 *
303 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
304 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
305 */
306 @VisibleForTesting
307 public boolean isFirewallAllowList(final int chain) {
308 switch (chain) {
309 case FIREWALL_CHAIN_DOZABLE:
310 case FIREWALL_CHAIN_POWERSAVE:
311 case FIREWALL_CHAIN_RESTRICTED:
312 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
313 return true;
314 case FIREWALL_CHAIN_STANDBY:
315 case FIREWALL_CHAIN_OEM_DENY_1:
316 case FIREWALL_CHAIN_OEM_DENY_2:
317 case FIREWALL_CHAIN_OEM_DENY_3:
318 return false;
319 default:
320 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
321 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000322 }
323
Ken Chenf5f51332022-01-28 10:08:16 +0800324 private void maybeThrow(final int err, final String msg) {
325 if (err != 0) {
326 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
327 }
328 }
329
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000330 private void throwIfPreT(final String msg) {
331 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000332 throw new UnsupportedOperationException(msg);
333 }
334 }
335
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000336 private void removeRule(final int uid, final long match, final String caller) {
337 try {
338 synchronized (sUidOwnerMap) {
339 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
340
341 if (oldMatch == null) {
342 throw new ServiceSpecificException(ENOENT,
343 "sUidOwnerMap does not have entry for uid: " + uid);
344 }
345
346 final UidOwnerValue newMatch = new UidOwnerValue(
347 (match == IIF_MATCH) ? 0 : oldMatch.iif,
348 oldMatch.rule & ~match
349 );
350
351 if (newMatch.rule == 0) {
352 sUidOwnerMap.deleteEntry(new U32(uid));
353 } else {
354 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
355 }
356 }
357 } catch (ErrnoException e) {
358 throw new ServiceSpecificException(e.errno,
359 caller + " failed to remove rule: " + Os.strerror(e.errno));
360 }
361 }
362
Motomu Utsumi389278e2022-06-28 07:05:05 +0000363 private void addRule(final int uid, final long match, final long iif, final String caller) {
364 if (match != IIF_MATCH && iif != 0) {
365 throw new ServiceSpecificException(EINVAL,
366 "Non-interface match must have zero interface index");
367 }
368
369 try {
370 synchronized (sUidOwnerMap) {
371 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
372
373 final UidOwnerValue newMatch;
374 if (oldMatch != null) {
375 newMatch = new UidOwnerValue(
376 (match == IIF_MATCH) ? iif : oldMatch.iif,
377 oldMatch.rule | match
378 );
379 } else {
380 newMatch = new UidOwnerValue(
381 iif,
382 match
383 );
384 }
385 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
386 }
387 } catch (ErrnoException e) {
388 throw new ServiceSpecificException(e.errno,
389 caller + " failed to add rule: " + Os.strerror(e.errno));
390 }
391 }
392
393 private void addRule(final int uid, final long match, final String caller) {
394 addRule(uid, match, 0 /* iif */, caller);
395 }
396
Ken Chenf5f51332022-01-28 10:08:16 +0800397 /**
398 * Add naughty app bandwidth rule for specific app
399 *
400 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800401 * @throws ServiceSpecificException in case of failure, with an error code indicating the
402 * cause of the failure.
403 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900404 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000405 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000406
407 if (sEnableJavaBpfMap) {
408 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
409 } else {
410 final int err = native_addNaughtyApp(uid);
411 maybeThrow(err, "Unable to add naughty app");
412 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800413 }
414
Ken Chenf5f51332022-01-28 10:08:16 +0800415 /**
416 * Remove naughty app bandwidth rule for specific app
417 *
418 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800419 * @throws ServiceSpecificException in case of failure, with an error code indicating the
420 * cause of the failure.
421 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900422 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000423 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000424
425 if (sEnableJavaBpfMap) {
426 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
427 } else {
428 final int err = native_removeNaughtyApp(uid);
429 maybeThrow(err, "Unable to remove naughty app");
430 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800431 }
432
Ken Chenf5f51332022-01-28 10:08:16 +0800433 /**
434 * Add nice app bandwidth rule for specific app
435 *
436 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800437 * @throws ServiceSpecificException in case of failure, with an error code indicating the
438 * cause of the failure.
439 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900440 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000441 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000442
443 if (sEnableJavaBpfMap) {
444 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
445 } else {
446 final int err = native_addNiceApp(uid);
447 maybeThrow(err, "Unable to add nice app");
448 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800449 }
450
Ken Chenf5f51332022-01-28 10:08:16 +0800451 /**
452 * Remove nice app bandwidth rule for specific app
453 *
454 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800455 * @throws ServiceSpecificException in case of failure, with an error code indicating the
456 * cause of the failure.
457 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900458 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000459 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000460
461 if (sEnableJavaBpfMap) {
462 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
463 } else {
464 final int err = native_removeNiceApp(uid);
465 maybeThrow(err, "Unable to remove nice app");
466 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800467 }
468
Ken Chenf5f51332022-01-28 10:08:16 +0800469 /**
470 * Set target firewall child chain
471 *
472 * @param childChain target chain to enable
473 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000474 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800475 * @throws ServiceSpecificException in case of failure, with an error code indicating the
476 * cause of the failure.
477 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900478 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000479 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000480
Motomu Utsumie057dd42022-08-03 01:23:49 +0000481 if (sEnableJavaBpfMap) {
482 final long match = getMatchByFirewallChain(childChain);
483 try {
484 synchronized (sUidRulesConfigBpfMapLock) {
485 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
486 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
487 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
488 }
489 } catch (ErrnoException e) {
490 throw new ServiceSpecificException(e.errno,
491 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000492 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000493 } else {
494 final int err = native_setChildChain(childChain, enable);
495 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000496 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800497 }
498
499 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000500 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000501 *
502 * @param childChain target chain
503 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
504 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000505 * @throws ServiceSpecificException in case of failure, with an error code indicating the
506 * cause of the failure.
507 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000508 public boolean isChainEnabled(final int childChain) {
509 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000510
511 final long match = getMatchByFirewallChain(childChain);
512 try {
513 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000514 return (config.val & match) != 0;
515 } catch (ErrnoException e) {
516 throw new ServiceSpecificException(e.errno,
517 "Unable to get firewall chain status: " + Os.strerror(e.errno));
518 }
519 }
520
521 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800522 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000523 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800524 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000525 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800526 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000527 * @throws UnsupportedOperationException if called on pre-T devices.
528 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800529 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000530 public void replaceUidChain(final int chain, final int[] uids) {
531 throwIfPreT("replaceUidChain is not available on pre-T devices");
532
Motomu Utsumic7c16852022-08-03 06:51:41 +0000533 if (sEnableJavaBpfMap) {
534 final long match;
535 try {
536 match = getMatchByFirewallChain(chain);
537 } catch (ServiceSpecificException e) {
538 // Throws IllegalArgumentException to keep the behavior of
539 // ConnectivityManager#replaceFirewallChain API
540 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000541 }
Motomu Utsumic7c16852022-08-03 06:51:41 +0000542 final Set<Integer> uidSet = Arrays.stream(uids).boxed().collect(Collectors.toSet());
543 final Set<Integer> uidSetToRemoveRule = new HashSet<>();
544 try {
545 synchronized (sUidOwnerMap) {
546 sUidOwnerMap.forEach((uid, config) -> {
547 // config could be null if there is a concurrent entry deletion.
548 // http://b/220084230.
549 if (config != null
550 && !uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
551 uidSetToRemoveRule.add((int) uid.val);
552 }
553 });
554
555 for (final int uid : uidSetToRemoveRule) {
556 removeRule(uid, match, "replaceUidChain");
557 }
558 for (final int uid : uids) {
559 addRule(uid, match, "replaceUidChain");
560 }
561 }
562 } catch (ErrnoException | ServiceSpecificException e) {
563 Log.e(TAG, "replaceUidChain failed: " + e);
564 }
565 } else {
566 final int err;
567 switch (chain) {
568 case FIREWALL_CHAIN_DOZABLE:
569 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
570 break;
571 case FIREWALL_CHAIN_STANDBY:
572 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
573 break;
574 case FIREWALL_CHAIN_POWERSAVE:
575 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
576 break;
577 case FIREWALL_CHAIN_RESTRICTED:
578 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
579 break;
580 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
581 err = native_replaceUidChain(
582 "fw_low_power_standby", true /* isAllowList */, uids);
583 break;
584 case FIREWALL_CHAIN_OEM_DENY_1:
585 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
586 break;
587 case FIREWALL_CHAIN_OEM_DENY_2:
588 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
589 break;
590 case FIREWALL_CHAIN_OEM_DENY_3:
591 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
592 break;
593 default:
594 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
595 + chain);
596 }
597 if (err != 0) {
598 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
599 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800600 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800601 }
602
Ken Chenf5f51332022-01-28 10:08:16 +0800603 /**
604 * Set firewall rule for uid
605 *
606 * @param childChain target chain
607 * @param uid uid to allow/deny
608 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800609 * @throws ServiceSpecificException in case of failure, with an error code indicating the
610 * cause of the failure.
611 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900612 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000613 throwIfPreT("setUidRule is not available on pre-T devices");
614
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000615 if (sEnableJavaBpfMap) {
616 final long match = getMatchByFirewallChain(childChain);
617 final boolean isAllowList = isFirewallAllowList(childChain);
618 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
619 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000620
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000621 if (add) {
622 addRule(uid, match, "setUidRule");
623 } else {
624 removeRule(uid, match, "setUidRule");
625 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000626 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000627 final int err = native_setUidRule(childChain, uid, firewallRule);
628 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000629 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800630 }
631
632 /**
633 * Add ingress interface filtering rules to a list of UIDs
634 *
635 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
636 * allowed interface and loopback to be sent to the list of UIDs.
637 *
638 * Calling this method on one or more UIDs with an existing filtering rule but a different
639 * interface name will result in the filtering rule being updated to allow the new interface
640 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
641 *
642 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800643 * be received.
644 * @param uids an array of UIDs which the filtering rules will be set
645 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800646 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800647 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800648 */
Ken Chenf5f51332022-01-28 10:08:16 +0800649 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000650 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800651 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800652 return;
653 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000654
655 if (sEnableJavaBpfMap) {
656 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
657 // ifIndex is set to 0.
658 final int ifIndex;
659 if (ifName == null) {
660 ifIndex = 0;
661 } else {
662 ifIndex = mDeps.getIfIndex(ifName);
663 if (ifIndex == 0) {
664 throw new ServiceSpecificException(ENODEV,
665 "Failed to get index of interface " + ifName);
666 }
667 }
668 for (final int uid : uids) {
669 try {
670 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
671 } catch (ServiceSpecificException e) {
672 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
673 }
674 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000675 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000676 final int err = native_addUidInterfaceRules(ifName, uids);
677 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000678 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800679 }
680
681 /**
682 * Remove ingress interface filtering rules from a list of UIDs
683 *
684 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
685 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
686 *
687 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800688 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800689 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800690 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800691 */
Ken Chenf5f51332022-01-28 10:08:16 +0800692 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000693 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800694 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800695 return;
696 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000697
698 if (sEnableJavaBpfMap) {
699 for (final int uid : uids) {
700 try {
701 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
702 } catch (ServiceSpecificException e) {
703 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
704 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000705 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000706 } else {
707 final int err = native_removeUidInterfaceRules(uids);
708 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000709 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800710 }
711
Ken Chenf5f51332022-01-28 10:08:16 +0800712 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000713 * Update lockdown rule for uid
714 *
715 * @param uid target uid to add/remove the rule
716 * @param add {@code true} to add the rule, {@code false} to remove the rule.
717 * @throws ServiceSpecificException in case of failure, with an error code indicating the
718 * cause of the failure.
719 */
720 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000721 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000722
723 if (sEnableJavaBpfMap) {
724 if (add) {
725 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
726 } else {
727 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
728 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000729 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000730 final int err = native_updateUidLockdownRule(uid, add);
731 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000732 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000733 }
734
735 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800736 * Request netd to change the current active network stats map.
737 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000738 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800739 * @throws ServiceSpecificException in case of failure, with an error code indicating the
740 * cause of the failure.
741 */
markchien49e944c2022-03-01 15:22:20 +0800742 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000743 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
744
745 if (sEnableJavaBpfMap) {
746 try {
747 synchronized (sCurrentStatsMapConfigLock) {
748 final long config = sConfigurationMap.getValue(
749 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
750 final long newConfig = (config == STATS_SELECT_MAP_A)
751 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
752 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
753 new U32(newConfig));
754 }
755 } catch (ErrnoException e) {
756 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
757 }
758
759 // After changing the config, it's needed to make sure all the current running eBPF
760 // programs are finished and all the CPUs are aware of this config change before the old
761 // map is modified. So special hack is needed here to wait for the kernel to do a
762 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
763 // be available to all cores and the next eBPF programs triggered inside the kernel will
764 // use the new map configuration. So once this function returns it is safe to modify the
765 // old stats map without concerning about race between the kernel and userspace.
766 final int err = mDeps.synchronizeKernelRCU();
767 maybeThrow(err, "synchronizeKernelRCU failed");
768 } else {
769 final int err = native_swapActiveStatsMap();
770 maybeThrow(err, "Unable to swap active stats map");
771 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800772 }
773
Ken Chenf5f51332022-01-28 10:08:16 +0800774 /**
775 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
776 * specified. Or remove all permissions from the uids.
777 *
778 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
779 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
780 * revoke all permissions for the uids.
781 * @param uids uid of users to grant permission
782 * @throws RemoteException when netd has crashed.
783 */
784 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000785 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800786 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800787 return;
788 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000789
790 if (sEnableJavaBpfMap) {
791 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
792 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
793 for (final int uid : uids) {
794 try {
795 sUidPermissionMap.deleteEntry(new U32(uid));
796 } catch (ErrnoException e) {
797 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
798 }
799 }
800 return;
801 }
802
803 for (final int uid : uids) {
804 try {
805 sUidPermissionMap.updateEntry(new U32(uid), new U8((short) permissions));
806 } catch (ErrnoException e) {
807 Log.e(TAG, "Failed to set permission "
808 + permissions + " to uid " + uid + ": " + e);
809 }
810 }
811 } else {
812 native_setPermissionForUids(permissions, uids);
813 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800814 }
815
Ken Chene6d511f2022-01-25 11:10:42 +0800816 /**
817 * Dump BPF maps
818 *
819 * @param fd file descriptor to output
820 * @throws IOException when file descriptor is invalid.
821 * @throws ServiceSpecificException when the method is called on an unsupported device.
822 */
823 public void dump(final FileDescriptor fd, boolean verbose)
824 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000825 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +0800826 throw new ServiceSpecificException(
827 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
828 + " devices, use dumpsys netd trafficcontroller instead.");
829 }
830 native_dump(fd, verbose);
831 }
832
Wayne Ma790c83e2022-01-13 10:35:05 +0800833 private static native void native_init();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800834 private native int native_addNaughtyApp(int uid);
835 private native int native_removeNaughtyApp(int uid);
836 private native int native_addNiceApp(int uid);
837 private native int native_removeNiceApp(int uid);
Motomu Utsumi114cd9c2022-08-01 02:08:35 +0000838 private native int native_setChildChain(int childChain, boolean enable);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800839 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
840 private native int native_setUidRule(int childChain, int uid, int firewallRule);
841 private native int native_addUidInterfaceRules(String ifName, int[] uids);
842 private native int native_removeUidInterfaceRules(int[] uids);
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000843 private native int native_updateUidLockdownRule(int uid, boolean add);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800844 private native int native_swapActiveStatsMap();
Wayne Ma2fde98c2022-01-17 18:04:05 +0800845 private native void native_setPermissionForUids(int permissions, int[] uids);
Ken Chene6d511f2022-01-25 11:10:42 +0800846 private native void native_dump(FileDescriptor fd, boolean verbose);
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000847 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800848}