blob: 671c4ac3ab7604bc83a52f6a9b468fa9ae31878c [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;
22import static android.net.BpfNetMapsConstants.HAPPY_BOX_MATCH;
23import static android.net.BpfNetMapsConstants.IIF_MATCH;
24import static android.net.BpfNetMapsConstants.LOCKDOWN_VPN_MATCH;
25import static android.net.BpfNetMapsConstants.PENALTY_BOX_MATCH;
26import static android.net.BpfNetMapsConstants.UID_OWNER_MAP_PATH;
27import static android.net.BpfNetMapsConstants.UID_PERMISSION_MAP_PATH;
28import static android.net.BpfNetMapsConstants.UID_RULES_CONFIGURATION_KEY;
Junyu Lai626045a2023-08-28 18:49:44 +080029import static android.net.BpfNetMapsUtils.PRE_T;
Junyu Lai29b7b632023-08-23 17:35:17 +080030import static android.net.BpfNetMapsUtils.getMatchByFirewallChain;
31import static android.net.BpfNetMapsUtils.matchToString;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000032import static android.net.ConnectivityManager.FIREWALL_CHAIN_DOZABLE;
33import static android.net.ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY;
34import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1;
35import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2;
36import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3;
37import static android.net.ConnectivityManager.FIREWALL_CHAIN_POWERSAVE;
38import static android.net.ConnectivityManager.FIREWALL_CHAIN_RESTRICTED;
39import static android.net.ConnectivityManager.FIREWALL_CHAIN_STANDBY;
Motomu Utsumi40230be2022-07-05 03:27:35 +000040import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
41import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Motomu Utsumi65271202022-07-05 08:21:41 +000042import static android.net.INetd.PERMISSION_INTERNET;
Motomu Utsumi310850f2022-09-02 12:48:20 +090043import static android.net.INetd.PERMISSION_NONE;
Motomu Utsumi65271202022-07-05 08:21:41 +000044import static android.net.INetd.PERMISSION_UNINSTALLED;
Motomu Utsumi310850f2022-09-02 12:48:20 +090045import static android.net.INetd.PERMISSION_UPDATE_DEVICE_STATS;
Motomu Utsumi18b287d2022-06-19 10:45:30 +000046import static android.system.OsConstants.EINVAL;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000047import static android.system.OsConstants.ENODEV;
Motomu Utsumi60ed3be2022-06-24 10:38:57 +000048import static android.system.OsConstants.ENOENT;
Ken Chene6d511f2022-01-25 11:10:42 +080049import static android.system.OsConstants.EOPNOTSUPP;
50
Motomu Utsumi166f9662022-09-01 10:35:29 +090051import static com.android.server.ConnectivityStatsLog.NETWORK_BPF_MAP_INFO;
52
53import android.app.StatsManager;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000054import android.content.Context;
Junyu Lai626045a2023-08-28 18:49:44 +080055import android.net.BpfNetMapsReader;
Wayne Ma2fde98c2022-01-17 18:04:05 +080056import android.net.INetd;
Junyu Lai626045a2023-08-28 18:49:44 +080057import android.net.UidOwnerValue;
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +000058import android.os.Build;
Wayne Ma2fde98c2022-01-17 18:04:05 +080059import android.os.RemoteException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080060import android.os.ServiceSpecificException;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000061import android.system.ErrnoException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080062import android.system.Os;
Motomu Utsumi1a477b02022-08-23 15:14:56 +090063import android.util.ArraySet;
Motomu Utsumi310850f2022-09-02 12:48:20 +090064import android.util.IndentingPrintWriter;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080065import android.util.Log;
Motomu Utsumi310850f2022-09-02 12:48:20 +090066import android.util.Pair;
Motomu Utsumi166f9662022-09-01 10:35:29 +090067import android.util.StatsEvent;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080068
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +000069import androidx.annotation.RequiresApi;
70
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000071import com.android.internal.annotations.VisibleForTesting;
Motomu Utsumi166f9662022-09-01 10:35:29 +090072import com.android.modules.utils.BackgroundThread;
Ken Chenf5f51332022-01-28 10:08:16 +080073import com.android.modules.utils.build.SdkLevel;
Motomu Utsumi310850f2022-09-02 12:48:20 +090074import com.android.net.module.util.BpfDump;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000075import com.android.net.module.util.BpfMap;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000076import com.android.net.module.util.DeviceConfigUtils;
Motomu Utsumi73599a52022-08-24 11:59:21 +090077import com.android.net.module.util.IBpfMap;
Motomu Utsumi166f9662022-09-01 10:35:29 +090078import com.android.net.module.util.Struct;
Maciej Żenczykowski785793f2022-09-17 02:35:20 +000079import com.android.net.module.util.Struct.S32;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000080import com.android.net.module.util.Struct.U32;
Motomu Utsumi65271202022-07-05 08:21:41 +000081import com.android.net.module.util.Struct.U8;
Motomu Utsumib9548862022-09-06 16:30:05 +090082import com.android.net.module.util.bpf.CookieTagMapKey;
83import com.android.net.module.util.bpf.CookieTagMapValue;
Ken Chenf5f51332022-01-28 10:08:16 +080084
Ken Chene6d511f2022-01-25 11:10:42 +080085import java.io.FileDescriptor;
86import java.io.IOException;
Motomu Utsumi310850f2022-09-02 12:48:20 +090087import java.util.Arrays;
Motomu Utsumi166f9662022-09-01 10:35:29 +090088import java.util.List;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000089import java.util.Set;
Motomu Utsumi310850f2022-09-02 12:48:20 +090090import java.util.StringJoiner;
Ken Chene6d511f2022-01-25 11:10:42 +080091
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080092/**
93 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
94 *
95 * {@hide}
96 */
97public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000098 static {
99 if (!PRE_T) {
100 System.loadLibrary("service-connectivity");
101 }
102 }
103
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800104 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +0800105 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000106 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +0800107 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +0800108 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800109
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000110 private static Boolean sEnableJavaBpfMap = null;
Motomu Utsumi7628ea32023-08-14 11:09:02 +0900111 private static final String BPF_NET_MAPS_FORCE_DISABLE_JAVA_BPF_MAP =
112 "bpf_net_maps_force_disable_java_bpf_map";
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000113
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000114 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
115 // This entry is not accessed by others.
116 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
117 private static final Object sUidRulesConfigBpfMapLock = new Object();
118
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000119 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
120 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
121 // BpfNetMaps is an only writer of this entry.
122 private static final Object sCurrentStatsMapConfigLock = new Object();
123
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000124 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
125 private static final long STATS_SELECT_MAP_A = 0;
126 private static final long STATS_SELECT_MAP_B = 1;
127
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000128 private static IBpfMap<S32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000129 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000130 private static IBpfMap<S32, UidOwnerValue> sUidOwnerMap = null;
131 private static IBpfMap<S32, U8> sUidPermissionMap = null;
Motomu Utsumib9548862022-09-06 16:30:05 +0900132 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> sCookieTagMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000133
Motomu Utsumi310850f2022-09-02 12:48:20 +0900134 private static final List<Pair<Integer, String>> PERMISSION_LIST = Arrays.asList(
135 Pair.create(PERMISSION_INTERNET, "PERMISSION_INTERNET"),
136 Pair.create(PERMISSION_UPDATE_DEVICE_STATS, "PERMISSION_UPDATE_DEVICE_STATS")
137 );
138
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000139 /**
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000140 * Set sEnableJavaBpfMap for test.
141 */
142 @VisibleForTesting
143 public static void setEnableJavaBpfMapForTest(boolean enable) {
144 sEnableJavaBpfMap = enable;
145 }
146
147 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000148 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000149 */
150 @VisibleForTesting
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000151 public static void setConfigurationMapForTest(IBpfMap<S32, U32> configurationMap) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000152 sConfigurationMap = configurationMap;
153 }
154
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000155 /**
156 * Set uidOwnerMap for test.
157 */
158 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000159 public static void setUidOwnerMapForTest(IBpfMap<S32, UidOwnerValue> uidOwnerMap) {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000160 sUidOwnerMap = uidOwnerMap;
161 }
162
Motomu Utsumi65271202022-07-05 08:21:41 +0000163 /**
164 * Set uidPermissionMap for test.
165 */
166 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000167 public static void setUidPermissionMapForTest(IBpfMap<S32, U8> uidPermissionMap) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000168 sUidPermissionMap = uidPermissionMap;
169 }
170
Motomu Utsumib9548862022-09-06 16:30:05 +0900171 /**
172 * Set cookieTagMap for test.
173 */
174 @VisibleForTesting
175 public static void setCookieTagMapForTest(
176 IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap) {
177 sCookieTagMap = cookieTagMap;
178 }
179
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000180 private static IBpfMap<S32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000181 try {
182 return new BpfMap<>(
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000183 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U32.class);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000184 } catch (ErrnoException e) {
185 throw new IllegalStateException("Cannot open netd configuration map", e);
186 }
187 }
188
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000189 private static IBpfMap<S32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000190 try {
191 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000192 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, UidOwnerValue.class);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000193 } catch (ErrnoException e) {
194 throw new IllegalStateException("Cannot open uid owner map", e);
195 }
196 }
197
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000198 private static IBpfMap<S32, U8> getUidPermissionMap() {
Motomu Utsumi65271202022-07-05 08:21:41 +0000199 try {
200 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000201 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
Motomu Utsumi65271202022-07-05 08:21:41 +0000202 } catch (ErrnoException e) {
203 throw new IllegalStateException("Cannot open uid permission map", e);
204 }
205 }
206
Motomu Utsumib9548862022-09-06 16:30:05 +0900207 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
208 try {
209 return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,
210 CookieTagMapKey.class, CookieTagMapValue.class);
211 } catch (ErrnoException e) {
212 throw new IllegalStateException("Cannot open cookie tag map", e);
213 }
214 }
215
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000216 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000217 if (sConfigurationMap == null) {
218 sConfigurationMap = getConfigurationMap();
219 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000220 try {
221 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
222 new U32(UID_RULES_DEFAULT_CONFIGURATION));
223 } catch (ErrnoException e) {
224 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
225 }
226 try {
227 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
228 new U32(STATS_SELECT_MAP_A));
229 } catch (ErrnoException e) {
230 throw new IllegalStateException("Failed to initialize current stats configuration", e);
231 }
232
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000233 if (sUidOwnerMap == null) {
234 sUidOwnerMap = getUidOwnerMap();
235 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000236 try {
237 sUidOwnerMap.clear();
238 } catch (ErrnoException e) {
239 throw new IllegalStateException("Failed to initialize uid owner map", e);
240 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000241
242 if (sUidPermissionMap == null) {
243 sUidPermissionMap = getUidPermissionMap();
244 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900245
246 if (sCookieTagMap == null) {
247 sCookieTagMap = getCookieTagMap();
248 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000249 }
250
Ken Chenf5f51332022-01-28 10:08:16 +0800251 /**
252 * Initializes the class if it is not already initialized. This method will open maps but not
253 * cause any other effects. This method may be called multiple times on any thread.
254 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000255 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800256 if (sInitialized) return;
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000257 if (sEnableJavaBpfMap == null) {
Maciej Żenczykowskie7ebb152022-12-27 10:57:38 +0000258 sEnableJavaBpfMap = SdkLevel.isAtLeastU() ||
Motomu Utsumied4e7ec2023-09-13 14:58:32 +0900259 DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context,
Motomu Utsumi7628ea32023-08-14 11:09:02 +0900260 BPF_NET_MAPS_FORCE_DISABLE_JAVA_BPF_MAP);
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000261 }
262 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
263
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000264 initBpfMaps();
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900265 native_init(!sEnableJavaBpfMap /* startSkDestroyListener */);
Ken Chenf5f51332022-01-28 10:08:16 +0800266 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800267 }
268
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900269 public boolean isSkDestroyListenerRunning() {
270 return !sEnableJavaBpfMap;
271 }
272
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000273 /**
274 * Dependencies of BpfNetMaps, for injection in tests.
275 */
276 @VisibleForTesting
277 public static class Dependencies {
278 /**
279 * Get interface index.
280 */
281 public int getIfIndex(final String ifName) {
282 return Os.if_nametoindex(ifName);
283 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000284
285 /**
286 * Call synchronize_rcu()
287 */
288 public int synchronizeKernelRCU() {
289 return native_synchronizeKernelRCU();
290 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900291
292 /**
293 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
294 */
295 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
296 final int uidPermissionMapSize) {
297 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
298 uidOwnerMapSize, uidPermissionMapSize);
299 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000300 }
301
markchien49e944c2022-03-01 15:22:20 +0800302 /** Constructor used after T that doesn't need to use netd anymore. */
Junyu Lai626045a2023-08-28 18:49:44 +0800303 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000304 public BpfNetMaps(final Context context) {
305 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800306
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000307 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800308 }
309
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000310 public BpfNetMaps(final Context context, final INetd netd) {
311 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000312 }
313
314 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000315 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000316 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000317 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000318 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800319 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000320 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800321 }
322
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000323 /**
Motomu Utsumi40230be2022-07-05 03:27:35 +0000324 * Get if the chain is allow list or not.
325 *
326 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
327 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
328 */
Motomu Utsumi40230be2022-07-05 03:27:35 +0000329 public boolean isFirewallAllowList(final int chain) {
330 switch (chain) {
331 case FIREWALL_CHAIN_DOZABLE:
332 case FIREWALL_CHAIN_POWERSAVE:
333 case FIREWALL_CHAIN_RESTRICTED:
334 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
335 return true;
336 case FIREWALL_CHAIN_STANDBY:
337 case FIREWALL_CHAIN_OEM_DENY_1:
338 case FIREWALL_CHAIN_OEM_DENY_2:
339 case FIREWALL_CHAIN_OEM_DENY_3:
340 return false;
341 default:
342 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
343 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000344 }
345
Ken Chenf5f51332022-01-28 10:08:16 +0800346 private void maybeThrow(final int err, final String msg) {
347 if (err != 0) {
348 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
349 }
350 }
351
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000352 private void throwIfPreT(final String msg) {
353 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000354 throw new UnsupportedOperationException(msg);
355 }
356 }
357
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000358 private void removeRule(final int uid, final long match, final String caller) {
359 try {
360 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000361 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000362
363 if (oldMatch == null) {
364 throw new ServiceSpecificException(ENOENT,
365 "sUidOwnerMap does not have entry for uid: " + uid);
366 }
367
368 final UidOwnerValue newMatch = new UidOwnerValue(
369 (match == IIF_MATCH) ? 0 : oldMatch.iif,
370 oldMatch.rule & ~match
371 );
372
373 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000374 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000375 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000376 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000377 }
378 }
379 } catch (ErrnoException e) {
380 throw new ServiceSpecificException(e.errno,
381 caller + " failed to remove rule: " + Os.strerror(e.errno));
382 }
383 }
384
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000385 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000386 if (match != IIF_MATCH && iif != 0) {
387 throw new ServiceSpecificException(EINVAL,
388 "Non-interface match must have zero interface index");
389 }
390
391 try {
392 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000393 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000394
395 final UidOwnerValue newMatch;
396 if (oldMatch != null) {
397 newMatch = new UidOwnerValue(
398 (match == IIF_MATCH) ? iif : oldMatch.iif,
399 oldMatch.rule | match
400 );
401 } else {
402 newMatch = new UidOwnerValue(
403 iif,
404 match
405 );
406 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000407 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000408 }
409 } catch (ErrnoException e) {
410 throw new ServiceSpecificException(e.errno,
411 caller + " failed to add rule: " + Os.strerror(e.errno));
412 }
413 }
414
415 private void addRule(final int uid, final long match, final String caller) {
416 addRule(uid, match, 0 /* iif */, caller);
417 }
418
Ken Chenf5f51332022-01-28 10:08:16 +0800419 /**
420 * Add naughty app bandwidth rule for specific app
421 *
422 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800423 * @throws ServiceSpecificException in case of failure, with an error code indicating the
424 * cause of the failure.
425 */
Junyu Lai626045a2023-08-28 18:49:44 +0800426 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900427 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000428 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000429
430 if (sEnableJavaBpfMap) {
431 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
432 } else {
433 final int err = native_addNaughtyApp(uid);
434 maybeThrow(err, "Unable to add naughty app");
435 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800436 }
437
Ken Chenf5f51332022-01-28 10:08:16 +0800438 /**
439 * Remove naughty app bandwidth rule for specific app
440 *
441 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800442 * @throws ServiceSpecificException in case of failure, with an error code indicating the
443 * cause of the failure.
444 */
Junyu Lai626045a2023-08-28 18:49:44 +0800445 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900446 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000447 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000448
449 if (sEnableJavaBpfMap) {
450 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
451 } else {
452 final int err = native_removeNaughtyApp(uid);
453 maybeThrow(err, "Unable to remove naughty app");
454 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800455 }
456
Ken Chenf5f51332022-01-28 10:08:16 +0800457 /**
458 * Add nice 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 */
Junyu Lai626045a2023-08-28 18:49:44 +0800464 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900465 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000466 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000467
468 if (sEnableJavaBpfMap) {
469 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
470 } else {
471 final int err = native_addNiceApp(uid);
472 maybeThrow(err, "Unable to add nice app");
473 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800474 }
475
Ken Chenf5f51332022-01-28 10:08:16 +0800476 /**
477 * Remove nice app bandwidth rule for specific app
478 *
479 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800480 * @throws ServiceSpecificException in case of failure, with an error code indicating the
481 * cause of the failure.
482 */
Junyu Lai626045a2023-08-28 18:49:44 +0800483 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900484 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000485 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000486
487 if (sEnableJavaBpfMap) {
488 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
489 } else {
490 final int err = native_removeNiceApp(uid);
491 maybeThrow(err, "Unable to remove nice app");
492 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800493 }
494
Ken Chenf5f51332022-01-28 10:08:16 +0800495 /**
496 * Set target firewall child chain
497 *
498 * @param childChain target chain to enable
499 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000500 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800501 * @throws ServiceSpecificException in case of failure, with an error code indicating the
502 * cause of the failure.
503 */
Junyu Lai626045a2023-08-28 18:49:44 +0800504 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900505 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000506 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000507
Motomu Utsumie057dd42022-08-03 01:23:49 +0000508 if (sEnableJavaBpfMap) {
509 final long match = getMatchByFirewallChain(childChain);
510 try {
511 synchronized (sUidRulesConfigBpfMapLock) {
512 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
513 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
514 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
515 }
516 } catch (ErrnoException e) {
517 throw new ServiceSpecificException(e.errno,
518 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000519 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000520 } else {
521 final int err = native_setChildChain(childChain, enable);
522 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000523 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800524 }
525
526 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000527 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000528 *
529 * @param childChain target chain
530 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
531 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000532 * @throws ServiceSpecificException in case of failure, with an error code indicating the
533 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800534 *
535 * @deprecated Use {@link BpfNetMapsReader#isChainEnabled} instead.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000536 */
Junyu Lai626045a2023-08-28 18:49:44 +0800537 // TODO: Migrate the callers to use {@link BpfNetMapsReader#isChainEnabled} instead.
538 @Deprecated
539 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000540 public boolean isChainEnabled(final int childChain) {
Junyu Lai626045a2023-08-28 18:49:44 +0800541 return BpfNetMapsReader.isChainEnabled(sConfigurationMap, childChain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000542 }
543
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900544 private Set<Integer> asSet(final int[] uids) {
545 final Set<Integer> uidSet = new ArraySet<>();
546 for (final int uid: uids) {
547 uidSet.add(uid);
548 }
549 return uidSet;
550 }
551
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000552 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800553 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000554 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800555 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000556 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800557 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000558 * @throws UnsupportedOperationException if called on pre-T devices.
559 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800560 */
Junyu Lai626045a2023-08-28 18:49:44 +0800561 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000562 public void replaceUidChain(final int chain, final int[] uids) {
563 throwIfPreT("replaceUidChain is not available on pre-T devices");
564
Motomu Utsumic7c16852022-08-03 06:51:41 +0000565 if (sEnableJavaBpfMap) {
566 final long match;
567 try {
568 match = getMatchByFirewallChain(chain);
569 } catch (ServiceSpecificException e) {
570 // Throws IllegalArgumentException to keep the behavior of
571 // ConnectivityManager#replaceFirewallChain API
572 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000573 }
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900574 final Set<Integer> uidSet = asSet(uids);
575 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
Motomu Utsumic7c16852022-08-03 06:51:41 +0000576 try {
577 synchronized (sUidOwnerMap) {
578 sUidOwnerMap.forEach((uid, config) -> {
579 // config could be null if there is a concurrent entry deletion.
Motomu Utsumi8e420ea2022-08-24 18:03:30 +0900580 // http://b/220084230. But sUidOwnerMap update must be done while holding a
581 // lock, so this should not happen.
582 if (config == null) {
583 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
584 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
Motomu Utsumic7c16852022-08-03 06:51:41 +0000585 uidSetToRemoveRule.add((int) uid.val);
586 }
587 });
588
589 for (final int uid : uidSetToRemoveRule) {
590 removeRule(uid, match, "replaceUidChain");
591 }
592 for (final int uid : uids) {
593 addRule(uid, match, "replaceUidChain");
594 }
595 }
596 } catch (ErrnoException | ServiceSpecificException e) {
597 Log.e(TAG, "replaceUidChain failed: " + e);
598 }
599 } else {
600 final int err;
601 switch (chain) {
602 case FIREWALL_CHAIN_DOZABLE:
603 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
604 break;
605 case FIREWALL_CHAIN_STANDBY:
606 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
607 break;
608 case FIREWALL_CHAIN_POWERSAVE:
609 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
610 break;
611 case FIREWALL_CHAIN_RESTRICTED:
612 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
613 break;
614 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
615 err = native_replaceUidChain(
616 "fw_low_power_standby", true /* isAllowList */, uids);
617 break;
618 case FIREWALL_CHAIN_OEM_DENY_1:
619 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
620 break;
621 case FIREWALL_CHAIN_OEM_DENY_2:
622 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
623 break;
624 case FIREWALL_CHAIN_OEM_DENY_3:
625 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
626 break;
627 default:
628 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
629 + chain);
630 }
631 if (err != 0) {
632 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
633 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800634 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800635 }
636
Ken Chenf5f51332022-01-28 10:08:16 +0800637 /**
638 * Set firewall rule for uid
639 *
640 * @param childChain target chain
641 * @param uid uid to allow/deny
642 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800643 * @throws ServiceSpecificException in case of failure, with an error code indicating the
644 * cause of the failure.
645 */
Junyu Lai626045a2023-08-28 18:49:44 +0800646 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900647 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000648 throwIfPreT("setUidRule is not available on pre-T devices");
649
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000650 if (sEnableJavaBpfMap) {
651 final long match = getMatchByFirewallChain(childChain);
652 final boolean isAllowList = isFirewallAllowList(childChain);
653 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
654 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000655
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000656 if (add) {
657 addRule(uid, match, "setUidRule");
658 } else {
659 removeRule(uid, match, "setUidRule");
660 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000661 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000662 final int err = native_setUidRule(childChain, uid, firewallRule);
663 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000664 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800665 }
666
667 /**
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900668 * Get firewall rule of specified firewall chain on specified uid.
669 *
670 * @param childChain target chain
671 * @param uid target uid
672 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
673 * @throws UnsupportedOperationException if called on pre-T devices.
674 * @throws ServiceSpecificException in case of failure, with an error code indicating the
675 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800676 *
677 * @deprecated use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900678 */
Junyu Lai626045a2023-08-28 18:49:44 +0800679 // TODO: Migrate the callers to use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900680 public int getUidRule(final int childChain, final int uid) {
Junyu Lai626045a2023-08-28 18:49:44 +0800681 return BpfNetMapsReader.getUidRule(sUidOwnerMap, childChain, uid);
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900682 }
683
Motomu Utsumid44a33a2023-03-28 18:08:12 +0900684 private Set<Integer> getUidsMatchEnabled(final int childChain) throws ErrnoException {
685 final long match = getMatchByFirewallChain(childChain);
686 Set<Integer> uids = new ArraySet<>();
687 synchronized (sUidOwnerMap) {
688 sUidOwnerMap.forEach((uid, val) -> {
689 if (val == null) {
690 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
691 } else {
692 if ((val.rule & match) != 0) {
693 uids.add(uid.val);
694 }
695 }
696 });
697 }
698 return uids;
699 }
700
701 /**
702 * Get uids that has FIREWALL_RULE_ALLOW on allowlist chain.
703 * Allowlist means the firewall denies all by default, uids must be explicitly allowed.
704 *
705 * Note that uids that has FIREWALL_RULE_DENY on allowlist chain can not be computed from the
706 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_ALLOW rule in bpf map
707 * are determined to have FIREWALL_RULE_DENY.
708 *
709 * @param childChain target chain
710 * @return Set of uids
711 */
712 public Set<Integer> getUidsWithAllowRuleOnAllowListChain(final int childChain)
713 throws ErrnoException {
714 if (!isFirewallAllowList(childChain)) {
715 throw new IllegalArgumentException("getUidsWithAllowRuleOnAllowListChain is called with"
716 + " denylist chain:" + childChain);
717 }
718 // Corresponding match is enabled for uids that has FIREWALL_RULE_ALLOW on allowlist chain.
719 return getUidsMatchEnabled(childChain);
720 }
721
722 /**
723 * Get uids that has FIREWALL_RULE_DENY on denylist chain.
724 * Denylist means the firewall allows all by default, uids must be explicitly denyed
725 *
726 * Note that uids that has FIREWALL_RULE_ALLOW on denylist chain can not be computed from the
727 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_DENY rule in bpf map
728 * are determined to have the FIREWALL_RULE_ALLOW.
729 *
730 * @param childChain target chain
731 * @return Set of uids
732 */
733 public Set<Integer> getUidsWithDenyRuleOnDenyListChain(final int childChain)
734 throws ErrnoException {
735 if (isFirewallAllowList(childChain)) {
736 throw new IllegalArgumentException("getUidsWithDenyRuleOnDenyListChain is called with"
737 + " allowlist chain:" + childChain);
738 }
739 // Corresponding match is enabled for uids that has FIREWALL_RULE_DENY on denylist chain.
740 return getUidsMatchEnabled(childChain);
741 }
742
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900743 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800744 * Add ingress interface filtering rules to a list of UIDs
745 *
746 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
747 * allowed interface and loopback to be sent to the list of UIDs.
748 *
749 * Calling this method on one or more UIDs with an existing filtering rule but a different
750 * interface name will result in the filtering rule being updated to allow the new interface
751 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
752 *
753 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800754 * be received.
755 * @param uids an array of UIDs which the filtering rules will be set
756 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800757 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800758 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800759 */
Ken Chenf5f51332022-01-28 10:08:16 +0800760 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000761 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800762 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800763 return;
764 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000765
766 if (sEnableJavaBpfMap) {
767 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
768 // ifIndex is set to 0.
769 final int ifIndex;
770 if (ifName == null) {
771 ifIndex = 0;
772 } else {
773 ifIndex = mDeps.getIfIndex(ifName);
774 if (ifIndex == 0) {
775 throw new ServiceSpecificException(ENODEV,
776 "Failed to get index of interface " + ifName);
777 }
778 }
779 for (final int uid : uids) {
780 try {
781 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
782 } catch (ServiceSpecificException e) {
783 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
784 }
785 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000786 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000787 final int err = native_addUidInterfaceRules(ifName, uids);
788 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000789 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800790 }
791
792 /**
793 * Remove ingress interface filtering rules from a list of UIDs
794 *
795 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
796 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
797 *
798 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800799 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800800 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800801 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800802 */
Ken Chenf5f51332022-01-28 10:08:16 +0800803 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000804 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800805 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800806 return;
807 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000808
809 if (sEnableJavaBpfMap) {
810 for (final int uid : uids) {
811 try {
812 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
813 } catch (ServiceSpecificException e) {
814 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
815 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000816 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000817 } else {
818 final int err = native_removeUidInterfaceRules(uids);
819 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000820 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800821 }
822
Ken Chenf5f51332022-01-28 10:08:16 +0800823 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000824 * Update lockdown rule for uid
825 *
826 * @param uid target uid to add/remove the rule
827 * @param add {@code true} to add the rule, {@code false} to remove the rule.
828 * @throws ServiceSpecificException in case of failure, with an error code indicating the
829 * cause of the failure.
830 */
Junyu Lai626045a2023-08-28 18:49:44 +0800831 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000832 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000833 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000834
835 if (sEnableJavaBpfMap) {
836 if (add) {
837 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
838 } else {
839 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
840 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000841 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000842 final int err = native_updateUidLockdownRule(uid, add);
843 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000844 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000845 }
846
847 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800848 * Request netd to change the current active network stats map.
849 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000850 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800851 * @throws ServiceSpecificException in case of failure, with an error code indicating the
852 * cause of the failure.
853 */
Junyu Lai626045a2023-08-28 18:49:44 +0800854 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien49e944c2022-03-01 15:22:20 +0800855 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000856 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
857
858 if (sEnableJavaBpfMap) {
859 try {
860 synchronized (sCurrentStatsMapConfigLock) {
861 final long config = sConfigurationMap.getValue(
862 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
863 final long newConfig = (config == STATS_SELECT_MAP_A)
864 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
865 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
866 new U32(newConfig));
867 }
868 } catch (ErrnoException e) {
869 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
870 }
871
872 // After changing the config, it's needed to make sure all the current running eBPF
873 // programs are finished and all the CPUs are aware of this config change before the old
874 // map is modified. So special hack is needed here to wait for the kernel to do a
875 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
876 // be available to all cores and the next eBPF programs triggered inside the kernel will
877 // use the new map configuration. So once this function returns it is safe to modify the
878 // old stats map without concerning about race between the kernel and userspace.
879 final int err = mDeps.synchronizeKernelRCU();
880 maybeThrow(err, "synchronizeKernelRCU failed");
881 } else {
882 final int err = native_swapActiveStatsMap();
883 maybeThrow(err, "Unable to swap active stats map");
884 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800885 }
886
Ken Chenf5f51332022-01-28 10:08:16 +0800887 /**
888 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
889 * specified. Or remove all permissions from the uids.
890 *
891 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
892 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
893 * revoke all permissions for the uids.
894 * @param uids uid of users to grant permission
895 * @throws RemoteException when netd has crashed.
896 */
897 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000898 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800899 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800900 return;
901 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000902
903 if (sEnableJavaBpfMap) {
904 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
905 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
906 for (final int uid : uids) {
907 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000908 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000909 } catch (ErrnoException e) {
910 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
911 }
912 }
913 return;
914 }
915
916 for (final int uid : uids) {
917 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000918 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
Motomu Utsumi65271202022-07-05 08:21:41 +0000919 } catch (ErrnoException e) {
920 Log.e(TAG, "Failed to set permission "
921 + permissions + " to uid " + uid + ": " + e);
922 }
923 }
924 } else {
925 native_setPermissionForUids(permissions, uids);
926 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800927 }
928
Motomu Utsumi166f9662022-09-01 10:35:29 +0900929 /** Register callback for statsd to pull atom. */
Junyu Lai626045a2023-08-28 18:49:44 +0800930 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi166f9662022-09-01 10:35:29 +0900931 public void setPullAtomCallback(final Context context) {
932 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
933
934 final StatsManager statsManager = context.getSystemService(StatsManager.class);
935 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
936 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
937 }
938
939 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
940 throws ErrnoException {
941 // forEach could restart iteration from the beginning if there is a concurrent entry
942 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
943 // So using Set to count the number of entry in the map.
944 Set<K> keySet = new ArraySet<>();
945 map.forEach((k, v) -> keySet.add(k));
946 return keySet.size();
947 }
948
949 /** Callback for StatsManager#setPullAtomCallback */
950 @VisibleForTesting
951 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
952 if (atomTag != NETWORK_BPF_MAP_INFO) {
953 Log.e(TAG, "Unexpected atom tag: " + atomTag);
954 return StatsManager.PULL_SKIP;
955 }
956
957 try {
958 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
959 getMapSize(sUidPermissionMap)));
960 } catch (ErrnoException e) {
961 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
962 return StatsManager.PULL_SKIP;
963 }
964 return StatsManager.PULL_SUCCESS;
965 }
966
Motomu Utsumi310850f2022-09-02 12:48:20 +0900967 private String permissionToString(int permissionMask) {
968 if (permissionMask == PERMISSION_NONE) {
969 return "PERMISSION_NONE";
970 }
971 if (permissionMask == PERMISSION_UNINSTALLED) {
972 // PERMISSION_UNINSTALLED should never appear in the map
973 return "PERMISSION_UNINSTALLED error!";
974 }
975
976 final StringJoiner sj = new StringJoiner(" ");
977 for (Pair<Integer, String> permission: PERMISSION_LIST) {
978 final int permissionFlag = permission.first;
979 final String permissionName = permission.second;
980 if ((permissionMask & permissionFlag) != 0) {
981 sj.add(permissionName);
982 permissionMask &= ~permissionFlag;
983 }
984 }
985 if (permissionMask != 0) {
986 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
987 }
988 return sj.toString();
989 }
990
Motomu Utsumi372c9b42022-09-02 19:02:56 +0900991 private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
992 try {
993 final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
994 pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
995 } catch (ErrnoException e) {
996 pw.println("Failed to read ownerMatch configuration: " + e);
997 }
998 }
999
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001000 private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
1001 try {
1002 final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
1003 final String currentStatsMap =
1004 (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
1005 pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
1006 } catch (ErrnoException e) {
1007 pw.println("Falied to read current statsMap configuration: " + e);
1008 }
1009 }
1010
Ken Chene6d511f2022-01-25 11:10:42 +08001011 /**
1012 * Dump BPF maps
1013 *
Motomu Utsumi310850f2022-09-02 12:48:20 +09001014 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +08001015 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +09001016 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +08001017 * @throws IOException when file descriptor is invalid.
1018 * @throws ServiceSpecificException when the method is called on an unsupported device.
1019 */
Junyu Lai626045a2023-08-28 18:49:44 +08001020 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi310850f2022-09-02 12:48:20 +09001021 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +08001022 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00001023 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +08001024 throw new ServiceSpecificException(
1025 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
1026 + " devices, use dumpsys netd trafficcontroller instead.");
1027 }
Maciej Żenczykowskid70a3302023-09-06 16:45:25 +00001028
1029 pw.println("TrafficController"); // required by CTS testDumpBpfNetMaps
Motomu Utsumi310850f2022-09-02 12:48:20 +09001030
Motomu Utsumi316d0572022-09-15 13:24:48 +09001031 pw.println();
1032 pw.println("sEnableJavaBpfMap: " + sEnableJavaBpfMap);
Motomu Utsumi310850f2022-09-02 12:48:20 +09001033 if (verbose) {
Motomu Utsumief546a92022-10-05 16:42:29 +09001034 pw.println();
1035 pw.println("BPF map content:");
1036 pw.increaseIndent();
1037
Motomu Utsumi372c9b42022-09-02 19:02:56 +09001038 dumpOwnerMatchConfig(pw);
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001039 dumpCurrentStatsMapConfig(pw);
1040 pw.println();
1041
Motomu Utsumief546a92022-10-05 16:42:29 +09001042 // TODO: Remove CookieTagMap content dump
1043 // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
1044 // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
1045 // need to be updated before remove the dump from BpfNetMaps.
1046 BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
1047 (key, value) -> "cookie=" + key.socketCookie
1048 + " tag=0x" + Long.toHexString(value.tag)
1049 + " uid=" + value.uid);
Motomu Utsumi956d86c2022-09-02 17:01:25 +09001050 BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
1051 (uid, match) -> {
1052 if ((match.rule & IIF_MATCH) != 0) {
1053 // TODO: convert interface index to interface name by IfaceIndexNameMap
1054 return uid.val + " " + matchToString(match.rule) + " " + match.iif;
1055 } else {
1056 return uid.val + " " + matchToString(match.rule);
1057 }
1058 });
Motomu Utsumi310850f2022-09-02 12:48:20 +09001059 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
1060 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
Motomu Utsumief546a92022-10-05 16:42:29 +09001061 pw.decreaseIndent();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001062 }
Ken Chene6d511f2022-01-25 11:10:42 +08001063 }
1064
Maciej Żenczykowski70fbfa42023-07-18 20:14:38 +00001065 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi3af8f0e2022-09-02 23:42:13 +09001066 private static native void native_init(boolean startSkDestroyListener);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001067
1068 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001069 private native int native_addNaughtyApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001070
1071 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001072 private native int native_removeNaughtyApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001073
1074 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001075 private native int native_addNiceApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001076
1077 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001078 private native int native_removeNiceApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001079
1080 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi114cd9c2022-08-01 02:08:35 +00001081 private native int native_setChildChain(int childChain, boolean enable);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001082
1083 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001084 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001085
1086 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001087 private native int native_setUidRule(int childChain, int uid, int firewallRule);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001088
1089 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001090 private native int native_addUidInterfaceRules(String ifName, int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001091
1092 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001093 private native int native_removeUidInterfaceRules(int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001094
1095 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +00001096 private native int native_updateUidLockdownRule(int uid, boolean add);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001097
1098 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001099 private native int native_swapActiveStatsMap();
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001100
1101 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma2fde98c2022-01-17 18:04:05 +08001102 private native void native_setPermissionForUids(int permissions, int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001103
1104 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi7abeaa42022-07-20 07:54:18 +00001105 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001106}