blob: 14ab2a1075a59c7b4de8a9d6f9360bc9b0c4be41 [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
Junyu Lai29b7b632023-08-23 17:35:17 +080019import static android.net.BpfNetMapsConstants.CONFIGURATION_MAP_PATH;
20import static android.net.BpfNetMapsConstants.COOKIE_TAG_MAP_PATH;
21import static android.net.BpfNetMapsConstants.CURRENT_STATS_MAP_CONFIGURATION_KEY;
Ken Chen24330172023-10-20 13:02:14 +080022import static android.net.BpfNetMapsConstants.DATA_SAVER_DISABLED;
23import static android.net.BpfNetMapsConstants.DATA_SAVER_ENABLED;
24import static android.net.BpfNetMapsConstants.DATA_SAVER_ENABLED_KEY;
25import static android.net.BpfNetMapsConstants.DATA_SAVER_ENABLED_MAP_PATH;
Junyu Lai29b7b632023-08-23 17:35:17 +080026import static android.net.BpfNetMapsConstants.HAPPY_BOX_MATCH;
27import static android.net.BpfNetMapsConstants.IIF_MATCH;
28import static android.net.BpfNetMapsConstants.LOCKDOWN_VPN_MATCH;
29import static android.net.BpfNetMapsConstants.PENALTY_BOX_MATCH;
30import static android.net.BpfNetMapsConstants.UID_OWNER_MAP_PATH;
31import static android.net.BpfNetMapsConstants.UID_PERMISSION_MAP_PATH;
32import static android.net.BpfNetMapsConstants.UID_RULES_CONFIGURATION_KEY;
Junyu Lai626045a2023-08-28 18:49:44 +080033import static android.net.BpfNetMapsUtils.PRE_T;
Junyu Lai29b7b632023-08-23 17:35:17 +080034import static android.net.BpfNetMapsUtils.getMatchByFirewallChain;
Junyu Laie0031522023-08-29 18:32:57 +080035import static android.net.BpfNetMapsUtils.isFirewallAllowList;
Junyu Lai29b7b632023-08-23 17:35:17 +080036import static android.net.BpfNetMapsUtils.matchToString;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000037import static android.net.ConnectivityManager.FIREWALL_CHAIN_DOZABLE;
38import static android.net.ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY;
39import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1;
40import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2;
41import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3;
42import static android.net.ConnectivityManager.FIREWALL_CHAIN_POWERSAVE;
43import static android.net.ConnectivityManager.FIREWALL_CHAIN_RESTRICTED;
44import static android.net.ConnectivityManager.FIREWALL_CHAIN_STANDBY;
Motomu Utsumi40230be2022-07-05 03:27:35 +000045import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
46import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Motomu Utsumi65271202022-07-05 08:21:41 +000047import static android.net.INetd.PERMISSION_INTERNET;
Motomu Utsumi310850f2022-09-02 12:48:20 +090048import static android.net.INetd.PERMISSION_NONE;
Motomu Utsumi65271202022-07-05 08:21:41 +000049import static android.net.INetd.PERMISSION_UNINSTALLED;
Motomu Utsumi310850f2022-09-02 12:48:20 +090050import static android.net.INetd.PERMISSION_UPDATE_DEVICE_STATS;
Motomu Utsumi18b287d2022-06-19 10:45:30 +000051import static android.system.OsConstants.EINVAL;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000052import static android.system.OsConstants.ENODEV;
Motomu Utsumi60ed3be2022-06-24 10:38:57 +000053import static android.system.OsConstants.ENOENT;
Ken Chene6d511f2022-01-25 11:10:42 +080054import static android.system.OsConstants.EOPNOTSUPP;
55
Motomu Utsumi166f9662022-09-01 10:35:29 +090056import static com.android.server.ConnectivityStatsLog.NETWORK_BPF_MAP_INFO;
57
58import android.app.StatsManager;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000059import android.content.Context;
Junyu Lai626045a2023-08-28 18:49:44 +080060import android.net.BpfNetMapsReader;
Wayne Ma2fde98c2022-01-17 18:04:05 +080061import android.net.INetd;
Junyu Lai626045a2023-08-28 18:49:44 +080062import android.net.UidOwnerValue;
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +000063import android.os.Build;
Wayne Ma2fde98c2022-01-17 18:04:05 +080064import android.os.RemoteException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080065import android.os.ServiceSpecificException;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000066import android.system.ErrnoException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080067import android.system.Os;
Motomu Utsumi1a477b02022-08-23 15:14:56 +090068import android.util.ArraySet;
Motomu Utsumi310850f2022-09-02 12:48:20 +090069import android.util.IndentingPrintWriter;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080070import android.util.Log;
Motomu Utsumi310850f2022-09-02 12:48:20 +090071import android.util.Pair;
Motomu Utsumi166f9662022-09-01 10:35:29 +090072import android.util.StatsEvent;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080073
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +000074import androidx.annotation.RequiresApi;
75
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000076import com.android.internal.annotations.VisibleForTesting;
Motomu Utsumi166f9662022-09-01 10:35:29 +090077import com.android.modules.utils.BackgroundThread;
Ken Chenf5f51332022-01-28 10:08:16 +080078import com.android.modules.utils.build.SdkLevel;
Motomu Utsumi310850f2022-09-02 12:48:20 +090079import com.android.net.module.util.BpfDump;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000080import com.android.net.module.util.BpfMap;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000081import com.android.net.module.util.DeviceConfigUtils;
Motomu Utsumi73599a52022-08-24 11:59:21 +090082import com.android.net.module.util.IBpfMap;
Motomu Utsumi166f9662022-09-01 10:35:29 +090083import com.android.net.module.util.Struct;
Maciej Żenczykowski785793f2022-09-17 02:35:20 +000084import com.android.net.module.util.Struct.S32;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000085import com.android.net.module.util.Struct.U32;
Motomu Utsumi65271202022-07-05 08:21:41 +000086import com.android.net.module.util.Struct.U8;
Motomu Utsumib9548862022-09-06 16:30:05 +090087import com.android.net.module.util.bpf.CookieTagMapKey;
88import com.android.net.module.util.bpf.CookieTagMapValue;
Ken Chenf5f51332022-01-28 10:08:16 +080089
Ken Chene6d511f2022-01-25 11:10:42 +080090import java.io.FileDescriptor;
91import java.io.IOException;
Motomu Utsumi310850f2022-09-02 12:48:20 +090092import java.util.Arrays;
Motomu Utsumi166f9662022-09-01 10:35:29 +090093import java.util.List;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000094import java.util.Set;
Motomu Utsumi310850f2022-09-02 12:48:20 +090095import java.util.StringJoiner;
Ken Chene6d511f2022-01-25 11:10:42 +080096
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080097/**
98 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
99 *
100 * {@hide}
101 */
102public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000103 static {
104 if (!PRE_T) {
105 System.loadLibrary("service-connectivity");
106 }
107 }
108
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800109 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +0800110 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000111 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +0800112 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +0800113 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800114
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000115 private static Boolean sEnableJavaBpfMap = null;
Motomu Utsumi7628ea32023-08-14 11:09:02 +0900116 private static final String BPF_NET_MAPS_FORCE_DISABLE_JAVA_BPF_MAP =
117 "bpf_net_maps_force_disable_java_bpf_map";
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000118
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000119 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
120 // This entry is not accessed by others.
121 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
122 private static final Object sUidRulesConfigBpfMapLock = new Object();
123
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000124 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
125 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
126 // BpfNetMaps is an only writer of this entry.
127 private static final Object sCurrentStatsMapConfigLock = new Object();
128
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000129 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
130 private static final long STATS_SELECT_MAP_A = 0;
131 private static final long STATS_SELECT_MAP_B = 1;
132
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000133 private static IBpfMap<S32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000134 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000135 private static IBpfMap<S32, UidOwnerValue> sUidOwnerMap = null;
136 private static IBpfMap<S32, U8> sUidPermissionMap = null;
Motomu Utsumib9548862022-09-06 16:30:05 +0900137 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> sCookieTagMap = null;
Ken Chen24330172023-10-20 13:02:14 +0800138 // TODO: Add BOOL class and replace U8?
139 private static IBpfMap<S32, U8> sDataSaverEnabledMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000140
Motomu Utsumi310850f2022-09-02 12:48:20 +0900141 private static final List<Pair<Integer, String>> PERMISSION_LIST = Arrays.asList(
142 Pair.create(PERMISSION_INTERNET, "PERMISSION_INTERNET"),
143 Pair.create(PERMISSION_UPDATE_DEVICE_STATS, "PERMISSION_UPDATE_DEVICE_STATS")
144 );
145
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000146 /**
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000147 * Set sEnableJavaBpfMap for test.
148 */
149 @VisibleForTesting
150 public static void setEnableJavaBpfMapForTest(boolean enable) {
151 sEnableJavaBpfMap = enable;
152 }
153
154 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000155 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000156 */
157 @VisibleForTesting
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000158 public static void setConfigurationMapForTest(IBpfMap<S32, U32> configurationMap) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000159 sConfigurationMap = configurationMap;
160 }
161
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000162 /**
163 * Set uidOwnerMap for test.
164 */
165 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000166 public static void setUidOwnerMapForTest(IBpfMap<S32, UidOwnerValue> uidOwnerMap) {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000167 sUidOwnerMap = uidOwnerMap;
168 }
169
Motomu Utsumi65271202022-07-05 08:21:41 +0000170 /**
171 * Set uidPermissionMap for test.
172 */
173 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000174 public static void setUidPermissionMapForTest(IBpfMap<S32, U8> uidPermissionMap) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000175 sUidPermissionMap = uidPermissionMap;
176 }
177
Motomu Utsumib9548862022-09-06 16:30:05 +0900178 /**
179 * Set cookieTagMap for test.
180 */
181 @VisibleForTesting
182 public static void setCookieTagMapForTest(
183 IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap) {
184 sCookieTagMap = cookieTagMap;
185 }
186
Ken Chen24330172023-10-20 13:02:14 +0800187 /**
188 * Set dataSaverEnabledMap for test.
189 */
190 @VisibleForTesting
191 public static void setDataSaverEnabledMapForTest(IBpfMap<S32, U8> dataSaverEnabledMap) {
192 sDataSaverEnabledMap = dataSaverEnabledMap;
193 }
194
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000195 private static IBpfMap<S32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000196 try {
197 return new BpfMap<>(
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000198 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U32.class);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000199 } catch (ErrnoException e) {
200 throw new IllegalStateException("Cannot open netd configuration map", e);
201 }
202 }
203
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000204 private static IBpfMap<S32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000205 try {
206 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000207 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, UidOwnerValue.class);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000208 } catch (ErrnoException e) {
209 throw new IllegalStateException("Cannot open uid owner map", e);
210 }
211 }
212
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000213 private static IBpfMap<S32, U8> getUidPermissionMap() {
Motomu Utsumi65271202022-07-05 08:21:41 +0000214 try {
215 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000216 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
Motomu Utsumi65271202022-07-05 08:21:41 +0000217 } catch (ErrnoException e) {
218 throw new IllegalStateException("Cannot open uid permission map", e);
219 }
220 }
221
Motomu Utsumib9548862022-09-06 16:30:05 +0900222 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
223 try {
224 return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,
225 CookieTagMapKey.class, CookieTagMapValue.class);
226 } catch (ErrnoException e) {
227 throw new IllegalStateException("Cannot open cookie tag map", e);
228 }
229 }
230
Ken Chen24330172023-10-20 13:02:14 +0800231 private static IBpfMap<S32, U8> getDataSaverEnabledMap() {
232 try {
233 return new BpfMap<>(
234 DATA_SAVER_ENABLED_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
235 } catch (ErrnoException e) {
236 throw new IllegalStateException("Cannot open data saver enabled map", e);
237 }
238 }
239
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000240 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000241 if (sConfigurationMap == null) {
242 sConfigurationMap = getConfigurationMap();
243 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000244 try {
245 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
246 new U32(UID_RULES_DEFAULT_CONFIGURATION));
247 } catch (ErrnoException e) {
248 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
249 }
250 try {
251 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
252 new U32(STATS_SELECT_MAP_A));
253 } catch (ErrnoException e) {
254 throw new IllegalStateException("Failed to initialize current stats configuration", e);
255 }
256
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000257 if (sUidOwnerMap == null) {
258 sUidOwnerMap = getUidOwnerMap();
259 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000260 try {
261 sUidOwnerMap.clear();
262 } catch (ErrnoException e) {
263 throw new IllegalStateException("Failed to initialize uid owner map", e);
264 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000265
266 if (sUidPermissionMap == null) {
267 sUidPermissionMap = getUidPermissionMap();
268 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900269
270 if (sCookieTagMap == null) {
271 sCookieTagMap = getCookieTagMap();
272 }
Ken Chen24330172023-10-20 13:02:14 +0800273
274 if (sDataSaverEnabledMap == null) {
275 sDataSaverEnabledMap = getDataSaverEnabledMap();
276 }
277 try {
278 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(DATA_SAVER_DISABLED));
279 } catch (ErrnoException e) {
280 throw new IllegalStateException("Failed to initialize data saver configuration", e);
281 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000282 }
283
Ken Chenf5f51332022-01-28 10:08:16 +0800284 /**
285 * Initializes the class if it is not already initialized. This method will open maps but not
286 * cause any other effects. This method may be called multiple times on any thread.
287 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000288 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800289 if (sInitialized) return;
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000290 if (sEnableJavaBpfMap == null) {
Maciej Żenczykowskie7ebb152022-12-27 10:57:38 +0000291 sEnableJavaBpfMap = SdkLevel.isAtLeastU() ||
Motomu Utsumied4e7ec2023-09-13 14:58:32 +0900292 DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context,
Motomu Utsumi7628ea32023-08-14 11:09:02 +0900293 BPF_NET_MAPS_FORCE_DISABLE_JAVA_BPF_MAP);
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000294 }
295 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
296
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000297 initBpfMaps();
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900298 native_init(!sEnableJavaBpfMap /* startSkDestroyListener */);
Ken Chenf5f51332022-01-28 10:08:16 +0800299 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800300 }
301
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900302 public boolean isSkDestroyListenerRunning() {
303 return !sEnableJavaBpfMap;
304 }
305
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000306 /**
307 * Dependencies of BpfNetMaps, for injection in tests.
308 */
309 @VisibleForTesting
310 public static class Dependencies {
311 /**
312 * Get interface index.
313 */
314 public int getIfIndex(final String ifName) {
315 return Os.if_nametoindex(ifName);
316 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000317
318 /**
319 * Call synchronize_rcu()
320 */
321 public int synchronizeKernelRCU() {
322 return native_synchronizeKernelRCU();
323 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900324
325 /**
326 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
327 */
328 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
329 final int uidPermissionMapSize) {
330 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
331 uidOwnerMapSize, uidPermissionMapSize);
332 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000333 }
334
markchien49e944c2022-03-01 15:22:20 +0800335 /** Constructor used after T that doesn't need to use netd anymore. */
Junyu Lai626045a2023-08-28 18:49:44 +0800336 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000337 public BpfNetMaps(final Context context) {
338 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800339
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000340 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800341 }
342
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000343 public BpfNetMaps(final Context context, final INetd netd) {
344 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000345 }
346
347 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000348 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000349 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000350 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000351 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800352 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000353 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800354 }
355
Ken Chenf5f51332022-01-28 10:08:16 +0800356 private void maybeThrow(final int err, final String msg) {
357 if (err != 0) {
358 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
359 }
360 }
361
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000362 private void throwIfPreT(final String msg) {
363 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000364 throw new UnsupportedOperationException(msg);
365 }
366 }
367
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000368 private void removeRule(final int uid, final long match, final String caller) {
369 try {
370 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000371 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000372
373 if (oldMatch == null) {
374 throw new ServiceSpecificException(ENOENT,
375 "sUidOwnerMap does not have entry for uid: " + uid);
376 }
377
378 final UidOwnerValue newMatch = new UidOwnerValue(
379 (match == IIF_MATCH) ? 0 : oldMatch.iif,
380 oldMatch.rule & ~match
381 );
382
383 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000384 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000385 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000386 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000387 }
388 }
389 } catch (ErrnoException e) {
390 throw new ServiceSpecificException(e.errno,
391 caller + " failed to remove rule: " + Os.strerror(e.errno));
392 }
393 }
394
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000395 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000396 if (match != IIF_MATCH && iif != 0) {
397 throw new ServiceSpecificException(EINVAL,
398 "Non-interface match must have zero interface index");
399 }
400
401 try {
402 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000403 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000404
405 final UidOwnerValue newMatch;
406 if (oldMatch != null) {
407 newMatch = new UidOwnerValue(
408 (match == IIF_MATCH) ? iif : oldMatch.iif,
409 oldMatch.rule | match
410 );
411 } else {
412 newMatch = new UidOwnerValue(
413 iif,
414 match
415 );
416 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000417 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000418 }
419 } catch (ErrnoException e) {
420 throw new ServiceSpecificException(e.errno,
421 caller + " failed to add rule: " + Os.strerror(e.errno));
422 }
423 }
424
425 private void addRule(final int uid, final long match, final String caller) {
426 addRule(uid, match, 0 /* iif */, caller);
427 }
428
Ken Chenf5f51332022-01-28 10:08:16 +0800429 /**
430 * Add naughty app bandwidth rule for specific app
431 *
432 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800433 * @throws ServiceSpecificException in case of failure, with an error code indicating the
434 * cause of the failure.
435 */
Junyu Lai626045a2023-08-28 18:49:44 +0800436 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900437 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000438 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000439
440 if (sEnableJavaBpfMap) {
441 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
442 } else {
443 final int err = native_addNaughtyApp(uid);
444 maybeThrow(err, "Unable to add naughty app");
445 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800446 }
447
Ken Chenf5f51332022-01-28 10:08:16 +0800448 /**
449 * Remove naughty app bandwidth rule for specific app
450 *
451 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800452 * @throws ServiceSpecificException in case of failure, with an error code indicating the
453 * cause of the failure.
454 */
Junyu Lai626045a2023-08-28 18:49:44 +0800455 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900456 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000457 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000458
459 if (sEnableJavaBpfMap) {
460 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
461 } else {
462 final int err = native_removeNaughtyApp(uid);
463 maybeThrow(err, "Unable to remove naughty app");
464 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800465 }
466
Ken Chenf5f51332022-01-28 10:08:16 +0800467 /**
468 * Add nice app bandwidth rule for specific app
469 *
470 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800471 * @throws ServiceSpecificException in case of failure, with an error code indicating the
472 * cause of the failure.
473 */
Junyu Lai626045a2023-08-28 18:49:44 +0800474 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900475 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000476 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000477
478 if (sEnableJavaBpfMap) {
479 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
480 } else {
481 final int err = native_addNiceApp(uid);
482 maybeThrow(err, "Unable to add nice app");
483 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800484 }
485
Ken Chenf5f51332022-01-28 10:08:16 +0800486 /**
487 * Remove nice app bandwidth rule for specific app
488 *
489 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800490 * @throws ServiceSpecificException in case of failure, with an error code indicating the
491 * cause of the failure.
492 */
Junyu Lai626045a2023-08-28 18:49:44 +0800493 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900494 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000495 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000496
497 if (sEnableJavaBpfMap) {
498 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
499 } else {
500 final int err = native_removeNiceApp(uid);
501 maybeThrow(err, "Unable to remove nice app");
502 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800503 }
504
Ken Chenf5f51332022-01-28 10:08:16 +0800505 /**
506 * Set target firewall child chain
507 *
508 * @param childChain target chain to enable
509 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000510 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800511 * @throws ServiceSpecificException in case of failure, with an error code indicating the
512 * cause of the failure.
513 */
Junyu Lai626045a2023-08-28 18:49:44 +0800514 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900515 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000516 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000517
Motomu Utsumie057dd42022-08-03 01:23:49 +0000518 if (sEnableJavaBpfMap) {
519 final long match = getMatchByFirewallChain(childChain);
520 try {
521 synchronized (sUidRulesConfigBpfMapLock) {
522 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
523 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
524 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
525 }
526 } catch (ErrnoException e) {
527 throw new ServiceSpecificException(e.errno,
528 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000529 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000530 } else {
531 final int err = native_setChildChain(childChain, enable);
532 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000533 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800534 }
535
536 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000537 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000538 *
539 * @param childChain target chain
540 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
541 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000542 * @throws ServiceSpecificException in case of failure, with an error code indicating the
543 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800544 *
545 * @deprecated Use {@link BpfNetMapsReader#isChainEnabled} instead.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000546 */
Junyu Lai626045a2023-08-28 18:49:44 +0800547 // TODO: Migrate the callers to use {@link BpfNetMapsReader#isChainEnabled} instead.
548 @Deprecated
549 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000550 public boolean isChainEnabled(final int childChain) {
Junyu Lai626045a2023-08-28 18:49:44 +0800551 return BpfNetMapsReader.isChainEnabled(sConfigurationMap, childChain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000552 }
553
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900554 private Set<Integer> asSet(final int[] uids) {
555 final Set<Integer> uidSet = new ArraySet<>();
556 for (final int uid: uids) {
557 uidSet.add(uid);
558 }
559 return uidSet;
560 }
561
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000562 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800563 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000564 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800565 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000566 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800567 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000568 * @throws UnsupportedOperationException if called on pre-T devices.
569 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800570 */
Junyu Lai626045a2023-08-28 18:49:44 +0800571 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000572 public void replaceUidChain(final int chain, final int[] uids) {
573 throwIfPreT("replaceUidChain is not available on pre-T devices");
574
Motomu Utsumic7c16852022-08-03 06:51:41 +0000575 if (sEnableJavaBpfMap) {
576 final long match;
577 try {
578 match = getMatchByFirewallChain(chain);
579 } catch (ServiceSpecificException e) {
580 // Throws IllegalArgumentException to keep the behavior of
581 // ConnectivityManager#replaceFirewallChain API
582 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000583 }
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900584 final Set<Integer> uidSet = asSet(uids);
585 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
Motomu Utsumic7c16852022-08-03 06:51:41 +0000586 try {
587 synchronized (sUidOwnerMap) {
588 sUidOwnerMap.forEach((uid, config) -> {
589 // config could be null if there is a concurrent entry deletion.
Motomu Utsumi8e420ea2022-08-24 18:03:30 +0900590 // http://b/220084230. But sUidOwnerMap update must be done while holding a
591 // lock, so this should not happen.
592 if (config == null) {
593 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
594 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
Motomu Utsumic7c16852022-08-03 06:51:41 +0000595 uidSetToRemoveRule.add((int) uid.val);
596 }
597 });
598
599 for (final int uid : uidSetToRemoveRule) {
600 removeRule(uid, match, "replaceUidChain");
601 }
602 for (final int uid : uids) {
603 addRule(uid, match, "replaceUidChain");
604 }
605 }
606 } catch (ErrnoException | ServiceSpecificException e) {
607 Log.e(TAG, "replaceUidChain failed: " + e);
608 }
609 } else {
610 final int err;
611 switch (chain) {
612 case FIREWALL_CHAIN_DOZABLE:
613 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
614 break;
615 case FIREWALL_CHAIN_STANDBY:
616 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
617 break;
618 case FIREWALL_CHAIN_POWERSAVE:
619 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
620 break;
621 case FIREWALL_CHAIN_RESTRICTED:
622 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
623 break;
624 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
625 err = native_replaceUidChain(
626 "fw_low_power_standby", true /* isAllowList */, uids);
627 break;
628 case FIREWALL_CHAIN_OEM_DENY_1:
629 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
630 break;
631 case FIREWALL_CHAIN_OEM_DENY_2:
632 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
633 break;
634 case FIREWALL_CHAIN_OEM_DENY_3:
635 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
636 break;
637 default:
638 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
639 + chain);
640 }
641 if (err != 0) {
642 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
643 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800644 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800645 }
646
Ken Chenf5f51332022-01-28 10:08:16 +0800647 /**
648 * Set firewall rule for uid
649 *
650 * @param childChain target chain
651 * @param uid uid to allow/deny
652 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800653 * @throws ServiceSpecificException in case of failure, with an error code indicating the
654 * cause of the failure.
655 */
Junyu Lai626045a2023-08-28 18:49:44 +0800656 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900657 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000658 throwIfPreT("setUidRule is not available on pre-T devices");
659
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000660 if (sEnableJavaBpfMap) {
661 final long match = getMatchByFirewallChain(childChain);
662 final boolean isAllowList = isFirewallAllowList(childChain);
663 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
664 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000665
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000666 if (add) {
667 addRule(uid, match, "setUidRule");
668 } else {
669 removeRule(uid, match, "setUidRule");
670 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000671 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000672 final int err = native_setUidRule(childChain, uid, firewallRule);
673 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000674 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800675 }
676
677 /**
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900678 * Get firewall rule of specified firewall chain on specified uid.
679 *
680 * @param childChain target chain
681 * @param uid target uid
682 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
683 * @throws UnsupportedOperationException if called on pre-T devices.
684 * @throws ServiceSpecificException in case of failure, with an error code indicating the
685 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800686 *
687 * @deprecated use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900688 */
Junyu Lai626045a2023-08-28 18:49:44 +0800689 // TODO: Migrate the callers to use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900690 public int getUidRule(final int childChain, final int uid) {
Junyu Lai626045a2023-08-28 18:49:44 +0800691 return BpfNetMapsReader.getUidRule(sUidOwnerMap, childChain, uid);
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900692 }
693
Motomu Utsumid44a33a2023-03-28 18:08:12 +0900694 private Set<Integer> getUidsMatchEnabled(final int childChain) throws ErrnoException {
695 final long match = getMatchByFirewallChain(childChain);
696 Set<Integer> uids = new ArraySet<>();
697 synchronized (sUidOwnerMap) {
698 sUidOwnerMap.forEach((uid, val) -> {
699 if (val == null) {
700 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
701 } else {
702 if ((val.rule & match) != 0) {
703 uids.add(uid.val);
704 }
705 }
706 });
707 }
708 return uids;
709 }
710
711 /**
712 * Get uids that has FIREWALL_RULE_ALLOW on allowlist chain.
713 * Allowlist means the firewall denies all by default, uids must be explicitly allowed.
714 *
715 * Note that uids that has FIREWALL_RULE_DENY on allowlist chain can not be computed from the
716 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_ALLOW rule in bpf map
717 * are determined to have FIREWALL_RULE_DENY.
718 *
719 * @param childChain target chain
720 * @return Set of uids
721 */
722 public Set<Integer> getUidsWithAllowRuleOnAllowListChain(final int childChain)
723 throws ErrnoException {
724 if (!isFirewallAllowList(childChain)) {
725 throw new IllegalArgumentException("getUidsWithAllowRuleOnAllowListChain is called with"
726 + " denylist chain:" + childChain);
727 }
728 // Corresponding match is enabled for uids that has FIREWALL_RULE_ALLOW on allowlist chain.
729 return getUidsMatchEnabled(childChain);
730 }
731
732 /**
733 * Get uids that has FIREWALL_RULE_DENY on denylist chain.
734 * Denylist means the firewall allows all by default, uids must be explicitly denyed
735 *
736 * Note that uids that has FIREWALL_RULE_ALLOW on denylist chain can not be computed from the
737 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_DENY rule in bpf map
738 * are determined to have the FIREWALL_RULE_ALLOW.
739 *
740 * @param childChain target chain
741 * @return Set of uids
742 */
743 public Set<Integer> getUidsWithDenyRuleOnDenyListChain(final int childChain)
744 throws ErrnoException {
745 if (isFirewallAllowList(childChain)) {
746 throw new IllegalArgumentException("getUidsWithDenyRuleOnDenyListChain is called with"
747 + " allowlist chain:" + childChain);
748 }
749 // Corresponding match is enabled for uids that has FIREWALL_RULE_DENY on denylist chain.
750 return getUidsMatchEnabled(childChain);
751 }
752
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900753 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800754 * Add ingress interface filtering rules to a list of UIDs
755 *
756 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
757 * allowed interface and loopback to be sent to the list of UIDs.
758 *
759 * Calling this method on one or more UIDs with an existing filtering rule but a different
760 * interface name will result in the filtering rule being updated to allow the new interface
761 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
762 *
763 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800764 * be received.
765 * @param uids an array of UIDs which the filtering rules will be set
766 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800767 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800768 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800769 */
Ken Chenf5f51332022-01-28 10:08:16 +0800770 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000771 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800772 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800773 return;
774 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000775
776 if (sEnableJavaBpfMap) {
777 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
778 // ifIndex is set to 0.
779 final int ifIndex;
780 if (ifName == null) {
781 ifIndex = 0;
782 } else {
783 ifIndex = mDeps.getIfIndex(ifName);
784 if (ifIndex == 0) {
785 throw new ServiceSpecificException(ENODEV,
786 "Failed to get index of interface " + ifName);
787 }
788 }
789 for (final int uid : uids) {
790 try {
791 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
792 } catch (ServiceSpecificException e) {
793 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
794 }
795 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000796 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000797 final int err = native_addUidInterfaceRules(ifName, uids);
798 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000799 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800800 }
801
802 /**
803 * Remove ingress interface filtering rules from a list of UIDs
804 *
805 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
806 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
807 *
808 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800809 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800810 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800811 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800812 */
Ken Chenf5f51332022-01-28 10:08:16 +0800813 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000814 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800815 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800816 return;
817 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000818
819 if (sEnableJavaBpfMap) {
820 for (final int uid : uids) {
821 try {
822 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
823 } catch (ServiceSpecificException e) {
824 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
825 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000826 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000827 } else {
828 final int err = native_removeUidInterfaceRules(uids);
829 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000830 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800831 }
832
Ken Chenf5f51332022-01-28 10:08:16 +0800833 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000834 * Update lockdown rule for uid
835 *
836 * @param uid target uid to add/remove the rule
837 * @param add {@code true} to add the rule, {@code false} to remove the rule.
838 * @throws ServiceSpecificException in case of failure, with an error code indicating the
839 * cause of the failure.
840 */
Junyu Lai626045a2023-08-28 18:49:44 +0800841 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000842 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000843 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000844
845 if (sEnableJavaBpfMap) {
846 if (add) {
847 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
848 } else {
849 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
850 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000851 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000852 final int err = native_updateUidLockdownRule(uid, add);
853 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000854 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000855 }
856
857 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800858 * Request netd to change the current active network stats map.
859 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000860 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800861 * @throws ServiceSpecificException in case of failure, with an error code indicating the
862 * cause of the failure.
863 */
Junyu Lai626045a2023-08-28 18:49:44 +0800864 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien49e944c2022-03-01 15:22:20 +0800865 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000866 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
867
868 if (sEnableJavaBpfMap) {
869 try {
870 synchronized (sCurrentStatsMapConfigLock) {
871 final long config = sConfigurationMap.getValue(
872 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
873 final long newConfig = (config == STATS_SELECT_MAP_A)
874 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
875 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
876 new U32(newConfig));
877 }
878 } catch (ErrnoException e) {
879 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
880 }
881
882 // After changing the config, it's needed to make sure all the current running eBPF
883 // programs are finished and all the CPUs are aware of this config change before the old
884 // map is modified. So special hack is needed here to wait for the kernel to do a
885 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
886 // be available to all cores and the next eBPF programs triggered inside the kernel will
887 // use the new map configuration. So once this function returns it is safe to modify the
888 // old stats map without concerning about race between the kernel and userspace.
889 final int err = mDeps.synchronizeKernelRCU();
890 maybeThrow(err, "synchronizeKernelRCU failed");
891 } else {
892 final int err = native_swapActiveStatsMap();
893 maybeThrow(err, "Unable to swap active stats map");
894 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800895 }
896
Ken Chenf5f51332022-01-28 10:08:16 +0800897 /**
898 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
899 * specified. Or remove all permissions from the uids.
900 *
901 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
902 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
903 * revoke all permissions for the uids.
904 * @param uids uid of users to grant permission
905 * @throws RemoteException when netd has crashed.
906 */
907 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000908 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800909 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800910 return;
911 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000912
913 if (sEnableJavaBpfMap) {
914 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
915 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
916 for (final int uid : uids) {
917 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000918 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000919 } catch (ErrnoException e) {
920 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
921 }
922 }
923 return;
924 }
925
926 for (final int uid : uids) {
927 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000928 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
Motomu Utsumi65271202022-07-05 08:21:41 +0000929 } catch (ErrnoException e) {
930 Log.e(TAG, "Failed to set permission "
931 + permissions + " to uid " + uid + ": " + e);
932 }
933 }
934 } else {
935 native_setPermissionForUids(permissions, uids);
936 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800937 }
938
Ken Chen24330172023-10-20 13:02:14 +0800939 /**
940 * Set Data Saver enabled or disabled
941 *
942 * @param enable whether Data Saver is enabled or disabled.
943 * @throws UnsupportedOperationException if called on pre-T devices.
944 * @throws ServiceSpecificException in case of failure, with an error code indicating the
945 * cause of the failure.
946 */
947 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
948 public void setDataSaverEnabled(boolean enable) {
949 throwIfPreT("setDataSaverEnabled is not available on pre-T devices");
950
951 try {
952 final short config = enable ? DATA_SAVER_ENABLED : DATA_SAVER_DISABLED;
953 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(config));
954 } catch (ErrnoException e) {
955 throw new ServiceSpecificException(e.errno, "Unable to set data saver: "
956 + Os.strerror(e.errno));
957 }
958 }
959
Motomu Utsumi166f9662022-09-01 10:35:29 +0900960 /** Register callback for statsd to pull atom. */
Junyu Lai626045a2023-08-28 18:49:44 +0800961 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi166f9662022-09-01 10:35:29 +0900962 public void setPullAtomCallback(final Context context) {
963 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
964
965 final StatsManager statsManager = context.getSystemService(StatsManager.class);
966 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
967 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
968 }
969
970 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
971 throws ErrnoException {
972 // forEach could restart iteration from the beginning if there is a concurrent entry
973 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
974 // So using Set to count the number of entry in the map.
975 Set<K> keySet = new ArraySet<>();
976 map.forEach((k, v) -> keySet.add(k));
977 return keySet.size();
978 }
979
980 /** Callback for StatsManager#setPullAtomCallback */
981 @VisibleForTesting
982 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
983 if (atomTag != NETWORK_BPF_MAP_INFO) {
984 Log.e(TAG, "Unexpected atom tag: " + atomTag);
985 return StatsManager.PULL_SKIP;
986 }
987
988 try {
989 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
990 getMapSize(sUidPermissionMap)));
991 } catch (ErrnoException e) {
992 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
993 return StatsManager.PULL_SKIP;
994 }
995 return StatsManager.PULL_SUCCESS;
996 }
997
Motomu Utsumi310850f2022-09-02 12:48:20 +0900998 private String permissionToString(int permissionMask) {
999 if (permissionMask == PERMISSION_NONE) {
1000 return "PERMISSION_NONE";
1001 }
1002 if (permissionMask == PERMISSION_UNINSTALLED) {
1003 // PERMISSION_UNINSTALLED should never appear in the map
1004 return "PERMISSION_UNINSTALLED error!";
1005 }
1006
1007 final StringJoiner sj = new StringJoiner(" ");
1008 for (Pair<Integer, String> permission: PERMISSION_LIST) {
1009 final int permissionFlag = permission.first;
1010 final String permissionName = permission.second;
1011 if ((permissionMask & permissionFlag) != 0) {
1012 sj.add(permissionName);
1013 permissionMask &= ~permissionFlag;
1014 }
1015 }
1016 if (permissionMask != 0) {
1017 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
1018 }
1019 return sj.toString();
1020 }
1021
Motomu Utsumi372c9b42022-09-02 19:02:56 +09001022 private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
1023 try {
1024 final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
1025 pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
1026 } catch (ErrnoException e) {
1027 pw.println("Failed to read ownerMatch configuration: " + e);
1028 }
1029 }
1030
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001031 private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
1032 try {
1033 final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
1034 final String currentStatsMap =
1035 (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
1036 pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
1037 } catch (ErrnoException e) {
1038 pw.println("Falied to read current statsMap configuration: " + e);
1039 }
1040 }
1041
Ken Chen24330172023-10-20 13:02:14 +08001042 private void dumpDataSaverConfig(final IndentingPrintWriter pw) {
1043 try {
1044 final short config = sDataSaverEnabledMap.getValue(DATA_SAVER_ENABLED_KEY).val;
1045 // Any non-zero value converted from short to boolean is true by convention.
1046 pw.println("sDataSaverEnabledMap: " + (config != DATA_SAVER_DISABLED));
1047 } catch (ErrnoException e) {
1048 pw.println("Failed to read data saver configuration: " + e);
1049 }
1050 }
Ken Chene6d511f2022-01-25 11:10:42 +08001051 /**
1052 * Dump BPF maps
1053 *
Motomu Utsumi310850f2022-09-02 12:48:20 +09001054 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +08001055 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +09001056 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +08001057 * @throws IOException when file descriptor is invalid.
1058 * @throws ServiceSpecificException when the method is called on an unsupported device.
1059 */
Junyu Lai626045a2023-08-28 18:49:44 +08001060 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi310850f2022-09-02 12:48:20 +09001061 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +08001062 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00001063 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +08001064 throw new ServiceSpecificException(
1065 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
1066 + " devices, use dumpsys netd trafficcontroller instead.");
1067 }
Maciej Żenczykowskid70a3302023-09-06 16:45:25 +00001068
1069 pw.println("TrafficController"); // required by CTS testDumpBpfNetMaps
Motomu Utsumi310850f2022-09-02 12:48:20 +09001070
Motomu Utsumi316d0572022-09-15 13:24:48 +09001071 pw.println();
1072 pw.println("sEnableJavaBpfMap: " + sEnableJavaBpfMap);
Motomu Utsumi310850f2022-09-02 12:48:20 +09001073 if (verbose) {
Motomu Utsumief546a92022-10-05 16:42:29 +09001074 pw.println();
1075 pw.println("BPF map content:");
1076 pw.increaseIndent();
1077
Motomu Utsumi372c9b42022-09-02 19:02:56 +09001078 dumpOwnerMatchConfig(pw);
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001079 dumpCurrentStatsMapConfig(pw);
1080 pw.println();
1081
Motomu Utsumief546a92022-10-05 16:42:29 +09001082 // TODO: Remove CookieTagMap content dump
1083 // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
1084 // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
1085 // need to be updated before remove the dump from BpfNetMaps.
1086 BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
1087 (key, value) -> "cookie=" + key.socketCookie
1088 + " tag=0x" + Long.toHexString(value.tag)
1089 + " uid=" + value.uid);
Motomu Utsumi956d86c2022-09-02 17:01:25 +09001090 BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
1091 (uid, match) -> {
1092 if ((match.rule & IIF_MATCH) != 0) {
1093 // TODO: convert interface index to interface name by IfaceIndexNameMap
1094 return uid.val + " " + matchToString(match.rule) + " " + match.iif;
1095 } else {
1096 return uid.val + " " + matchToString(match.rule);
1097 }
1098 });
Motomu Utsumi310850f2022-09-02 12:48:20 +09001099 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
1100 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
Ken Chen24330172023-10-20 13:02:14 +08001101
1102 dumpDataSaverConfig(pw);
Motomu Utsumief546a92022-10-05 16:42:29 +09001103 pw.decreaseIndent();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001104 }
Ken Chene6d511f2022-01-25 11:10:42 +08001105 }
1106
Maciej Żenczykowski70fbfa42023-07-18 20:14:38 +00001107 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi3af8f0e2022-09-02 23:42:13 +09001108 private static native void native_init(boolean startSkDestroyListener);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001109
1110 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001111 private native int native_addNaughtyApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001112
1113 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001114 private native int native_removeNaughtyApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001115
1116 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001117 private native int native_addNiceApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001118
1119 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001120 private native int native_removeNiceApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001121
1122 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi114cd9c2022-08-01 02:08:35 +00001123 private native int native_setChildChain(int childChain, boolean enable);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001124
1125 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001126 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001127
1128 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001129 private native int native_setUidRule(int childChain, int uid, int firewallRule);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001130
1131 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001132 private native int native_addUidInterfaceRules(String ifName, int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001133
1134 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001135 private native int native_removeUidInterfaceRules(int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001136
1137 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +00001138 private native int native_updateUidLockdownRule(int uid, boolean add);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001139
1140 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001141 private native int native_swapActiveStatsMap();
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001142
1143 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma2fde98c2022-01-17 18:04:05 +08001144 private native void native_setPermissionForUids(int permissions, int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001145
1146 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi7abeaa42022-07-20 07:54:18 +00001147 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001148}