blob: 69b6486a792809da349cd0b5c22604ad9d07eafe [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 Utsumi166f9662022-09-01 10:35:29 +090036import static com.android.server.ConnectivityStatsLog.NETWORK_BPF_MAP_INFO;
37
38import android.app.StatsManager;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000039import android.content.Context;
Wayne Ma2fde98c2022-01-17 18:04:05 +080040import android.net.INetd;
41import android.os.RemoteException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080042import android.os.ServiceSpecificException;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000043import android.provider.DeviceConfig;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000044import android.system.ErrnoException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080045import android.system.Os;
Motomu Utsumi1a477b02022-08-23 15:14:56 +090046import android.util.ArraySet;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080047import android.util.Log;
Motomu Utsumi166f9662022-09-01 10:35:29 +090048import android.util.StatsEvent;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080049
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000050import com.android.internal.annotations.VisibleForTesting;
Motomu Utsumi166f9662022-09-01 10:35:29 +090051import com.android.modules.utils.BackgroundThread;
Ken Chenf5f51332022-01-28 10:08:16 +080052import com.android.modules.utils.build.SdkLevel;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000053import com.android.net.module.util.BpfMap;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000054import com.android.net.module.util.DeviceConfigUtils;
Motomu Utsumi73599a52022-08-24 11:59:21 +090055import com.android.net.module.util.IBpfMap;
Motomu Utsumi166f9662022-09-01 10:35:29 +090056import com.android.net.module.util.Struct;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000057import com.android.net.module.util.Struct.U32;
Motomu Utsumi65271202022-07-05 08:21:41 +000058import com.android.net.module.util.Struct.U8;
Motomu Utsumib9548862022-09-06 16:30:05 +090059import com.android.net.module.util.bpf.CookieTagMapKey;
60import com.android.net.module.util.bpf.CookieTagMapValue;
Ken Chenf5f51332022-01-28 10:08:16 +080061
Ken Chene6d511f2022-01-25 11:10:42 +080062import java.io.FileDescriptor;
63import java.io.IOException;
Motomu Utsumi166f9662022-09-01 10:35:29 +090064import java.util.List;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000065import java.util.Set;
Ken Chene6d511f2022-01-25 11:10:42 +080066
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080067/**
68 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
69 *
70 * {@hide}
71 */
72public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000073 private static final boolean PRE_T = !SdkLevel.isAtLeastT();
74 static {
75 if (!PRE_T) {
76 System.loadLibrary("service-connectivity");
77 }
78 }
79
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080080 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +080081 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000082 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +080083 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +080084 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080085
Motomu Utsumif688eeb2022-07-22 03:47:35 +000086 private static Boolean sEnableJavaBpfMap = null;
87 private static final String BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP =
88 "bpf_net_maps_enable_java_bpf_map";
89
Motomu Utsumi18b287d2022-06-19 10:45:30 +000090 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
91 // This entry is not accessed by others.
92 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
93 private static final Object sUidRulesConfigBpfMapLock = new Object();
94
Motomu Utsumi7abeaa42022-07-20 07:54:18 +000095 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
96 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
97 // BpfNetMaps is an only writer of this entry.
98 private static final Object sCurrentStatsMapConfigLock = new Object();
99
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000100 private static final String CONFIGURATION_MAP_PATH =
101 "/sys/fs/bpf/netd_shared/map_netd_configuration_map";
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000102 private static final String UID_OWNER_MAP_PATH =
103 "/sys/fs/bpf/netd_shared/map_netd_uid_owner_map";
Motomu Utsumi65271202022-07-05 08:21:41 +0000104 private static final String UID_PERMISSION_MAP_PATH =
105 "/sys/fs/bpf/netd_shared/map_netd_uid_permission_map";
Motomu Utsumib9548862022-09-06 16:30:05 +0900106 private static final String COOKIE_TAG_MAP_PATH =
107 "/sys/fs/bpf/netd_shared/map_netd_cookie_tag_map";
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000108 private static final U32 UID_RULES_CONFIGURATION_KEY = new U32(0);
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000109 private static final U32 CURRENT_STATS_MAP_CONFIGURATION_KEY = new U32(1);
110 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
111 private static final long STATS_SELECT_MAP_A = 0;
112 private static final long STATS_SELECT_MAP_B = 1;
113
Motomu Utsumi73599a52022-08-24 11:59:21 +0900114 private static IBpfMap<U32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000115 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
Motomu Utsumi73599a52022-08-24 11:59:21 +0900116 private static IBpfMap<U32, UidOwnerValue> sUidOwnerMap = null;
117 private static IBpfMap<U32, U8> sUidPermissionMap = null;
Motomu Utsumib9548862022-09-06 16:30:05 +0900118 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> sCookieTagMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000119
120 // LINT.IfChange(match_type)
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000121 @VisibleForTesting public static final long NO_MATCH = 0;
122 @VisibleForTesting public static final long HAPPY_BOX_MATCH = (1 << 0);
123 @VisibleForTesting public static final long PENALTY_BOX_MATCH = (1 << 1);
124 @VisibleForTesting public static final long DOZABLE_MATCH = (1 << 2);
125 @VisibleForTesting public static final long STANDBY_MATCH = (1 << 3);
126 @VisibleForTesting public static final long POWERSAVE_MATCH = (1 << 4);
127 @VisibleForTesting public static final long RESTRICTED_MATCH = (1 << 5);
128 @VisibleForTesting public static final long LOW_POWER_STANDBY_MATCH = (1 << 6);
129 @VisibleForTesting public static final long IIF_MATCH = (1 << 7);
130 @VisibleForTesting public static final long LOCKDOWN_VPN_MATCH = (1 << 8);
131 @VisibleForTesting public static final long OEM_DENY_1_MATCH = (1 << 9);
132 @VisibleForTesting public static final long OEM_DENY_2_MATCH = (1 << 10);
133 @VisibleForTesting public static final long OEM_DENY_3_MATCH = (1 << 11);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000134 // LINT.ThenChange(packages/modules/Connectivity/bpf_progs/bpf_shared.h)
135
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000136 /**
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000137 * Set sEnableJavaBpfMap for test.
138 */
139 @VisibleForTesting
140 public static void setEnableJavaBpfMapForTest(boolean enable) {
141 sEnableJavaBpfMap = enable;
142 }
143
144 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000145 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000146 */
147 @VisibleForTesting
Motomu Utsumi73599a52022-08-24 11:59:21 +0900148 public static void setConfigurationMapForTest(IBpfMap<U32, U32> configurationMap) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000149 sConfigurationMap = configurationMap;
150 }
151
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000152 /**
153 * Set uidOwnerMap for test.
154 */
155 @VisibleForTesting
Motomu Utsumi73599a52022-08-24 11:59:21 +0900156 public static void setUidOwnerMapForTest(IBpfMap<U32, UidOwnerValue> uidOwnerMap) {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000157 sUidOwnerMap = uidOwnerMap;
158 }
159
Motomu Utsumi65271202022-07-05 08:21:41 +0000160 /**
161 * Set uidPermissionMap for test.
162 */
163 @VisibleForTesting
Motomu Utsumi73599a52022-08-24 11:59:21 +0900164 public static void setUidPermissionMapForTest(IBpfMap<U32, U8> uidPermissionMap) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000165 sUidPermissionMap = uidPermissionMap;
166 }
167
Motomu Utsumib9548862022-09-06 16:30:05 +0900168 /**
169 * Set cookieTagMap for test.
170 */
171 @VisibleForTesting
172 public static void setCookieTagMapForTest(
173 IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap) {
174 sCookieTagMap = cookieTagMap;
175 }
176
Motomu Utsumi73599a52022-08-24 11:59:21 +0900177 private static IBpfMap<U32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000178 try {
179 return new BpfMap<>(
180 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, U32.class);
181 } catch (ErrnoException e) {
182 throw new IllegalStateException("Cannot open netd configuration map", e);
183 }
184 }
185
Motomu Utsumi73599a52022-08-24 11:59:21 +0900186 private static IBpfMap<U32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000187 try {
188 return new BpfMap<>(
189 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, UidOwnerValue.class);
190 } catch (ErrnoException e) {
191 throw new IllegalStateException("Cannot open uid owner map", e);
192 }
193 }
194
Motomu Utsumi73599a52022-08-24 11:59:21 +0900195 private static IBpfMap<U32, U8> getUidPermissionMap() {
Motomu Utsumi65271202022-07-05 08:21:41 +0000196 try {
197 return new BpfMap<>(
198 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, U8.class);
199 } catch (ErrnoException e) {
200 throw new IllegalStateException("Cannot open uid permission map", e);
201 }
202 }
203
Motomu Utsumib9548862022-09-06 16:30:05 +0900204 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
205 try {
206 return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,
207 CookieTagMapKey.class, CookieTagMapValue.class);
208 } catch (ErrnoException e) {
209 throw new IllegalStateException("Cannot open cookie tag map", e);
210 }
211 }
212
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000213 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000214 if (sConfigurationMap == null) {
215 sConfigurationMap = getConfigurationMap();
216 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000217 try {
218 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
219 new U32(UID_RULES_DEFAULT_CONFIGURATION));
220 } catch (ErrnoException e) {
221 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
222 }
223 try {
224 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
225 new U32(STATS_SELECT_MAP_A));
226 } catch (ErrnoException e) {
227 throw new IllegalStateException("Failed to initialize current stats configuration", e);
228 }
229
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000230 if (sUidOwnerMap == null) {
231 sUidOwnerMap = getUidOwnerMap();
232 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000233 try {
234 sUidOwnerMap.clear();
235 } catch (ErrnoException e) {
236 throw new IllegalStateException("Failed to initialize uid owner map", e);
237 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000238
239 if (sUidPermissionMap == null) {
240 sUidPermissionMap = getUidPermissionMap();
241 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900242
243 if (sCookieTagMap == null) {
244 sCookieTagMap = getCookieTagMap();
245 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000246 }
247
Ken Chenf5f51332022-01-28 10:08:16 +0800248 /**
249 * Initializes the class if it is not already initialized. This method will open maps but not
250 * cause any other effects. This method may be called multiple times on any thread.
251 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000252 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800253 if (sInitialized) return;
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000254 if (sEnableJavaBpfMap == null) {
255 sEnableJavaBpfMap = DeviceConfigUtils.isFeatureEnabled(context,
256 DeviceConfig.NAMESPACE_TETHERING, BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP,
257 SdkLevel.isAtLeastU() /* defaultValue */);
258 }
259 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
260
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000261 initBpfMaps();
Motomu Utsumi305975f2022-06-27 09:24:32 +0000262 native_init();
Ken Chenf5f51332022-01-28 10:08:16 +0800263 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800264 }
265
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000266 /**
267 * Dependencies of BpfNetMaps, for injection in tests.
268 */
269 @VisibleForTesting
270 public static class Dependencies {
271 /**
272 * Get interface index.
273 */
274 public int getIfIndex(final String ifName) {
275 return Os.if_nametoindex(ifName);
276 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000277
278 /**
279 * Call synchronize_rcu()
280 */
281 public int synchronizeKernelRCU() {
282 return native_synchronizeKernelRCU();
283 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900284
285 /**
286 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
287 */
288 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
289 final int uidPermissionMapSize) {
290 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
291 uidOwnerMapSize, uidPermissionMapSize);
292 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000293 }
294
markchien49e944c2022-03-01 15:22:20 +0800295 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000296 public BpfNetMaps(final Context context) {
297 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800298
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000299 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800300 }
301
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000302 public BpfNetMaps(final Context context, final INetd netd) {
303 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000304 }
305
306 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000307 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000308 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000309 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000310 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800311 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000312 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800313 }
314
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000315 /**
316 * Get corresponding match from firewall chain.
317 */
318 @VisibleForTesting
319 public long getMatchByFirewallChain(final int chain) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000320 switch (chain) {
321 case FIREWALL_CHAIN_DOZABLE:
322 return DOZABLE_MATCH;
323 case FIREWALL_CHAIN_STANDBY:
324 return STANDBY_MATCH;
325 case FIREWALL_CHAIN_POWERSAVE:
326 return POWERSAVE_MATCH;
327 case FIREWALL_CHAIN_RESTRICTED:
328 return RESTRICTED_MATCH;
329 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
330 return LOW_POWER_STANDBY_MATCH;
331 case FIREWALL_CHAIN_OEM_DENY_1:
332 return OEM_DENY_1_MATCH;
333 case FIREWALL_CHAIN_OEM_DENY_2:
334 return OEM_DENY_2_MATCH;
335 case FIREWALL_CHAIN_OEM_DENY_3:
336 return OEM_DENY_3_MATCH;
337 default:
338 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000339 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000340 }
341
342 /**
343 * Get if the chain is allow list or not.
344 *
345 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
346 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
347 */
348 @VisibleForTesting
349 public boolean isFirewallAllowList(final int chain) {
350 switch (chain) {
351 case FIREWALL_CHAIN_DOZABLE:
352 case FIREWALL_CHAIN_POWERSAVE:
353 case FIREWALL_CHAIN_RESTRICTED:
354 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
355 return true;
356 case FIREWALL_CHAIN_STANDBY:
357 case FIREWALL_CHAIN_OEM_DENY_1:
358 case FIREWALL_CHAIN_OEM_DENY_2:
359 case FIREWALL_CHAIN_OEM_DENY_3:
360 return false;
361 default:
362 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
363 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000364 }
365
Ken Chenf5f51332022-01-28 10:08:16 +0800366 private void maybeThrow(final int err, final String msg) {
367 if (err != 0) {
368 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
369 }
370 }
371
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000372 private void throwIfPreT(final String msg) {
373 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000374 throw new UnsupportedOperationException(msg);
375 }
376 }
377
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000378 private void removeRule(final int uid, final long match, final String caller) {
379 try {
380 synchronized (sUidOwnerMap) {
381 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
382
383 if (oldMatch == null) {
384 throw new ServiceSpecificException(ENOENT,
385 "sUidOwnerMap does not have entry for uid: " + uid);
386 }
387
388 final UidOwnerValue newMatch = new UidOwnerValue(
389 (match == IIF_MATCH) ? 0 : oldMatch.iif,
390 oldMatch.rule & ~match
391 );
392
393 if (newMatch.rule == 0) {
394 sUidOwnerMap.deleteEntry(new U32(uid));
395 } else {
396 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
397 }
398 }
399 } catch (ErrnoException e) {
400 throw new ServiceSpecificException(e.errno,
401 caller + " failed to remove rule: " + Os.strerror(e.errno));
402 }
403 }
404
Motomu Utsumi389278e2022-06-28 07:05:05 +0000405 private void addRule(final int uid, final long match, final long iif, final String caller) {
406 if (match != IIF_MATCH && iif != 0) {
407 throw new ServiceSpecificException(EINVAL,
408 "Non-interface match must have zero interface index");
409 }
410
411 try {
412 synchronized (sUidOwnerMap) {
413 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
414
415 final UidOwnerValue newMatch;
416 if (oldMatch != null) {
417 newMatch = new UidOwnerValue(
418 (match == IIF_MATCH) ? iif : oldMatch.iif,
419 oldMatch.rule | match
420 );
421 } else {
422 newMatch = new UidOwnerValue(
423 iif,
424 match
425 );
426 }
427 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
428 }
429 } catch (ErrnoException e) {
430 throw new ServiceSpecificException(e.errno,
431 caller + " failed to add rule: " + Os.strerror(e.errno));
432 }
433 }
434
435 private void addRule(final int uid, final long match, final String caller) {
436 addRule(uid, match, 0 /* iif */, caller);
437 }
438
Ken Chenf5f51332022-01-28 10:08:16 +0800439 /**
440 * Add naughty 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 addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000447 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000448
449 if (sEnableJavaBpfMap) {
450 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
451 } else {
452 final int err = native_addNaughtyApp(uid);
453 maybeThrow(err, "Unable to add naughty app");
454 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800455 }
456
Ken Chenf5f51332022-01-28 10:08:16 +0800457 /**
458 * Remove naughty app bandwidth rule for specific app
459 *
460 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800461 * @throws ServiceSpecificException in case of failure, with an error code indicating the
462 * cause of the failure.
463 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900464 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000465 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000466
467 if (sEnableJavaBpfMap) {
468 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
469 } else {
470 final int err = native_removeNaughtyApp(uid);
471 maybeThrow(err, "Unable to remove naughty app");
472 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800473 }
474
Ken Chenf5f51332022-01-28 10:08:16 +0800475 /**
476 * Add nice app bandwidth rule for specific app
477 *
478 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800479 * @throws ServiceSpecificException in case of failure, with an error code indicating the
480 * cause of the failure.
481 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900482 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000483 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000484
485 if (sEnableJavaBpfMap) {
486 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
487 } else {
488 final int err = native_addNiceApp(uid);
489 maybeThrow(err, "Unable to add nice app");
490 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800491 }
492
Ken Chenf5f51332022-01-28 10:08:16 +0800493 /**
494 * Remove nice app bandwidth rule for specific app
495 *
496 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800497 * @throws ServiceSpecificException in case of failure, with an error code indicating the
498 * cause of the failure.
499 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900500 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000501 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000502
503 if (sEnableJavaBpfMap) {
504 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
505 } else {
506 final int err = native_removeNiceApp(uid);
507 maybeThrow(err, "Unable to remove nice app");
508 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800509 }
510
Ken Chenf5f51332022-01-28 10:08:16 +0800511 /**
512 * Set target firewall child chain
513 *
514 * @param childChain target chain to enable
515 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000516 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800517 * @throws ServiceSpecificException in case of failure, with an error code indicating the
518 * cause of the failure.
519 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900520 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000521 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000522
Motomu Utsumie057dd42022-08-03 01:23:49 +0000523 if (sEnableJavaBpfMap) {
524 final long match = getMatchByFirewallChain(childChain);
525 try {
526 synchronized (sUidRulesConfigBpfMapLock) {
527 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
528 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
529 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
530 }
531 } catch (ErrnoException e) {
532 throw new ServiceSpecificException(e.errno,
533 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000534 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000535 } else {
536 final int err = native_setChildChain(childChain, enable);
537 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000538 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800539 }
540
541 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000542 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000543 *
544 * @param childChain target chain
545 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
546 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000547 * @throws ServiceSpecificException in case of failure, with an error code indicating the
548 * cause of the failure.
549 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000550 public boolean isChainEnabled(final int childChain) {
551 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000552
553 final long match = getMatchByFirewallChain(childChain);
554 try {
555 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000556 return (config.val & match) != 0;
557 } catch (ErrnoException e) {
558 throw new ServiceSpecificException(e.errno,
559 "Unable to get firewall chain status: " + Os.strerror(e.errno));
560 }
561 }
562
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900563 private Set<Integer> asSet(final int[] uids) {
564 final Set<Integer> uidSet = new ArraySet<>();
565 for (final int uid: uids) {
566 uidSet.add(uid);
567 }
568 return uidSet;
569 }
570
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000571 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800572 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000573 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800574 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000575 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800576 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000577 * @throws UnsupportedOperationException if called on pre-T devices.
578 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800579 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000580 public void replaceUidChain(final int chain, final int[] uids) {
581 throwIfPreT("replaceUidChain is not available on pre-T devices");
582
Motomu Utsumic7c16852022-08-03 06:51:41 +0000583 if (sEnableJavaBpfMap) {
584 final long match;
585 try {
586 match = getMatchByFirewallChain(chain);
587 } catch (ServiceSpecificException e) {
588 // Throws IllegalArgumentException to keep the behavior of
589 // ConnectivityManager#replaceFirewallChain API
590 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000591 }
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900592 final Set<Integer> uidSet = asSet(uids);
593 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
Motomu Utsumic7c16852022-08-03 06:51:41 +0000594 try {
595 synchronized (sUidOwnerMap) {
596 sUidOwnerMap.forEach((uid, config) -> {
597 // config could be null if there is a concurrent entry deletion.
Motomu Utsumi8e420ea2022-08-24 18:03:30 +0900598 // http://b/220084230. But sUidOwnerMap update must be done while holding a
599 // lock, so this should not happen.
600 if (config == null) {
601 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
602 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
Motomu Utsumic7c16852022-08-03 06:51:41 +0000603 uidSetToRemoveRule.add((int) uid.val);
604 }
605 });
606
607 for (final int uid : uidSetToRemoveRule) {
608 removeRule(uid, match, "replaceUidChain");
609 }
610 for (final int uid : uids) {
611 addRule(uid, match, "replaceUidChain");
612 }
613 }
614 } catch (ErrnoException | ServiceSpecificException e) {
615 Log.e(TAG, "replaceUidChain failed: " + e);
616 }
617 } else {
618 final int err;
619 switch (chain) {
620 case FIREWALL_CHAIN_DOZABLE:
621 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
622 break;
623 case FIREWALL_CHAIN_STANDBY:
624 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
625 break;
626 case FIREWALL_CHAIN_POWERSAVE:
627 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
628 break;
629 case FIREWALL_CHAIN_RESTRICTED:
630 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
631 break;
632 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
633 err = native_replaceUidChain(
634 "fw_low_power_standby", true /* isAllowList */, uids);
635 break;
636 case FIREWALL_CHAIN_OEM_DENY_1:
637 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
638 break;
639 case FIREWALL_CHAIN_OEM_DENY_2:
640 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
641 break;
642 case FIREWALL_CHAIN_OEM_DENY_3:
643 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
644 break;
645 default:
646 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
647 + chain);
648 }
649 if (err != 0) {
650 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
651 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800652 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800653 }
654
Ken Chenf5f51332022-01-28 10:08:16 +0800655 /**
656 * Set firewall rule for uid
657 *
658 * @param childChain target chain
659 * @param uid uid to allow/deny
660 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800661 * @throws ServiceSpecificException in case of failure, with an error code indicating the
662 * cause of the failure.
663 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900664 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000665 throwIfPreT("setUidRule is not available on pre-T devices");
666
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000667 if (sEnableJavaBpfMap) {
668 final long match = getMatchByFirewallChain(childChain);
669 final boolean isAllowList = isFirewallAllowList(childChain);
670 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
671 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000672
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000673 if (add) {
674 addRule(uid, match, "setUidRule");
675 } else {
676 removeRule(uid, match, "setUidRule");
677 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000678 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000679 final int err = native_setUidRule(childChain, uid, firewallRule);
680 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000681 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800682 }
683
684 /**
685 * Add ingress interface filtering rules to a list of UIDs
686 *
687 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
688 * allowed interface and loopback to be sent to the list of UIDs.
689 *
690 * Calling this method on one or more UIDs with an existing filtering rule but a different
691 * interface name will result in the filtering rule being updated to allow the new interface
692 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
693 *
694 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800695 * be received.
696 * @param uids an array of UIDs which the filtering rules will be set
697 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800698 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800699 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800700 */
Ken Chenf5f51332022-01-28 10:08:16 +0800701 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000702 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800703 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800704 return;
705 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000706
707 if (sEnableJavaBpfMap) {
708 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
709 // ifIndex is set to 0.
710 final int ifIndex;
711 if (ifName == null) {
712 ifIndex = 0;
713 } else {
714 ifIndex = mDeps.getIfIndex(ifName);
715 if (ifIndex == 0) {
716 throw new ServiceSpecificException(ENODEV,
717 "Failed to get index of interface " + ifName);
718 }
719 }
720 for (final int uid : uids) {
721 try {
722 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
723 } catch (ServiceSpecificException e) {
724 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
725 }
726 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000727 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000728 final int err = native_addUidInterfaceRules(ifName, uids);
729 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000730 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800731 }
732
733 /**
734 * Remove ingress interface filtering rules from a list of UIDs
735 *
736 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
737 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
738 *
739 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800740 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800741 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800742 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800743 */
Ken Chenf5f51332022-01-28 10:08:16 +0800744 public void removeUidInterfaceRules(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.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800747 return;
748 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000749
750 if (sEnableJavaBpfMap) {
751 for (final int uid : uids) {
752 try {
753 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
754 } catch (ServiceSpecificException e) {
755 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
756 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000757 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000758 } else {
759 final int err = native_removeUidInterfaceRules(uids);
760 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000761 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800762 }
763
Ken Chenf5f51332022-01-28 10:08:16 +0800764 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000765 * Update lockdown rule for uid
766 *
767 * @param uid target uid to add/remove the rule
768 * @param add {@code true} to add the rule, {@code false} to remove the rule.
769 * @throws ServiceSpecificException in case of failure, with an error code indicating the
770 * cause of the failure.
771 */
772 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000773 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000774
775 if (sEnableJavaBpfMap) {
776 if (add) {
777 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
778 } else {
779 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
780 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000781 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000782 final int err = native_updateUidLockdownRule(uid, add);
783 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000784 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000785 }
786
787 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800788 * Request netd to change the current active network stats map.
789 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000790 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800791 * @throws ServiceSpecificException in case of failure, with an error code indicating the
792 * cause of the failure.
793 */
markchien49e944c2022-03-01 15:22:20 +0800794 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000795 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
796
797 if (sEnableJavaBpfMap) {
798 try {
799 synchronized (sCurrentStatsMapConfigLock) {
800 final long config = sConfigurationMap.getValue(
801 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
802 final long newConfig = (config == STATS_SELECT_MAP_A)
803 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
804 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
805 new U32(newConfig));
806 }
807 } catch (ErrnoException e) {
808 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
809 }
810
811 // After changing the config, it's needed to make sure all the current running eBPF
812 // programs are finished and all the CPUs are aware of this config change before the old
813 // map is modified. So special hack is needed here to wait for the kernel to do a
814 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
815 // be available to all cores and the next eBPF programs triggered inside the kernel will
816 // use the new map configuration. So once this function returns it is safe to modify the
817 // old stats map without concerning about race between the kernel and userspace.
818 final int err = mDeps.synchronizeKernelRCU();
819 maybeThrow(err, "synchronizeKernelRCU failed");
820 } else {
821 final int err = native_swapActiveStatsMap();
822 maybeThrow(err, "Unable to swap active stats map");
823 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800824 }
825
Ken Chenf5f51332022-01-28 10:08:16 +0800826 /**
827 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
828 * specified. Or remove all permissions from the uids.
829 *
830 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
831 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
832 * revoke all permissions for the uids.
833 * @param uids uid of users to grant permission
834 * @throws RemoteException when netd has crashed.
835 */
836 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000837 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800838 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800839 return;
840 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000841
842 if (sEnableJavaBpfMap) {
843 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
844 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
845 for (final int uid : uids) {
846 try {
847 sUidPermissionMap.deleteEntry(new U32(uid));
848 } catch (ErrnoException e) {
849 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
850 }
851 }
852 return;
853 }
854
855 for (final int uid : uids) {
856 try {
857 sUidPermissionMap.updateEntry(new U32(uid), new U8((short) permissions));
858 } catch (ErrnoException e) {
859 Log.e(TAG, "Failed to set permission "
860 + permissions + " to uid " + uid + ": " + e);
861 }
862 }
863 } else {
864 native_setPermissionForUids(permissions, uids);
865 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800866 }
867
Motomu Utsumi166f9662022-09-01 10:35:29 +0900868 /** Register callback for statsd to pull atom. */
869 public void setPullAtomCallback(final Context context) {
870 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
871
872 final StatsManager statsManager = context.getSystemService(StatsManager.class);
873 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
874 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
875 }
876
877 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
878 throws ErrnoException {
879 // forEach could restart iteration from the beginning if there is a concurrent entry
880 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
881 // So using Set to count the number of entry in the map.
882 Set<K> keySet = new ArraySet<>();
883 map.forEach((k, v) -> keySet.add(k));
884 return keySet.size();
885 }
886
887 /** Callback for StatsManager#setPullAtomCallback */
888 @VisibleForTesting
889 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
890 if (atomTag != NETWORK_BPF_MAP_INFO) {
891 Log.e(TAG, "Unexpected atom tag: " + atomTag);
892 return StatsManager.PULL_SKIP;
893 }
894
895 try {
896 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
897 getMapSize(sUidPermissionMap)));
898 } catch (ErrnoException e) {
899 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
900 return StatsManager.PULL_SKIP;
901 }
902 return StatsManager.PULL_SUCCESS;
903 }
904
Ken Chene6d511f2022-01-25 11:10:42 +0800905 /**
906 * Dump BPF maps
907 *
908 * @param fd file descriptor to output
909 * @throws IOException when file descriptor is invalid.
910 * @throws ServiceSpecificException when the method is called on an unsupported device.
911 */
912 public void dump(final FileDescriptor fd, boolean verbose)
913 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000914 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +0800915 throw new ServiceSpecificException(
916 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
917 + " devices, use dumpsys netd trafficcontroller instead.");
918 }
919 native_dump(fd, verbose);
920 }
921
Wayne Ma790c83e2022-01-13 10:35:05 +0800922 private static native void native_init();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800923 private native int native_addNaughtyApp(int uid);
924 private native int native_removeNaughtyApp(int uid);
925 private native int native_addNiceApp(int uid);
926 private native int native_removeNiceApp(int uid);
Motomu Utsumi114cd9c2022-08-01 02:08:35 +0000927 private native int native_setChildChain(int childChain, boolean enable);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800928 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
929 private native int native_setUidRule(int childChain, int uid, int firewallRule);
930 private native int native_addUidInterfaceRules(String ifName, int[] uids);
931 private native int native_removeUidInterfaceRules(int[] uids);
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000932 private native int native_updateUidLockdownRule(int uid, boolean add);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800933 private native int native_swapActiveStatsMap();
Wayne Ma2fde98c2022-01-17 18:04:05 +0800934 private native void native_setPermissionForUids(int permissions, int[] uids);
Ken Chene6d511f2022-01-25 11:10:42 +0800935 private native void native_dump(FileDescriptor fd, boolean verbose);
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000936 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800937}