blob: f08ffc320ce8992707bae6b2a9e3446892a775f4 [file] [log] [blame]
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001/*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000019import static android.net.ConnectivityManager.FIREWALL_CHAIN_DOZABLE;
20import static android.net.ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY;
21import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1;
22import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2;
23import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3;
24import static android.net.ConnectivityManager.FIREWALL_CHAIN_POWERSAVE;
25import static android.net.ConnectivityManager.FIREWALL_CHAIN_RESTRICTED;
26import static android.net.ConnectivityManager.FIREWALL_CHAIN_STANDBY;
Motomu Utsumi40230be2022-07-05 03:27:35 +000027import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
28import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Motomu Utsumi65271202022-07-05 08:21:41 +000029import static android.net.INetd.PERMISSION_INTERNET;
Motomu Utsumi310850f2022-09-02 12:48:20 +090030import static android.net.INetd.PERMISSION_NONE;
Motomu Utsumi65271202022-07-05 08:21:41 +000031import static android.net.INetd.PERMISSION_UNINSTALLED;
Motomu Utsumi310850f2022-09-02 12:48:20 +090032import static android.net.INetd.PERMISSION_UPDATE_DEVICE_STATS;
Motomu Utsumi18b287d2022-06-19 10:45:30 +000033import static android.system.OsConstants.EINVAL;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000034import static android.system.OsConstants.ENODEV;
Motomu Utsumi60ed3be2022-06-24 10:38:57 +000035import static android.system.OsConstants.ENOENT;
Ken Chene6d511f2022-01-25 11:10:42 +080036import static android.system.OsConstants.EOPNOTSUPP;
37
Motomu Utsumi166f9662022-09-01 10:35:29 +090038import static com.android.server.ConnectivityStatsLog.NETWORK_BPF_MAP_INFO;
39
40import android.app.StatsManager;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000041import android.content.Context;
Wayne Ma2fde98c2022-01-17 18:04:05 +080042import android.net.INetd;
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +000043import android.os.Build;
Wayne Ma2fde98c2022-01-17 18:04:05 +080044import android.os.RemoteException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080045import android.os.ServiceSpecificException;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000046import android.provider.DeviceConfig;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000047import android.system.ErrnoException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080048import android.system.Os;
Motomu Utsumi1a477b02022-08-23 15:14:56 +090049import android.util.ArraySet;
Motomu Utsumi310850f2022-09-02 12:48:20 +090050import android.util.IndentingPrintWriter;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080051import android.util.Log;
Motomu Utsumi310850f2022-09-02 12:48:20 +090052import android.util.Pair;
Motomu Utsumi166f9662022-09-01 10:35:29 +090053import android.util.StatsEvent;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080054
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +000055import androidx.annotation.RequiresApi;
56
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000057import com.android.internal.annotations.VisibleForTesting;
Motomu Utsumi166f9662022-09-01 10:35:29 +090058import com.android.modules.utils.BackgroundThread;
Ken Chenf5f51332022-01-28 10:08:16 +080059import com.android.modules.utils.build.SdkLevel;
Motomu Utsumi310850f2022-09-02 12:48:20 +090060import com.android.net.module.util.BpfDump;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000061import com.android.net.module.util.BpfMap;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000062import com.android.net.module.util.DeviceConfigUtils;
Motomu Utsumi73599a52022-08-24 11:59:21 +090063import com.android.net.module.util.IBpfMap;
Motomu Utsumi166f9662022-09-01 10:35:29 +090064import com.android.net.module.util.Struct;
Maciej Żenczykowski785793f2022-09-17 02:35:20 +000065import com.android.net.module.util.Struct.S32;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000066import com.android.net.module.util.Struct.U32;
Motomu Utsumi65271202022-07-05 08:21:41 +000067import com.android.net.module.util.Struct.U8;
Motomu Utsumib9548862022-09-06 16:30:05 +090068import com.android.net.module.util.bpf.CookieTagMapKey;
69import com.android.net.module.util.bpf.CookieTagMapValue;
Ken Chenf5f51332022-01-28 10:08:16 +080070
Ken Chene6d511f2022-01-25 11:10:42 +080071import java.io.FileDescriptor;
72import java.io.IOException;
Motomu Utsumi310850f2022-09-02 12:48:20 +090073import java.util.Arrays;
Motomu Utsumi166f9662022-09-01 10:35:29 +090074import java.util.List;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000075import java.util.Set;
Motomu Utsumi310850f2022-09-02 12:48:20 +090076import java.util.StringJoiner;
Ken Chene6d511f2022-01-25 11:10:42 +080077
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080078/**
79 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
80 *
81 * {@hide}
82 */
83public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000084 private static final boolean PRE_T = !SdkLevel.isAtLeastT();
85 static {
86 if (!PRE_T) {
87 System.loadLibrary("service-connectivity");
88 }
89 }
90
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080091 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +080092 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000093 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +080094 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +080095 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080096
Motomu Utsumif688eeb2022-07-22 03:47:35 +000097 private static Boolean sEnableJavaBpfMap = null;
98 private static final String BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP =
99 "bpf_net_maps_enable_java_bpf_map";
100
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000101 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
102 // This entry is not accessed by others.
103 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
104 private static final Object sUidRulesConfigBpfMapLock = new Object();
105
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000106 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
107 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
108 // BpfNetMaps is an only writer of this entry.
109 private static final Object sCurrentStatsMapConfigLock = new Object();
110
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000111 private static final String CONFIGURATION_MAP_PATH =
112 "/sys/fs/bpf/netd_shared/map_netd_configuration_map";
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000113 private static final String UID_OWNER_MAP_PATH =
114 "/sys/fs/bpf/netd_shared/map_netd_uid_owner_map";
Motomu Utsumi65271202022-07-05 08:21:41 +0000115 private static final String UID_PERMISSION_MAP_PATH =
116 "/sys/fs/bpf/netd_shared/map_netd_uid_permission_map";
Motomu Utsumib9548862022-09-06 16:30:05 +0900117 private static final String COOKIE_TAG_MAP_PATH =
118 "/sys/fs/bpf/netd_shared/map_netd_cookie_tag_map";
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000119 private static final S32 UID_RULES_CONFIGURATION_KEY = new S32(0);
120 private static final S32 CURRENT_STATS_MAP_CONFIGURATION_KEY = new S32(1);
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000121 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
122 private static final long STATS_SELECT_MAP_A = 0;
123 private static final long STATS_SELECT_MAP_B = 1;
124
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000125 private static IBpfMap<S32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000126 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000127 private static IBpfMap<S32, UidOwnerValue> sUidOwnerMap = null;
128 private static IBpfMap<S32, U8> sUidPermissionMap = null;
Motomu Utsumib9548862022-09-06 16:30:05 +0900129 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> sCookieTagMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000130
131 // LINT.IfChange(match_type)
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000132 @VisibleForTesting public static final long NO_MATCH = 0;
133 @VisibleForTesting public static final long HAPPY_BOX_MATCH = (1 << 0);
134 @VisibleForTesting public static final long PENALTY_BOX_MATCH = (1 << 1);
135 @VisibleForTesting public static final long DOZABLE_MATCH = (1 << 2);
136 @VisibleForTesting public static final long STANDBY_MATCH = (1 << 3);
137 @VisibleForTesting public static final long POWERSAVE_MATCH = (1 << 4);
138 @VisibleForTesting public static final long RESTRICTED_MATCH = (1 << 5);
139 @VisibleForTesting public static final long LOW_POWER_STANDBY_MATCH = (1 << 6);
140 @VisibleForTesting public static final long IIF_MATCH = (1 << 7);
141 @VisibleForTesting public static final long LOCKDOWN_VPN_MATCH = (1 << 8);
142 @VisibleForTesting public static final long OEM_DENY_1_MATCH = (1 << 9);
143 @VisibleForTesting public static final long OEM_DENY_2_MATCH = (1 << 10);
144 @VisibleForTesting public static final long OEM_DENY_3_MATCH = (1 << 11);
Maciej Żenczykowski513474c2022-12-08 16:20:43 +0000145 // LINT.ThenChange(packages/modules/Connectivity/bpf_progs/netd.h)
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000146
Motomu Utsumi310850f2022-09-02 12:48:20 +0900147 private static final List<Pair<Integer, String>> PERMISSION_LIST = Arrays.asList(
148 Pair.create(PERMISSION_INTERNET, "PERMISSION_INTERNET"),
149 Pair.create(PERMISSION_UPDATE_DEVICE_STATS, "PERMISSION_UPDATE_DEVICE_STATS")
150 );
Motomu Utsumi956d86c2022-09-02 17:01:25 +0900151 private static final List<Pair<Long, String>> MATCH_LIST = Arrays.asList(
152 Pair.create(HAPPY_BOX_MATCH, "HAPPY_BOX_MATCH"),
153 Pair.create(PENALTY_BOX_MATCH, "PENALTY_BOX_MATCH"),
154 Pair.create(DOZABLE_MATCH, "DOZABLE_MATCH"),
155 Pair.create(STANDBY_MATCH, "STANDBY_MATCH"),
156 Pair.create(POWERSAVE_MATCH, "POWERSAVE_MATCH"),
157 Pair.create(RESTRICTED_MATCH, "RESTRICTED_MATCH"),
158 Pair.create(LOW_POWER_STANDBY_MATCH, "LOW_POWER_STANDBY_MATCH"),
159 Pair.create(IIF_MATCH, "IIF_MATCH"),
160 Pair.create(LOCKDOWN_VPN_MATCH, "LOCKDOWN_VPN_MATCH"),
161 Pair.create(OEM_DENY_1_MATCH, "OEM_DENY_1_MATCH"),
162 Pair.create(OEM_DENY_2_MATCH, "OEM_DENY_2_MATCH"),
163 Pair.create(OEM_DENY_3_MATCH, "OEM_DENY_3_MATCH")
164 );
Motomu Utsumi310850f2022-09-02 12:48:20 +0900165
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000166 /**
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000167 * Set sEnableJavaBpfMap for test.
168 */
169 @VisibleForTesting
170 public static void setEnableJavaBpfMapForTest(boolean enable) {
171 sEnableJavaBpfMap = enable;
172 }
173
174 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000175 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000176 */
177 @VisibleForTesting
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000178 public static void setConfigurationMapForTest(IBpfMap<S32, U32> configurationMap) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000179 sConfigurationMap = configurationMap;
180 }
181
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000182 /**
183 * Set uidOwnerMap for test.
184 */
185 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000186 public static void setUidOwnerMapForTest(IBpfMap<S32, UidOwnerValue> uidOwnerMap) {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000187 sUidOwnerMap = uidOwnerMap;
188 }
189
Motomu Utsumi65271202022-07-05 08:21:41 +0000190 /**
191 * Set uidPermissionMap for test.
192 */
193 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000194 public static void setUidPermissionMapForTest(IBpfMap<S32, U8> uidPermissionMap) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000195 sUidPermissionMap = uidPermissionMap;
196 }
197
Motomu Utsumib9548862022-09-06 16:30:05 +0900198 /**
199 * Set cookieTagMap for test.
200 */
201 @VisibleForTesting
202 public static void setCookieTagMapForTest(
203 IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap) {
204 sCookieTagMap = cookieTagMap;
205 }
206
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000207 private static IBpfMap<S32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000208 try {
209 return new BpfMap<>(
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000210 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U32.class);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000211 } catch (ErrnoException e) {
212 throw new IllegalStateException("Cannot open netd configuration map", e);
213 }
214 }
215
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000216 private static IBpfMap<S32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000217 try {
218 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000219 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, UidOwnerValue.class);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000220 } catch (ErrnoException e) {
221 throw new IllegalStateException("Cannot open uid owner map", e);
222 }
223 }
224
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000225 private static IBpfMap<S32, U8> getUidPermissionMap() {
Motomu Utsumi65271202022-07-05 08:21:41 +0000226 try {
227 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000228 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
Motomu Utsumi65271202022-07-05 08:21:41 +0000229 } catch (ErrnoException e) {
230 throw new IllegalStateException("Cannot open uid permission map", e);
231 }
232 }
233
Motomu Utsumib9548862022-09-06 16:30:05 +0900234 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
235 try {
236 return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,
237 CookieTagMapKey.class, CookieTagMapValue.class);
238 } catch (ErrnoException e) {
239 throw new IllegalStateException("Cannot open cookie tag map", e);
240 }
241 }
242
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000243 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000244 if (sConfigurationMap == null) {
245 sConfigurationMap = getConfigurationMap();
246 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000247 try {
248 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
249 new U32(UID_RULES_DEFAULT_CONFIGURATION));
250 } catch (ErrnoException e) {
251 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
252 }
253 try {
254 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
255 new U32(STATS_SELECT_MAP_A));
256 } catch (ErrnoException e) {
257 throw new IllegalStateException("Failed to initialize current stats configuration", e);
258 }
259
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000260 if (sUidOwnerMap == null) {
261 sUidOwnerMap = getUidOwnerMap();
262 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000263 try {
264 sUidOwnerMap.clear();
265 } catch (ErrnoException e) {
266 throw new IllegalStateException("Failed to initialize uid owner map", e);
267 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000268
269 if (sUidPermissionMap == null) {
270 sUidPermissionMap = getUidPermissionMap();
271 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900272
273 if (sCookieTagMap == null) {
274 sCookieTagMap = getCookieTagMap();
275 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000276 }
277
Ken Chenf5f51332022-01-28 10:08:16 +0800278 /**
279 * Initializes the class if it is not already initialized. This method will open maps but not
280 * cause any other effects. This method may be called multiple times on any thread.
281 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000282 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800283 if (sInitialized) return;
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000284 if (sEnableJavaBpfMap == null) {
Maciej Żenczykowskie7ebb152022-12-27 10:57:38 +0000285 sEnableJavaBpfMap = SdkLevel.isAtLeastU() ||
286 DeviceConfigUtils.isFeatureEnabled(context,
Motomu Utsumi278db582023-04-21 12:35:22 +0900287 DeviceConfig.NAMESPACE_TETHERING, BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP,
288 DeviceConfigUtils.TETHERING_MODULE_NAME, false /* defaultValue */);
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000289 }
290 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
291
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000292 initBpfMaps();
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900293 native_init(!sEnableJavaBpfMap /* startSkDestroyListener */);
Ken Chenf5f51332022-01-28 10:08:16 +0800294 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800295 }
296
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900297 public boolean isSkDestroyListenerRunning() {
298 return !sEnableJavaBpfMap;
299 }
300
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000301 /**
302 * Dependencies of BpfNetMaps, for injection in tests.
303 */
304 @VisibleForTesting
305 public static class Dependencies {
306 /**
307 * Get interface index.
308 */
309 public int getIfIndex(final String ifName) {
310 return Os.if_nametoindex(ifName);
311 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000312
313 /**
314 * Call synchronize_rcu()
315 */
316 public int synchronizeKernelRCU() {
317 return native_synchronizeKernelRCU();
318 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900319
320 /**
321 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
322 */
323 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
324 final int uidPermissionMapSize) {
325 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
326 uidOwnerMapSize, uidPermissionMapSize);
327 }
Motomu Utsumidf8d2992022-09-01 17:08:27 +0900328
329 /**
330 * Call native_dump
331 */
332 public void nativeDump(final FileDescriptor fd, final boolean verbose) {
333 native_dump(fd, verbose);
334 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000335 }
336
markchien49e944c2022-03-01 15:22:20 +0800337 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000338 public BpfNetMaps(final Context context) {
339 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800340
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000341 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800342 }
343
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000344 public BpfNetMaps(final Context context, final INetd netd) {
345 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000346 }
347
348 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000349 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000350 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000351 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000352 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800353 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000354 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800355 }
356
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000357 /**
358 * Get corresponding match from firewall chain.
359 */
360 @VisibleForTesting
361 public long getMatchByFirewallChain(final int chain) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000362 switch (chain) {
363 case FIREWALL_CHAIN_DOZABLE:
364 return DOZABLE_MATCH;
365 case FIREWALL_CHAIN_STANDBY:
366 return STANDBY_MATCH;
367 case FIREWALL_CHAIN_POWERSAVE:
368 return POWERSAVE_MATCH;
369 case FIREWALL_CHAIN_RESTRICTED:
370 return RESTRICTED_MATCH;
371 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
372 return LOW_POWER_STANDBY_MATCH;
373 case FIREWALL_CHAIN_OEM_DENY_1:
374 return OEM_DENY_1_MATCH;
375 case FIREWALL_CHAIN_OEM_DENY_2:
376 return OEM_DENY_2_MATCH;
377 case FIREWALL_CHAIN_OEM_DENY_3:
378 return OEM_DENY_3_MATCH;
379 default:
380 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000381 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000382 }
383
384 /**
385 * Get if the chain is allow list or not.
386 *
387 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
388 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
389 */
Motomu Utsumi40230be2022-07-05 03:27:35 +0000390 public boolean isFirewallAllowList(final int chain) {
391 switch (chain) {
392 case FIREWALL_CHAIN_DOZABLE:
393 case FIREWALL_CHAIN_POWERSAVE:
394 case FIREWALL_CHAIN_RESTRICTED:
395 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
396 return true;
397 case FIREWALL_CHAIN_STANDBY:
398 case FIREWALL_CHAIN_OEM_DENY_1:
399 case FIREWALL_CHAIN_OEM_DENY_2:
400 case FIREWALL_CHAIN_OEM_DENY_3:
401 return false;
402 default:
403 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
404 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000405 }
406
Ken Chenf5f51332022-01-28 10:08:16 +0800407 private void maybeThrow(final int err, final String msg) {
408 if (err != 0) {
409 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
410 }
411 }
412
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000413 private void throwIfPreT(final String msg) {
414 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000415 throw new UnsupportedOperationException(msg);
416 }
417 }
418
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000419 private void removeRule(final int uid, final long match, final String caller) {
420 try {
421 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000422 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000423
424 if (oldMatch == null) {
425 throw new ServiceSpecificException(ENOENT,
426 "sUidOwnerMap does not have entry for uid: " + uid);
427 }
428
429 final UidOwnerValue newMatch = new UidOwnerValue(
430 (match == IIF_MATCH) ? 0 : oldMatch.iif,
431 oldMatch.rule & ~match
432 );
433
434 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000435 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000436 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000437 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000438 }
439 }
440 } catch (ErrnoException e) {
441 throw new ServiceSpecificException(e.errno,
442 caller + " failed to remove rule: " + Os.strerror(e.errno));
443 }
444 }
445
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000446 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000447 if (match != IIF_MATCH && iif != 0) {
448 throw new ServiceSpecificException(EINVAL,
449 "Non-interface match must have zero interface index");
450 }
451
452 try {
453 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000454 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000455
456 final UidOwnerValue newMatch;
457 if (oldMatch != null) {
458 newMatch = new UidOwnerValue(
459 (match == IIF_MATCH) ? iif : oldMatch.iif,
460 oldMatch.rule | match
461 );
462 } else {
463 newMatch = new UidOwnerValue(
464 iif,
465 match
466 );
467 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000468 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000469 }
470 } catch (ErrnoException e) {
471 throw new ServiceSpecificException(e.errno,
472 caller + " failed to add rule: " + Os.strerror(e.errno));
473 }
474 }
475
476 private void addRule(final int uid, final long match, final String caller) {
477 addRule(uid, match, 0 /* iif */, caller);
478 }
479
Ken Chenf5f51332022-01-28 10:08:16 +0800480 /**
481 * Add naughty app bandwidth rule for specific app
482 *
483 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800484 * @throws ServiceSpecificException in case of failure, with an error code indicating the
485 * cause of the failure.
486 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900487 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000488 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000489
490 if (sEnableJavaBpfMap) {
491 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
492 } else {
493 final int err = native_addNaughtyApp(uid);
494 maybeThrow(err, "Unable to add naughty app");
495 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800496 }
497
Ken Chenf5f51332022-01-28 10:08:16 +0800498 /**
499 * Remove naughty app bandwidth rule for specific app
500 *
501 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800502 * @throws ServiceSpecificException in case of failure, with an error code indicating the
503 * cause of the failure.
504 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900505 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000506 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000507
508 if (sEnableJavaBpfMap) {
509 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
510 } else {
511 final int err = native_removeNaughtyApp(uid);
512 maybeThrow(err, "Unable to remove naughty app");
513 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800514 }
515
Ken Chenf5f51332022-01-28 10:08:16 +0800516 /**
517 * Add nice app bandwidth rule for specific app
518 *
519 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800520 * @throws ServiceSpecificException in case of failure, with an error code indicating the
521 * cause of the failure.
522 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900523 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000524 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000525
526 if (sEnableJavaBpfMap) {
527 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
528 } else {
529 final int err = native_addNiceApp(uid);
530 maybeThrow(err, "Unable to add nice app");
531 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800532 }
533
Ken Chenf5f51332022-01-28 10:08:16 +0800534 /**
535 * Remove nice app bandwidth rule for specific app
536 *
537 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800538 * @throws ServiceSpecificException in case of failure, with an error code indicating the
539 * cause of the failure.
540 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900541 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000542 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000543
544 if (sEnableJavaBpfMap) {
545 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
546 } else {
547 final int err = native_removeNiceApp(uid);
548 maybeThrow(err, "Unable to remove nice app");
549 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800550 }
551
Ken Chenf5f51332022-01-28 10:08:16 +0800552 /**
553 * Set target firewall child chain
554 *
555 * @param childChain target chain to enable
556 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000557 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800558 * @throws ServiceSpecificException in case of failure, with an error code indicating the
559 * cause of the failure.
560 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900561 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000562 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000563
Motomu Utsumie057dd42022-08-03 01:23:49 +0000564 if (sEnableJavaBpfMap) {
565 final long match = getMatchByFirewallChain(childChain);
566 try {
567 synchronized (sUidRulesConfigBpfMapLock) {
568 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
569 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
570 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
571 }
572 } catch (ErrnoException e) {
573 throw new ServiceSpecificException(e.errno,
574 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000575 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000576 } else {
577 final int err = native_setChildChain(childChain, enable);
578 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000579 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800580 }
581
582 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000583 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000584 *
585 * @param childChain target chain
586 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
587 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000588 * @throws ServiceSpecificException in case of failure, with an error code indicating the
589 * cause of the failure.
590 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000591 public boolean isChainEnabled(final int childChain) {
592 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000593
594 final long match = getMatchByFirewallChain(childChain);
595 try {
596 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000597 return (config.val & match) != 0;
598 } catch (ErrnoException e) {
599 throw new ServiceSpecificException(e.errno,
600 "Unable to get firewall chain status: " + Os.strerror(e.errno));
601 }
602 }
603
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900604 private Set<Integer> asSet(final int[] uids) {
605 final Set<Integer> uidSet = new ArraySet<>();
606 for (final int uid: uids) {
607 uidSet.add(uid);
608 }
609 return uidSet;
610 }
611
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000612 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800613 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000614 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800615 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000616 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800617 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000618 * @throws UnsupportedOperationException if called on pre-T devices.
619 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800620 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000621 public void replaceUidChain(final int chain, final int[] uids) {
622 throwIfPreT("replaceUidChain is not available on pre-T devices");
623
Motomu Utsumic7c16852022-08-03 06:51:41 +0000624 if (sEnableJavaBpfMap) {
625 final long match;
626 try {
627 match = getMatchByFirewallChain(chain);
628 } catch (ServiceSpecificException e) {
629 // Throws IllegalArgumentException to keep the behavior of
630 // ConnectivityManager#replaceFirewallChain API
631 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000632 }
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900633 final Set<Integer> uidSet = asSet(uids);
634 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
Motomu Utsumic7c16852022-08-03 06:51:41 +0000635 try {
636 synchronized (sUidOwnerMap) {
637 sUidOwnerMap.forEach((uid, config) -> {
638 // config could be null if there is a concurrent entry deletion.
Motomu Utsumi8e420ea2022-08-24 18:03:30 +0900639 // http://b/220084230. But sUidOwnerMap update must be done while holding a
640 // lock, so this should not happen.
641 if (config == null) {
642 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
643 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
Motomu Utsumic7c16852022-08-03 06:51:41 +0000644 uidSetToRemoveRule.add((int) uid.val);
645 }
646 });
647
648 for (final int uid : uidSetToRemoveRule) {
649 removeRule(uid, match, "replaceUidChain");
650 }
651 for (final int uid : uids) {
652 addRule(uid, match, "replaceUidChain");
653 }
654 }
655 } catch (ErrnoException | ServiceSpecificException e) {
656 Log.e(TAG, "replaceUidChain failed: " + e);
657 }
658 } else {
659 final int err;
660 switch (chain) {
661 case FIREWALL_CHAIN_DOZABLE:
662 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
663 break;
664 case FIREWALL_CHAIN_STANDBY:
665 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
666 break;
667 case FIREWALL_CHAIN_POWERSAVE:
668 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
669 break;
670 case FIREWALL_CHAIN_RESTRICTED:
671 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
672 break;
673 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
674 err = native_replaceUidChain(
675 "fw_low_power_standby", true /* isAllowList */, uids);
676 break;
677 case FIREWALL_CHAIN_OEM_DENY_1:
678 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
679 break;
680 case FIREWALL_CHAIN_OEM_DENY_2:
681 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
682 break;
683 case FIREWALL_CHAIN_OEM_DENY_3:
684 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
685 break;
686 default:
687 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
688 + chain);
689 }
690 if (err != 0) {
691 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
692 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800693 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800694 }
695
Ken Chenf5f51332022-01-28 10:08:16 +0800696 /**
697 * Set firewall rule for uid
698 *
699 * @param childChain target chain
700 * @param uid uid to allow/deny
701 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800702 * @throws ServiceSpecificException in case of failure, with an error code indicating the
703 * cause of the failure.
704 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900705 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000706 throwIfPreT("setUidRule is not available on pre-T devices");
707
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000708 if (sEnableJavaBpfMap) {
709 final long match = getMatchByFirewallChain(childChain);
710 final boolean isAllowList = isFirewallAllowList(childChain);
711 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
712 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000713
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000714 if (add) {
715 addRule(uid, match, "setUidRule");
716 } else {
717 removeRule(uid, match, "setUidRule");
718 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000719 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000720 final int err = native_setUidRule(childChain, uid, firewallRule);
721 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000722 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800723 }
724
725 /**
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900726 * Get firewall rule of specified firewall chain on specified uid.
727 *
728 * @param childChain target chain
729 * @param uid target uid
730 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
731 * @throws UnsupportedOperationException if called on pre-T devices.
732 * @throws ServiceSpecificException in case of failure, with an error code indicating the
733 * cause of the failure.
734 */
735 public int getUidRule(final int childChain, final int uid) {
736 throwIfPreT("isUidChainEnabled is not available on pre-T devices");
737
738 final long match = getMatchByFirewallChain(childChain);
739 final boolean isAllowList = isFirewallAllowList(childChain);
740 try {
741 final UidOwnerValue uidMatch = sUidOwnerMap.getValue(new S32(uid));
742 final boolean isMatchEnabled = uidMatch != null && (uidMatch.rule & match) != 0;
743 return isMatchEnabled == isAllowList ? FIREWALL_RULE_ALLOW : FIREWALL_RULE_DENY;
744 } catch (ErrnoException e) {
745 throw new ServiceSpecificException(e.errno,
746 "Unable to get uid rule status: " + Os.strerror(e.errno));
747 }
748 }
749
Motomu Utsumid44a33a2023-03-28 18:08:12 +0900750 private Set<Integer> getUidsMatchEnabled(final int childChain) throws ErrnoException {
751 final long match = getMatchByFirewallChain(childChain);
752 Set<Integer> uids = new ArraySet<>();
753 synchronized (sUidOwnerMap) {
754 sUidOwnerMap.forEach((uid, val) -> {
755 if (val == null) {
756 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
757 } else {
758 if ((val.rule & match) != 0) {
759 uids.add(uid.val);
760 }
761 }
762 });
763 }
764 return uids;
765 }
766
767 /**
768 * Get uids that has FIREWALL_RULE_ALLOW on allowlist chain.
769 * Allowlist means the firewall denies all by default, uids must be explicitly allowed.
770 *
771 * Note that uids that has FIREWALL_RULE_DENY on allowlist chain can not be computed from the
772 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_ALLOW rule in bpf map
773 * are determined to have FIREWALL_RULE_DENY.
774 *
775 * @param childChain target chain
776 * @return Set of uids
777 */
778 public Set<Integer> getUidsWithAllowRuleOnAllowListChain(final int childChain)
779 throws ErrnoException {
780 if (!isFirewallAllowList(childChain)) {
781 throw new IllegalArgumentException("getUidsWithAllowRuleOnAllowListChain is called with"
782 + " denylist chain:" + childChain);
783 }
784 // Corresponding match is enabled for uids that has FIREWALL_RULE_ALLOW on allowlist chain.
785 return getUidsMatchEnabled(childChain);
786 }
787
788 /**
789 * Get uids that has FIREWALL_RULE_DENY on denylist chain.
790 * Denylist means the firewall allows all by default, uids must be explicitly denyed
791 *
792 * Note that uids that has FIREWALL_RULE_ALLOW on denylist chain can not be computed from the
793 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_DENY rule in bpf map
794 * are determined to have the FIREWALL_RULE_ALLOW.
795 *
796 * @param childChain target chain
797 * @return Set of uids
798 */
799 public Set<Integer> getUidsWithDenyRuleOnDenyListChain(final int childChain)
800 throws ErrnoException {
801 if (isFirewallAllowList(childChain)) {
802 throw new IllegalArgumentException("getUidsWithDenyRuleOnDenyListChain is called with"
803 + " allowlist chain:" + childChain);
804 }
805 // Corresponding match is enabled for uids that has FIREWALL_RULE_DENY on denylist chain.
806 return getUidsMatchEnabled(childChain);
807 }
808
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900809 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800810 * Add ingress interface filtering rules to a list of UIDs
811 *
812 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
813 * allowed interface and loopback to be sent to the list of UIDs.
814 *
815 * Calling this method on one or more UIDs with an existing filtering rule but a different
816 * interface name will result in the filtering rule being updated to allow the new interface
817 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
818 *
819 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800820 * be received.
821 * @param uids an array of UIDs which the filtering rules will be set
822 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800823 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800824 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800825 */
Ken Chenf5f51332022-01-28 10:08:16 +0800826 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000827 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800828 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800829 return;
830 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000831
832 if (sEnableJavaBpfMap) {
833 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
834 // ifIndex is set to 0.
835 final int ifIndex;
836 if (ifName == null) {
837 ifIndex = 0;
838 } else {
839 ifIndex = mDeps.getIfIndex(ifName);
840 if (ifIndex == 0) {
841 throw new ServiceSpecificException(ENODEV,
842 "Failed to get index of interface " + ifName);
843 }
844 }
845 for (final int uid : uids) {
846 try {
847 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
848 } catch (ServiceSpecificException e) {
849 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
850 }
851 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000852 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000853 final int err = native_addUidInterfaceRules(ifName, uids);
854 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000855 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800856 }
857
858 /**
859 * Remove ingress interface filtering rules from a list of UIDs
860 *
861 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
862 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
863 *
864 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800865 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800866 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800867 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800868 */
Ken Chenf5f51332022-01-28 10:08:16 +0800869 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000870 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800871 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800872 return;
873 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000874
875 if (sEnableJavaBpfMap) {
876 for (final int uid : uids) {
877 try {
878 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
879 } catch (ServiceSpecificException e) {
880 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
881 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000882 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000883 } else {
884 final int err = native_removeUidInterfaceRules(uids);
885 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000886 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800887 }
888
Ken Chenf5f51332022-01-28 10:08:16 +0800889 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000890 * Update lockdown rule for uid
891 *
892 * @param uid target uid to add/remove the rule
893 * @param add {@code true} to add the rule, {@code false} to remove the rule.
894 * @throws ServiceSpecificException in case of failure, with an error code indicating the
895 * cause of the failure.
896 */
897 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000898 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000899
900 if (sEnableJavaBpfMap) {
901 if (add) {
902 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
903 } else {
904 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
905 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000906 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000907 final int err = native_updateUidLockdownRule(uid, add);
908 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000909 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000910 }
911
912 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800913 * Request netd to change the current active network stats map.
914 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000915 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800916 * @throws ServiceSpecificException in case of failure, with an error code indicating the
917 * cause of the failure.
918 */
markchien49e944c2022-03-01 15:22:20 +0800919 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000920 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
921
922 if (sEnableJavaBpfMap) {
923 try {
924 synchronized (sCurrentStatsMapConfigLock) {
925 final long config = sConfigurationMap.getValue(
926 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
927 final long newConfig = (config == STATS_SELECT_MAP_A)
928 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
929 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
930 new U32(newConfig));
931 }
932 } catch (ErrnoException e) {
933 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
934 }
935
936 // After changing the config, it's needed to make sure all the current running eBPF
937 // programs are finished and all the CPUs are aware of this config change before the old
938 // map is modified. So special hack is needed here to wait for the kernel to do a
939 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
940 // be available to all cores and the next eBPF programs triggered inside the kernel will
941 // use the new map configuration. So once this function returns it is safe to modify the
942 // old stats map without concerning about race between the kernel and userspace.
943 final int err = mDeps.synchronizeKernelRCU();
944 maybeThrow(err, "synchronizeKernelRCU failed");
945 } else {
946 final int err = native_swapActiveStatsMap();
947 maybeThrow(err, "Unable to swap active stats map");
948 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800949 }
950
Ken Chenf5f51332022-01-28 10:08:16 +0800951 /**
952 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
953 * specified. Or remove all permissions from the uids.
954 *
955 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
956 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
957 * revoke all permissions for the uids.
958 * @param uids uid of users to grant permission
959 * @throws RemoteException when netd has crashed.
960 */
961 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000962 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800963 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800964 return;
965 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000966
967 if (sEnableJavaBpfMap) {
968 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
969 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
970 for (final int uid : uids) {
971 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000972 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000973 } catch (ErrnoException e) {
974 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
975 }
976 }
977 return;
978 }
979
980 for (final int uid : uids) {
981 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000982 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
Motomu Utsumi65271202022-07-05 08:21:41 +0000983 } catch (ErrnoException e) {
984 Log.e(TAG, "Failed to set permission "
985 + permissions + " to uid " + uid + ": " + e);
986 }
987 }
988 } else {
989 native_setPermissionForUids(permissions, uids);
990 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800991 }
992
Motomu Utsumi166f9662022-09-01 10:35:29 +0900993 /** Register callback for statsd to pull atom. */
994 public void setPullAtomCallback(final Context context) {
995 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
996
997 final StatsManager statsManager = context.getSystemService(StatsManager.class);
998 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
999 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
1000 }
1001
1002 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
1003 throws ErrnoException {
1004 // forEach could restart iteration from the beginning if there is a concurrent entry
1005 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
1006 // So using Set to count the number of entry in the map.
1007 Set<K> keySet = new ArraySet<>();
1008 map.forEach((k, v) -> keySet.add(k));
1009 return keySet.size();
1010 }
1011
1012 /** Callback for StatsManager#setPullAtomCallback */
1013 @VisibleForTesting
1014 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
1015 if (atomTag != NETWORK_BPF_MAP_INFO) {
1016 Log.e(TAG, "Unexpected atom tag: " + atomTag);
1017 return StatsManager.PULL_SKIP;
1018 }
1019
1020 try {
1021 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
1022 getMapSize(sUidPermissionMap)));
1023 } catch (ErrnoException e) {
1024 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
1025 return StatsManager.PULL_SKIP;
1026 }
1027 return StatsManager.PULL_SUCCESS;
1028 }
1029
Motomu Utsumi310850f2022-09-02 12:48:20 +09001030 private String permissionToString(int permissionMask) {
1031 if (permissionMask == PERMISSION_NONE) {
1032 return "PERMISSION_NONE";
1033 }
1034 if (permissionMask == PERMISSION_UNINSTALLED) {
1035 // PERMISSION_UNINSTALLED should never appear in the map
1036 return "PERMISSION_UNINSTALLED error!";
1037 }
1038
1039 final StringJoiner sj = new StringJoiner(" ");
1040 for (Pair<Integer, String> permission: PERMISSION_LIST) {
1041 final int permissionFlag = permission.first;
1042 final String permissionName = permission.second;
1043 if ((permissionMask & permissionFlag) != 0) {
1044 sj.add(permissionName);
1045 permissionMask &= ~permissionFlag;
1046 }
1047 }
1048 if (permissionMask != 0) {
1049 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
1050 }
1051 return sj.toString();
1052 }
1053
Motomu Utsumi956d86c2022-09-02 17:01:25 +09001054 private String matchToString(long matchMask) {
1055 if (matchMask == NO_MATCH) {
1056 return "NO_MATCH";
1057 }
1058
1059 final StringJoiner sj = new StringJoiner(" ");
1060 for (Pair<Long, String> match: MATCH_LIST) {
1061 final long matchFlag = match.first;
1062 final String matchName = match.second;
1063 if ((matchMask & matchFlag) != 0) {
1064 sj.add(matchName);
1065 matchMask &= ~matchFlag;
1066 }
1067 }
1068 if (matchMask != 0) {
1069 sj.add("UNKNOWN_MATCH(" + matchMask + ")");
1070 }
1071 return sj.toString();
1072 }
1073
Motomu Utsumi372c9b42022-09-02 19:02:56 +09001074 private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
1075 try {
1076 final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
1077 pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
1078 } catch (ErrnoException e) {
1079 pw.println("Failed to read ownerMatch configuration: " + e);
1080 }
1081 }
1082
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001083 private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
1084 try {
1085 final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
1086 final String currentStatsMap =
1087 (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
1088 pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
1089 } catch (ErrnoException e) {
1090 pw.println("Falied to read current statsMap configuration: " + e);
1091 }
1092 }
1093
Ken Chene6d511f2022-01-25 11:10:42 +08001094 /**
1095 * Dump BPF maps
1096 *
Motomu Utsumi310850f2022-09-02 12:48:20 +09001097 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +08001098 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +09001099 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +08001100 * @throws IOException when file descriptor is invalid.
1101 * @throws ServiceSpecificException when the method is called on an unsupported device.
1102 */
Motomu Utsumi310850f2022-09-02 12:48:20 +09001103 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +08001104 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00001105 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +08001106 throw new ServiceSpecificException(
1107 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
1108 + " devices, use dumpsys netd trafficcontroller instead.");
1109 }
Motomu Utsumidf8d2992022-09-01 17:08:27 +09001110 mDeps.nativeDump(fd, verbose);
Motomu Utsumi310850f2022-09-02 12:48:20 +09001111
Motomu Utsumi316d0572022-09-15 13:24:48 +09001112 pw.println();
1113 pw.println("sEnableJavaBpfMap: " + sEnableJavaBpfMap);
Motomu Utsumi310850f2022-09-02 12:48:20 +09001114 if (verbose) {
Motomu Utsumief546a92022-10-05 16:42:29 +09001115 pw.println();
1116 pw.println("BPF map content:");
1117 pw.increaseIndent();
1118
Motomu Utsumi372c9b42022-09-02 19:02:56 +09001119 dumpOwnerMatchConfig(pw);
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001120 dumpCurrentStatsMapConfig(pw);
1121 pw.println();
1122
Motomu Utsumief546a92022-10-05 16:42:29 +09001123 // TODO: Remove CookieTagMap content dump
1124 // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
1125 // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
1126 // need to be updated before remove the dump from BpfNetMaps.
1127 BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
1128 (key, value) -> "cookie=" + key.socketCookie
1129 + " tag=0x" + Long.toHexString(value.tag)
1130 + " uid=" + value.uid);
Motomu Utsumi956d86c2022-09-02 17:01:25 +09001131 BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
1132 (uid, match) -> {
1133 if ((match.rule & IIF_MATCH) != 0) {
1134 // TODO: convert interface index to interface name by IfaceIndexNameMap
1135 return uid.val + " " + matchToString(match.rule) + " " + match.iif;
1136 } else {
1137 return uid.val + " " + matchToString(match.rule);
1138 }
1139 });
Motomu Utsumi310850f2022-09-02 12:48:20 +09001140 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
1141 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
Motomu Utsumief546a92022-10-05 16:42:29 +09001142 pw.decreaseIndent();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001143 }
Ken Chene6d511f2022-01-25 11:10:42 +08001144 }
1145
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001146 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi3af8f0e2022-09-02 23:42:13 +09001147 private static native void native_init(boolean startSkDestroyListener);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001148
1149 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001150 private native int native_addNaughtyApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001151
1152 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001153 private native int native_removeNaughtyApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001154
1155 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001156 private native int native_addNiceApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001157
1158 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001159 private native int native_removeNiceApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001160
1161 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi114cd9c2022-08-01 02:08:35 +00001162 private native int native_setChildChain(int childChain, boolean enable);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001163
1164 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001165 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001166
1167 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001168 private native int native_setUidRule(int childChain, int uid, int firewallRule);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001169
1170 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001171 private native int native_addUidInterfaceRules(String ifName, int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001172
1173 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001174 private native int native_removeUidInterfaceRules(int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001175
1176 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +00001177 private native int native_updateUidLockdownRule(int uid, boolean add);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001178
1179 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001180 private native int native_swapActiveStatsMap();
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001181
1182 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma2fde98c2022-01-17 18:04:05 +08001183 private native void native_setPermissionForUids(int permissions, int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001184
1185 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumidf8d2992022-09-01 17:08:27 +09001186 private static native void native_dump(FileDescriptor fd, boolean verbose);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001187
1188 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi7abeaa42022-07-20 07:54:18 +00001189 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001190}