blob: aea21036bda8470d0b033d8c6b145692b95eb188 [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;
43import android.os.RemoteException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080044import android.os.ServiceSpecificException;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000045import android.provider.DeviceConfig;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000046import android.system.ErrnoException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080047import android.system.Os;
Motomu Utsumi1a477b02022-08-23 15:14:56 +090048import android.util.ArraySet;
Motomu Utsumi310850f2022-09-02 12:48:20 +090049import android.util.IndentingPrintWriter;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080050import android.util.Log;
Motomu Utsumi310850f2022-09-02 12:48:20 +090051import android.util.Pair;
Motomu Utsumi166f9662022-09-01 10:35:29 +090052import android.util.StatsEvent;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080053
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000054import com.android.internal.annotations.VisibleForTesting;
Motomu Utsumi166f9662022-09-01 10:35:29 +090055import com.android.modules.utils.BackgroundThread;
Ken Chenf5f51332022-01-28 10:08:16 +080056import com.android.modules.utils.build.SdkLevel;
Motomu Utsumi310850f2022-09-02 12:48:20 +090057import com.android.net.module.util.BpfDump;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000058import com.android.net.module.util.BpfMap;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000059import com.android.net.module.util.DeviceConfigUtils;
Motomu Utsumi73599a52022-08-24 11:59:21 +090060import com.android.net.module.util.IBpfMap;
Motomu Utsumi166f9662022-09-01 10:35:29 +090061import com.android.net.module.util.Struct;
Maciej Żenczykowski785793f2022-09-17 02:35:20 +000062import com.android.net.module.util.Struct.S32;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000063import com.android.net.module.util.Struct.U32;
Motomu Utsumi65271202022-07-05 08:21:41 +000064import com.android.net.module.util.Struct.U8;
Motomu Utsumib9548862022-09-06 16:30:05 +090065import com.android.net.module.util.bpf.CookieTagMapKey;
66import com.android.net.module.util.bpf.CookieTagMapValue;
Ken Chenf5f51332022-01-28 10:08:16 +080067
Ken Chene6d511f2022-01-25 11:10:42 +080068import java.io.FileDescriptor;
69import java.io.IOException;
Motomu Utsumi310850f2022-09-02 12:48:20 +090070import java.util.Arrays;
Motomu Utsumi166f9662022-09-01 10:35:29 +090071import java.util.List;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000072import java.util.Set;
Motomu Utsumi310850f2022-09-02 12:48:20 +090073import java.util.StringJoiner;
Ken Chene6d511f2022-01-25 11:10:42 +080074
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080075/**
76 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
77 *
78 * {@hide}
79 */
80public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000081 private static final boolean PRE_T = !SdkLevel.isAtLeastT();
82 static {
83 if (!PRE_T) {
84 System.loadLibrary("service-connectivity");
85 }
86 }
87
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080088 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +080089 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000090 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +080091 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +080092 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080093
Motomu Utsumif688eeb2022-07-22 03:47:35 +000094 private static Boolean sEnableJavaBpfMap = null;
95 private static final String BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP =
96 "bpf_net_maps_enable_java_bpf_map";
97
Motomu Utsumi18b287d2022-06-19 10:45:30 +000098 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
99 // This entry is not accessed by others.
100 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
101 private static final Object sUidRulesConfigBpfMapLock = new Object();
102
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000103 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
104 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
105 // BpfNetMaps is an only writer of this entry.
106 private static final Object sCurrentStatsMapConfigLock = new Object();
107
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000108 private static final String CONFIGURATION_MAP_PATH =
109 "/sys/fs/bpf/netd_shared/map_netd_configuration_map";
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000110 private static final String UID_OWNER_MAP_PATH =
111 "/sys/fs/bpf/netd_shared/map_netd_uid_owner_map";
Motomu Utsumi65271202022-07-05 08:21:41 +0000112 private static final String UID_PERMISSION_MAP_PATH =
113 "/sys/fs/bpf/netd_shared/map_netd_uid_permission_map";
Motomu Utsumib9548862022-09-06 16:30:05 +0900114 private static final String COOKIE_TAG_MAP_PATH =
115 "/sys/fs/bpf/netd_shared/map_netd_cookie_tag_map";
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000116 private static final S32 UID_RULES_CONFIGURATION_KEY = new S32(0);
117 private static final S32 CURRENT_STATS_MAP_CONFIGURATION_KEY = new S32(1);
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000118 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
119 private static final long STATS_SELECT_MAP_A = 0;
120 private static final long STATS_SELECT_MAP_B = 1;
121
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000122 private static IBpfMap<S32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000123 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000124 private static IBpfMap<S32, UidOwnerValue> sUidOwnerMap = null;
125 private static IBpfMap<S32, U8> sUidPermissionMap = null;
Motomu Utsumib9548862022-09-06 16:30:05 +0900126 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> sCookieTagMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000127
128 // LINT.IfChange(match_type)
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000129 @VisibleForTesting public static final long NO_MATCH = 0;
130 @VisibleForTesting public static final long HAPPY_BOX_MATCH = (1 << 0);
131 @VisibleForTesting public static final long PENALTY_BOX_MATCH = (1 << 1);
132 @VisibleForTesting public static final long DOZABLE_MATCH = (1 << 2);
133 @VisibleForTesting public static final long STANDBY_MATCH = (1 << 3);
134 @VisibleForTesting public static final long POWERSAVE_MATCH = (1 << 4);
135 @VisibleForTesting public static final long RESTRICTED_MATCH = (1 << 5);
136 @VisibleForTesting public static final long LOW_POWER_STANDBY_MATCH = (1 << 6);
137 @VisibleForTesting public static final long IIF_MATCH = (1 << 7);
138 @VisibleForTesting public static final long LOCKDOWN_VPN_MATCH = (1 << 8);
139 @VisibleForTesting public static final long OEM_DENY_1_MATCH = (1 << 9);
140 @VisibleForTesting public static final long OEM_DENY_2_MATCH = (1 << 10);
141 @VisibleForTesting public static final long OEM_DENY_3_MATCH = (1 << 11);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000142 // LINT.ThenChange(packages/modules/Connectivity/bpf_progs/bpf_shared.h)
143
Motomu Utsumi310850f2022-09-02 12:48:20 +0900144 private static final List<Pair<Integer, String>> PERMISSION_LIST = Arrays.asList(
145 Pair.create(PERMISSION_INTERNET, "PERMISSION_INTERNET"),
146 Pair.create(PERMISSION_UPDATE_DEVICE_STATS, "PERMISSION_UPDATE_DEVICE_STATS")
147 );
Motomu Utsumi956d86c2022-09-02 17:01:25 +0900148 private static final List<Pair<Long, String>> MATCH_LIST = Arrays.asList(
149 Pair.create(HAPPY_BOX_MATCH, "HAPPY_BOX_MATCH"),
150 Pair.create(PENALTY_BOX_MATCH, "PENALTY_BOX_MATCH"),
151 Pair.create(DOZABLE_MATCH, "DOZABLE_MATCH"),
152 Pair.create(STANDBY_MATCH, "STANDBY_MATCH"),
153 Pair.create(POWERSAVE_MATCH, "POWERSAVE_MATCH"),
154 Pair.create(RESTRICTED_MATCH, "RESTRICTED_MATCH"),
155 Pair.create(LOW_POWER_STANDBY_MATCH, "LOW_POWER_STANDBY_MATCH"),
156 Pair.create(IIF_MATCH, "IIF_MATCH"),
157 Pair.create(LOCKDOWN_VPN_MATCH, "LOCKDOWN_VPN_MATCH"),
158 Pair.create(OEM_DENY_1_MATCH, "OEM_DENY_1_MATCH"),
159 Pair.create(OEM_DENY_2_MATCH, "OEM_DENY_2_MATCH"),
160 Pair.create(OEM_DENY_3_MATCH, "OEM_DENY_3_MATCH")
161 );
Motomu Utsumi310850f2022-09-02 12:48:20 +0900162
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000163 /**
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000164 * Set sEnableJavaBpfMap for test.
165 */
166 @VisibleForTesting
167 public static void setEnableJavaBpfMapForTest(boolean enable) {
168 sEnableJavaBpfMap = enable;
169 }
170
171 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000172 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000173 */
174 @VisibleForTesting
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000175 public static void setConfigurationMapForTest(IBpfMap<S32, U32> configurationMap) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000176 sConfigurationMap = configurationMap;
177 }
178
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000179 /**
180 * Set uidOwnerMap for test.
181 */
182 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000183 public static void setUidOwnerMapForTest(IBpfMap<S32, UidOwnerValue> uidOwnerMap) {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000184 sUidOwnerMap = uidOwnerMap;
185 }
186
Motomu Utsumi65271202022-07-05 08:21:41 +0000187 /**
188 * Set uidPermissionMap for test.
189 */
190 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000191 public static void setUidPermissionMapForTest(IBpfMap<S32, U8> uidPermissionMap) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000192 sUidPermissionMap = uidPermissionMap;
193 }
194
Motomu Utsumib9548862022-09-06 16:30:05 +0900195 /**
196 * Set cookieTagMap for test.
197 */
198 @VisibleForTesting
199 public static void setCookieTagMapForTest(
200 IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap) {
201 sCookieTagMap = cookieTagMap;
202 }
203
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000204 private static IBpfMap<S32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000205 try {
206 return new BpfMap<>(
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000207 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U32.class);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000208 } catch (ErrnoException e) {
209 throw new IllegalStateException("Cannot open netd configuration map", e);
210 }
211 }
212
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000213 private static IBpfMap<S32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000214 try {
215 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000216 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, UidOwnerValue.class);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000217 } catch (ErrnoException e) {
218 throw new IllegalStateException("Cannot open uid owner map", e);
219 }
220 }
221
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000222 private static IBpfMap<S32, U8> getUidPermissionMap() {
Motomu Utsumi65271202022-07-05 08:21:41 +0000223 try {
224 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000225 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
Motomu Utsumi65271202022-07-05 08:21:41 +0000226 } catch (ErrnoException e) {
227 throw new IllegalStateException("Cannot open uid permission map", e);
228 }
229 }
230
Motomu Utsumib9548862022-09-06 16:30:05 +0900231 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
232 try {
233 return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,
234 CookieTagMapKey.class, CookieTagMapValue.class);
235 } catch (ErrnoException e) {
236 throw new IllegalStateException("Cannot open cookie tag map", e);
237 }
238 }
239
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000240 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000241 if (sConfigurationMap == null) {
242 sConfigurationMap = getConfigurationMap();
243 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000244 try {
245 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
246 new U32(UID_RULES_DEFAULT_CONFIGURATION));
247 } catch (ErrnoException e) {
248 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
249 }
250 try {
251 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
252 new U32(STATS_SELECT_MAP_A));
253 } catch (ErrnoException e) {
254 throw new IllegalStateException("Failed to initialize current stats configuration", e);
255 }
256
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000257 if (sUidOwnerMap == null) {
258 sUidOwnerMap = getUidOwnerMap();
259 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000260 try {
261 sUidOwnerMap.clear();
262 } catch (ErrnoException e) {
263 throw new IllegalStateException("Failed to initialize uid owner map", e);
264 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000265
266 if (sUidPermissionMap == null) {
267 sUidPermissionMap = getUidPermissionMap();
268 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900269
270 if (sCookieTagMap == null) {
271 sCookieTagMap = getCookieTagMap();
272 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000273 }
274
Ken Chenf5f51332022-01-28 10:08:16 +0800275 /**
276 * Initializes the class if it is not already initialized. This method will open maps but not
277 * cause any other effects. This method may be called multiple times on any thread.
278 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000279 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800280 if (sInitialized) return;
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000281 if (sEnableJavaBpfMap == null) {
282 sEnableJavaBpfMap = DeviceConfigUtils.isFeatureEnabled(context,
283 DeviceConfig.NAMESPACE_TETHERING, BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP,
284 SdkLevel.isAtLeastU() /* defaultValue */);
285 }
286 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
287
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000288 initBpfMaps();
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900289 native_init(!sEnableJavaBpfMap /* startSkDestroyListener */);
Ken Chenf5f51332022-01-28 10:08:16 +0800290 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800291 }
292
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900293 public boolean isSkDestroyListenerRunning() {
294 return !sEnableJavaBpfMap;
295 }
296
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000297 /**
298 * Dependencies of BpfNetMaps, for injection in tests.
299 */
300 @VisibleForTesting
301 public static class Dependencies {
302 /**
303 * Get interface index.
304 */
305 public int getIfIndex(final String ifName) {
306 return Os.if_nametoindex(ifName);
307 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000308
309 /**
310 * Call synchronize_rcu()
311 */
312 public int synchronizeKernelRCU() {
313 return native_synchronizeKernelRCU();
314 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900315
316 /**
317 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
318 */
319 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
320 final int uidPermissionMapSize) {
321 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
322 uidOwnerMapSize, uidPermissionMapSize);
323 }
Motomu Utsumidf8d2992022-09-01 17:08:27 +0900324
325 /**
326 * Call native_dump
327 */
328 public void nativeDump(final FileDescriptor fd, final boolean verbose) {
329 native_dump(fd, verbose);
330 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000331 }
332
markchien49e944c2022-03-01 15:22:20 +0800333 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000334 public BpfNetMaps(final Context context) {
335 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800336
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000337 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800338 }
339
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000340 public BpfNetMaps(final Context context, final INetd netd) {
341 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000342 }
343
344 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000345 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000346 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000347 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000348 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800349 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000350 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800351 }
352
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000353 /**
354 * Get corresponding match from firewall chain.
355 */
356 @VisibleForTesting
357 public long getMatchByFirewallChain(final int chain) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000358 switch (chain) {
359 case FIREWALL_CHAIN_DOZABLE:
360 return DOZABLE_MATCH;
361 case FIREWALL_CHAIN_STANDBY:
362 return STANDBY_MATCH;
363 case FIREWALL_CHAIN_POWERSAVE:
364 return POWERSAVE_MATCH;
365 case FIREWALL_CHAIN_RESTRICTED:
366 return RESTRICTED_MATCH;
367 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
368 return LOW_POWER_STANDBY_MATCH;
369 case FIREWALL_CHAIN_OEM_DENY_1:
370 return OEM_DENY_1_MATCH;
371 case FIREWALL_CHAIN_OEM_DENY_2:
372 return OEM_DENY_2_MATCH;
373 case FIREWALL_CHAIN_OEM_DENY_3:
374 return OEM_DENY_3_MATCH;
375 default:
376 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000377 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000378 }
379
380 /**
381 * Get if the chain is allow list or not.
382 *
383 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
384 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
385 */
386 @VisibleForTesting
387 public boolean isFirewallAllowList(final int chain) {
388 switch (chain) {
389 case FIREWALL_CHAIN_DOZABLE:
390 case FIREWALL_CHAIN_POWERSAVE:
391 case FIREWALL_CHAIN_RESTRICTED:
392 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
393 return true;
394 case FIREWALL_CHAIN_STANDBY:
395 case FIREWALL_CHAIN_OEM_DENY_1:
396 case FIREWALL_CHAIN_OEM_DENY_2:
397 case FIREWALL_CHAIN_OEM_DENY_3:
398 return false;
399 default:
400 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
401 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000402 }
403
Ken Chenf5f51332022-01-28 10:08:16 +0800404 private void maybeThrow(final int err, final String msg) {
405 if (err != 0) {
406 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
407 }
408 }
409
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000410 private void throwIfPreT(final String msg) {
411 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000412 throw new UnsupportedOperationException(msg);
413 }
414 }
415
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000416 private void removeRule(final int uid, final long match, final String caller) {
417 try {
418 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000419 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000420
421 if (oldMatch == null) {
422 throw new ServiceSpecificException(ENOENT,
423 "sUidOwnerMap does not have entry for uid: " + uid);
424 }
425
426 final UidOwnerValue newMatch = new UidOwnerValue(
427 (match == IIF_MATCH) ? 0 : oldMatch.iif,
428 oldMatch.rule & ~match
429 );
430
431 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000432 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000433 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000434 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000435 }
436 }
437 } catch (ErrnoException e) {
438 throw new ServiceSpecificException(e.errno,
439 caller + " failed to remove rule: " + Os.strerror(e.errno));
440 }
441 }
442
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000443 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000444 if (match != IIF_MATCH && iif != 0) {
445 throw new ServiceSpecificException(EINVAL,
446 "Non-interface match must have zero interface index");
447 }
448
449 try {
450 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000451 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000452
453 final UidOwnerValue newMatch;
454 if (oldMatch != null) {
455 newMatch = new UidOwnerValue(
456 (match == IIF_MATCH) ? iif : oldMatch.iif,
457 oldMatch.rule | match
458 );
459 } else {
460 newMatch = new UidOwnerValue(
461 iif,
462 match
463 );
464 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000465 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000466 }
467 } catch (ErrnoException e) {
468 throw new ServiceSpecificException(e.errno,
469 caller + " failed to add rule: " + Os.strerror(e.errno));
470 }
471 }
472
473 private void addRule(final int uid, final long match, final String caller) {
474 addRule(uid, match, 0 /* iif */, caller);
475 }
476
Ken Chenf5f51332022-01-28 10:08:16 +0800477 /**
478 * Add naughty app bandwidth rule for specific app
479 *
480 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800481 * @throws ServiceSpecificException in case of failure, with an error code indicating the
482 * cause of the failure.
483 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900484 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000485 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000486
487 if (sEnableJavaBpfMap) {
488 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
489 } else {
490 final int err = native_addNaughtyApp(uid);
491 maybeThrow(err, "Unable to add naughty app");
492 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800493 }
494
Ken Chenf5f51332022-01-28 10:08:16 +0800495 /**
496 * Remove naughty app bandwidth rule for specific app
497 *
498 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800499 * @throws ServiceSpecificException in case of failure, with an error code indicating the
500 * cause of the failure.
501 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900502 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000503 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000504
505 if (sEnableJavaBpfMap) {
506 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
507 } else {
508 final int err = native_removeNaughtyApp(uid);
509 maybeThrow(err, "Unable to remove naughty app");
510 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800511 }
512
Ken Chenf5f51332022-01-28 10:08:16 +0800513 /**
514 * Add nice app bandwidth rule for specific app
515 *
516 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800517 * @throws ServiceSpecificException in case of failure, with an error code indicating the
518 * cause of the failure.
519 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900520 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000521 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000522
523 if (sEnableJavaBpfMap) {
524 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
525 } else {
526 final int err = native_addNiceApp(uid);
527 maybeThrow(err, "Unable to add nice app");
528 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800529 }
530
Ken Chenf5f51332022-01-28 10:08:16 +0800531 /**
532 * Remove nice app bandwidth rule for specific app
533 *
534 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800535 * @throws ServiceSpecificException in case of failure, with an error code indicating the
536 * cause of the failure.
537 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900538 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000539 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000540
541 if (sEnableJavaBpfMap) {
542 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
543 } else {
544 final int err = native_removeNiceApp(uid);
545 maybeThrow(err, "Unable to remove nice app");
546 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800547 }
548
Ken Chenf5f51332022-01-28 10:08:16 +0800549 /**
550 * Set target firewall child chain
551 *
552 * @param childChain target chain to enable
553 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000554 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800555 * @throws ServiceSpecificException in case of failure, with an error code indicating the
556 * cause of the failure.
557 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900558 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000559 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000560
Motomu Utsumie057dd42022-08-03 01:23:49 +0000561 if (sEnableJavaBpfMap) {
562 final long match = getMatchByFirewallChain(childChain);
563 try {
564 synchronized (sUidRulesConfigBpfMapLock) {
565 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
566 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
567 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
568 }
569 } catch (ErrnoException e) {
570 throw new ServiceSpecificException(e.errno,
571 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000572 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000573 } else {
574 final int err = native_setChildChain(childChain, enable);
575 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000576 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800577 }
578
579 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000580 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000581 *
582 * @param childChain target chain
583 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
584 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000585 * @throws ServiceSpecificException in case of failure, with an error code indicating the
586 * cause of the failure.
587 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000588 public boolean isChainEnabled(final int childChain) {
589 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000590
591 final long match = getMatchByFirewallChain(childChain);
592 try {
593 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000594 return (config.val & match) != 0;
595 } catch (ErrnoException e) {
596 throw new ServiceSpecificException(e.errno,
597 "Unable to get firewall chain status: " + Os.strerror(e.errno));
598 }
599 }
600
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900601 private Set<Integer> asSet(final int[] uids) {
602 final Set<Integer> uidSet = new ArraySet<>();
603 for (final int uid: uids) {
604 uidSet.add(uid);
605 }
606 return uidSet;
607 }
608
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000609 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800610 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000611 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800612 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000613 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800614 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000615 * @throws UnsupportedOperationException if called on pre-T devices.
616 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800617 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000618 public void replaceUidChain(final int chain, final int[] uids) {
619 throwIfPreT("replaceUidChain is not available on pre-T devices");
620
Motomu Utsumic7c16852022-08-03 06:51:41 +0000621 if (sEnableJavaBpfMap) {
622 final long match;
623 try {
624 match = getMatchByFirewallChain(chain);
625 } catch (ServiceSpecificException e) {
626 // Throws IllegalArgumentException to keep the behavior of
627 // ConnectivityManager#replaceFirewallChain API
628 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000629 }
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900630 final Set<Integer> uidSet = asSet(uids);
631 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
Motomu Utsumic7c16852022-08-03 06:51:41 +0000632 try {
633 synchronized (sUidOwnerMap) {
634 sUidOwnerMap.forEach((uid, config) -> {
635 // config could be null if there is a concurrent entry deletion.
Motomu Utsumi8e420ea2022-08-24 18:03:30 +0900636 // http://b/220084230. But sUidOwnerMap update must be done while holding a
637 // lock, so this should not happen.
638 if (config == null) {
639 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
640 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
Motomu Utsumic7c16852022-08-03 06:51:41 +0000641 uidSetToRemoveRule.add((int) uid.val);
642 }
643 });
644
645 for (final int uid : uidSetToRemoveRule) {
646 removeRule(uid, match, "replaceUidChain");
647 }
648 for (final int uid : uids) {
649 addRule(uid, match, "replaceUidChain");
650 }
651 }
652 } catch (ErrnoException | ServiceSpecificException e) {
653 Log.e(TAG, "replaceUidChain failed: " + e);
654 }
655 } else {
656 final int err;
657 switch (chain) {
658 case FIREWALL_CHAIN_DOZABLE:
659 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
660 break;
661 case FIREWALL_CHAIN_STANDBY:
662 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
663 break;
664 case FIREWALL_CHAIN_POWERSAVE:
665 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
666 break;
667 case FIREWALL_CHAIN_RESTRICTED:
668 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
669 break;
670 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
671 err = native_replaceUidChain(
672 "fw_low_power_standby", true /* isAllowList */, uids);
673 break;
674 case FIREWALL_CHAIN_OEM_DENY_1:
675 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
676 break;
677 case FIREWALL_CHAIN_OEM_DENY_2:
678 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
679 break;
680 case FIREWALL_CHAIN_OEM_DENY_3:
681 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
682 break;
683 default:
684 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
685 + chain);
686 }
687 if (err != 0) {
688 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
689 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800690 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800691 }
692
Ken Chenf5f51332022-01-28 10:08:16 +0800693 /**
694 * Set firewall rule for uid
695 *
696 * @param childChain target chain
697 * @param uid uid to allow/deny
698 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800699 * @throws ServiceSpecificException in case of failure, with an error code indicating the
700 * cause of the failure.
701 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900702 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000703 throwIfPreT("setUidRule is not available on pre-T devices");
704
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000705 if (sEnableJavaBpfMap) {
706 final long match = getMatchByFirewallChain(childChain);
707 final boolean isAllowList = isFirewallAllowList(childChain);
708 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
709 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000710
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000711 if (add) {
712 addRule(uid, match, "setUidRule");
713 } else {
714 removeRule(uid, match, "setUidRule");
715 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000716 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000717 final int err = native_setUidRule(childChain, uid, firewallRule);
718 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000719 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800720 }
721
722 /**
723 * Add ingress interface filtering rules to a list of UIDs
724 *
725 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
726 * allowed interface and loopback to be sent to the list of UIDs.
727 *
728 * Calling this method on one or more UIDs with an existing filtering rule but a different
729 * interface name will result in the filtering rule being updated to allow the new interface
730 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
731 *
732 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800733 * be received.
734 * @param uids an array of UIDs which the filtering rules will be set
735 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800736 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800737 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800738 */
Ken Chenf5f51332022-01-28 10:08:16 +0800739 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000740 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800741 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800742 return;
743 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000744
745 if (sEnableJavaBpfMap) {
746 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
747 // ifIndex is set to 0.
748 final int ifIndex;
749 if (ifName == null) {
750 ifIndex = 0;
751 } else {
752 ifIndex = mDeps.getIfIndex(ifName);
753 if (ifIndex == 0) {
754 throw new ServiceSpecificException(ENODEV,
755 "Failed to get index of interface " + ifName);
756 }
757 }
758 for (final int uid : uids) {
759 try {
760 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
761 } catch (ServiceSpecificException e) {
762 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
763 }
764 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000765 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000766 final int err = native_addUidInterfaceRules(ifName, uids);
767 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000768 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800769 }
770
771 /**
772 * Remove ingress interface filtering rules from a list of UIDs
773 *
774 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
775 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
776 *
777 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800778 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800779 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800780 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800781 */
Ken Chenf5f51332022-01-28 10:08:16 +0800782 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000783 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800784 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800785 return;
786 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000787
788 if (sEnableJavaBpfMap) {
789 for (final int uid : uids) {
790 try {
791 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
792 } catch (ServiceSpecificException e) {
793 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
794 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000795 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000796 } else {
797 final int err = native_removeUidInterfaceRules(uids);
798 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000799 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800800 }
801
Ken Chenf5f51332022-01-28 10:08:16 +0800802 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000803 * Update lockdown rule for uid
804 *
805 * @param uid target uid to add/remove the rule
806 * @param add {@code true} to add the rule, {@code false} to remove the rule.
807 * @throws ServiceSpecificException in case of failure, with an error code indicating the
808 * cause of the failure.
809 */
810 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000811 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000812
813 if (sEnableJavaBpfMap) {
814 if (add) {
815 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
816 } else {
817 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
818 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000819 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000820 final int err = native_updateUidLockdownRule(uid, add);
821 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000822 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000823 }
824
825 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800826 * Request netd to change the current active network stats map.
827 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000828 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800829 * @throws ServiceSpecificException in case of failure, with an error code indicating the
830 * cause of the failure.
831 */
markchien49e944c2022-03-01 15:22:20 +0800832 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000833 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
834
835 if (sEnableJavaBpfMap) {
836 try {
837 synchronized (sCurrentStatsMapConfigLock) {
838 final long config = sConfigurationMap.getValue(
839 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
840 final long newConfig = (config == STATS_SELECT_MAP_A)
841 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
842 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
843 new U32(newConfig));
844 }
845 } catch (ErrnoException e) {
846 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
847 }
848
849 // After changing the config, it's needed to make sure all the current running eBPF
850 // programs are finished and all the CPUs are aware of this config change before the old
851 // map is modified. So special hack is needed here to wait for the kernel to do a
852 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
853 // be available to all cores and the next eBPF programs triggered inside the kernel will
854 // use the new map configuration. So once this function returns it is safe to modify the
855 // old stats map without concerning about race between the kernel and userspace.
856 final int err = mDeps.synchronizeKernelRCU();
857 maybeThrow(err, "synchronizeKernelRCU failed");
858 } else {
859 final int err = native_swapActiveStatsMap();
860 maybeThrow(err, "Unable to swap active stats map");
861 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800862 }
863
Ken Chenf5f51332022-01-28 10:08:16 +0800864 /**
865 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
866 * specified. Or remove all permissions from the uids.
867 *
868 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
869 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
870 * revoke all permissions for the uids.
871 * @param uids uid of users to grant permission
872 * @throws RemoteException when netd has crashed.
873 */
874 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000875 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800876 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800877 return;
878 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000879
880 if (sEnableJavaBpfMap) {
881 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
882 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
883 for (final int uid : uids) {
884 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000885 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000886 } catch (ErrnoException e) {
887 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
888 }
889 }
890 return;
891 }
892
893 for (final int uid : uids) {
894 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000895 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
Motomu Utsumi65271202022-07-05 08:21:41 +0000896 } catch (ErrnoException e) {
897 Log.e(TAG, "Failed to set permission "
898 + permissions + " to uid " + uid + ": " + e);
899 }
900 }
901 } else {
902 native_setPermissionForUids(permissions, uids);
903 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800904 }
905
Motomu Utsumi166f9662022-09-01 10:35:29 +0900906 /** Register callback for statsd to pull atom. */
907 public void setPullAtomCallback(final Context context) {
908 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
909
910 final StatsManager statsManager = context.getSystemService(StatsManager.class);
911 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
912 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
913 }
914
915 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
916 throws ErrnoException {
917 // forEach could restart iteration from the beginning if there is a concurrent entry
918 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
919 // So using Set to count the number of entry in the map.
920 Set<K> keySet = new ArraySet<>();
921 map.forEach((k, v) -> keySet.add(k));
922 return keySet.size();
923 }
924
925 /** Callback for StatsManager#setPullAtomCallback */
926 @VisibleForTesting
927 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
928 if (atomTag != NETWORK_BPF_MAP_INFO) {
929 Log.e(TAG, "Unexpected atom tag: " + atomTag);
930 return StatsManager.PULL_SKIP;
931 }
932
933 try {
934 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
935 getMapSize(sUidPermissionMap)));
936 } catch (ErrnoException e) {
937 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
938 return StatsManager.PULL_SKIP;
939 }
940 return StatsManager.PULL_SUCCESS;
941 }
942
Motomu Utsumi310850f2022-09-02 12:48:20 +0900943 private String permissionToString(int permissionMask) {
944 if (permissionMask == PERMISSION_NONE) {
945 return "PERMISSION_NONE";
946 }
947 if (permissionMask == PERMISSION_UNINSTALLED) {
948 // PERMISSION_UNINSTALLED should never appear in the map
949 return "PERMISSION_UNINSTALLED error!";
950 }
951
952 final StringJoiner sj = new StringJoiner(" ");
953 for (Pair<Integer, String> permission: PERMISSION_LIST) {
954 final int permissionFlag = permission.first;
955 final String permissionName = permission.second;
956 if ((permissionMask & permissionFlag) != 0) {
957 sj.add(permissionName);
958 permissionMask &= ~permissionFlag;
959 }
960 }
961 if (permissionMask != 0) {
962 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
963 }
964 return sj.toString();
965 }
966
Motomu Utsumi956d86c2022-09-02 17:01:25 +0900967 private String matchToString(long matchMask) {
968 if (matchMask == NO_MATCH) {
969 return "NO_MATCH";
970 }
971
972 final StringJoiner sj = new StringJoiner(" ");
973 for (Pair<Long, String> match: MATCH_LIST) {
974 final long matchFlag = match.first;
975 final String matchName = match.second;
976 if ((matchMask & matchFlag) != 0) {
977 sj.add(matchName);
978 matchMask &= ~matchFlag;
979 }
980 }
981 if (matchMask != 0) {
982 sj.add("UNKNOWN_MATCH(" + matchMask + ")");
983 }
984 return sj.toString();
985 }
986
Motomu Utsumi372c9b42022-09-02 19:02:56 +0900987 private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
988 try {
989 final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
990 pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
991 } catch (ErrnoException e) {
992 pw.println("Failed to read ownerMatch configuration: " + e);
993 }
994 }
995
Motomu Utsumic675d6f2022-09-02 18:15:25 +0900996 private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
997 try {
998 final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
999 final String currentStatsMap =
1000 (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
1001 pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
1002 } catch (ErrnoException e) {
1003 pw.println("Falied to read current statsMap configuration: " + e);
1004 }
1005 }
1006
Ken Chene6d511f2022-01-25 11:10:42 +08001007 /**
1008 * Dump BPF maps
1009 *
Motomu Utsumi310850f2022-09-02 12:48:20 +09001010 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +08001011 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +09001012 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +08001013 * @throws IOException when file descriptor is invalid.
1014 * @throws ServiceSpecificException when the method is called on an unsupported device.
1015 */
Motomu Utsumi310850f2022-09-02 12:48:20 +09001016 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +08001017 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00001018 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +08001019 throw new ServiceSpecificException(
1020 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
1021 + " devices, use dumpsys netd trafficcontroller instead.");
1022 }
Motomu Utsumidf8d2992022-09-01 17:08:27 +09001023 mDeps.nativeDump(fd, verbose);
Motomu Utsumi310850f2022-09-02 12:48:20 +09001024
Motomu Utsumi316d0572022-09-15 13:24:48 +09001025 pw.println();
1026 pw.println("sEnableJavaBpfMap: " + sEnableJavaBpfMap);
Motomu Utsumi310850f2022-09-02 12:48:20 +09001027 if (verbose) {
Motomu Utsumief546a92022-10-05 16:42:29 +09001028 pw.println();
1029 pw.println("BPF map content:");
1030 pw.increaseIndent();
1031
Motomu Utsumi372c9b42022-09-02 19:02:56 +09001032 dumpOwnerMatchConfig(pw);
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001033 dumpCurrentStatsMapConfig(pw);
1034 pw.println();
1035
Motomu Utsumief546a92022-10-05 16:42:29 +09001036 // TODO: Remove CookieTagMap content dump
1037 // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
1038 // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
1039 // need to be updated before remove the dump from BpfNetMaps.
1040 BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
1041 (key, value) -> "cookie=" + key.socketCookie
1042 + " tag=0x" + Long.toHexString(value.tag)
1043 + " uid=" + value.uid);
Motomu Utsumi956d86c2022-09-02 17:01:25 +09001044 BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
1045 (uid, match) -> {
1046 if ((match.rule & IIF_MATCH) != 0) {
1047 // TODO: convert interface index to interface name by IfaceIndexNameMap
1048 return uid.val + " " + matchToString(match.rule) + " " + match.iif;
1049 } else {
1050 return uid.val + " " + matchToString(match.rule);
1051 }
1052 });
Motomu Utsumi310850f2022-09-02 12:48:20 +09001053 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
1054 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
Motomu Utsumief546a92022-10-05 16:42:29 +09001055 pw.decreaseIndent();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001056 }
Ken Chene6d511f2022-01-25 11:10:42 +08001057 }
1058
Motomu Utsumi3af8f0e2022-09-02 23:42:13 +09001059 private static native void native_init(boolean startSkDestroyListener);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001060 private native int native_addNaughtyApp(int uid);
1061 private native int native_removeNaughtyApp(int uid);
1062 private native int native_addNiceApp(int uid);
1063 private native int native_removeNiceApp(int uid);
Motomu Utsumi114cd9c2022-08-01 02:08:35 +00001064 private native int native_setChildChain(int childChain, boolean enable);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001065 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
1066 private native int native_setUidRule(int childChain, int uid, int firewallRule);
1067 private native int native_addUidInterfaceRules(String ifName, int[] uids);
1068 private native int native_removeUidInterfaceRules(int[] uids);
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +00001069 private native int native_updateUidLockdownRule(int uid, boolean add);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001070 private native int native_swapActiveStatsMap();
Wayne Ma2fde98c2022-01-17 18:04:05 +08001071 private native void native_setPermissionForUids(int permissions, int[] uids);
Motomu Utsumidf8d2992022-09-01 17:08:27 +09001072 private static native void native_dump(FileDescriptor fd, boolean verbose);
Motomu Utsumi7abeaa42022-07-20 07:54:18 +00001073 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001074}