blob: 26ec37a2ae4bbeb3c6070c5ed0c57c6ab1766179 [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);
Maciej Żenczykowski513474c2022-12-08 16:20:43 +0000142 // LINT.ThenChange(packages/modules/Connectivity/bpf_progs/netd.h)
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000143
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) {
Maciej Żenczykowskie7ebb152022-12-27 10:57:38 +0000282 sEnableJavaBpfMap = SdkLevel.isAtLeastU() ||
283 DeviceConfigUtils.isFeatureEnabled(context,
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000284 DeviceConfig.NAMESPACE_TETHERING, BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP,
Maciej Żenczykowskie7ebb152022-12-27 10:57:38 +0000285 false /* defaultValue */);
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000286 }
287 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
288
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000289 initBpfMaps();
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900290 native_init(!sEnableJavaBpfMap /* startSkDestroyListener */);
Ken Chenf5f51332022-01-28 10:08:16 +0800291 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800292 }
293
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900294 public boolean isSkDestroyListenerRunning() {
295 return !sEnableJavaBpfMap;
296 }
297
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000298 /**
299 * Dependencies of BpfNetMaps, for injection in tests.
300 */
301 @VisibleForTesting
302 public static class Dependencies {
303 /**
304 * Get interface index.
305 */
306 public int getIfIndex(final String ifName) {
307 return Os.if_nametoindex(ifName);
308 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000309
310 /**
311 * Call synchronize_rcu()
312 */
313 public int synchronizeKernelRCU() {
314 return native_synchronizeKernelRCU();
315 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900316
317 /**
318 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
319 */
320 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
321 final int uidPermissionMapSize) {
322 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
323 uidOwnerMapSize, uidPermissionMapSize);
324 }
Motomu Utsumidf8d2992022-09-01 17:08:27 +0900325
326 /**
327 * Call native_dump
328 */
329 public void nativeDump(final FileDescriptor fd, final boolean verbose) {
330 native_dump(fd, verbose);
331 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000332 }
333
markchien49e944c2022-03-01 15:22:20 +0800334 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000335 public BpfNetMaps(final Context context) {
336 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800337
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000338 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800339 }
340
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000341 public BpfNetMaps(final Context context, final INetd netd) {
342 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000343 }
344
345 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000346 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000347 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000348 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000349 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800350 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000351 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800352 }
353
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000354 /**
355 * Get corresponding match from firewall chain.
356 */
357 @VisibleForTesting
358 public long getMatchByFirewallChain(final int chain) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000359 switch (chain) {
360 case FIREWALL_CHAIN_DOZABLE:
361 return DOZABLE_MATCH;
362 case FIREWALL_CHAIN_STANDBY:
363 return STANDBY_MATCH;
364 case FIREWALL_CHAIN_POWERSAVE:
365 return POWERSAVE_MATCH;
366 case FIREWALL_CHAIN_RESTRICTED:
367 return RESTRICTED_MATCH;
368 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
369 return LOW_POWER_STANDBY_MATCH;
370 case FIREWALL_CHAIN_OEM_DENY_1:
371 return OEM_DENY_1_MATCH;
372 case FIREWALL_CHAIN_OEM_DENY_2:
373 return OEM_DENY_2_MATCH;
374 case FIREWALL_CHAIN_OEM_DENY_3:
375 return OEM_DENY_3_MATCH;
376 default:
377 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000378 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000379 }
380
381 /**
382 * Get if the chain is allow list or not.
383 *
384 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
385 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
386 */
387 @VisibleForTesting
388 public boolean isFirewallAllowList(final int chain) {
389 switch (chain) {
390 case FIREWALL_CHAIN_DOZABLE:
391 case FIREWALL_CHAIN_POWERSAVE:
392 case FIREWALL_CHAIN_RESTRICTED:
393 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
394 return true;
395 case FIREWALL_CHAIN_STANDBY:
396 case FIREWALL_CHAIN_OEM_DENY_1:
397 case FIREWALL_CHAIN_OEM_DENY_2:
398 case FIREWALL_CHAIN_OEM_DENY_3:
399 return false;
400 default:
401 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
402 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000403 }
404
Ken Chenf5f51332022-01-28 10:08:16 +0800405 private void maybeThrow(final int err, final String msg) {
406 if (err != 0) {
407 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
408 }
409 }
410
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000411 private void throwIfPreT(final String msg) {
412 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000413 throw new UnsupportedOperationException(msg);
414 }
415 }
416
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000417 private void removeRule(final int uid, final long match, final String caller) {
418 try {
419 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000420 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000421
422 if (oldMatch == null) {
423 throw new ServiceSpecificException(ENOENT,
424 "sUidOwnerMap does not have entry for uid: " + uid);
425 }
426
427 final UidOwnerValue newMatch = new UidOwnerValue(
428 (match == IIF_MATCH) ? 0 : oldMatch.iif,
429 oldMatch.rule & ~match
430 );
431
432 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000433 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000434 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000435 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000436 }
437 }
438 } catch (ErrnoException e) {
439 throw new ServiceSpecificException(e.errno,
440 caller + " failed to remove rule: " + Os.strerror(e.errno));
441 }
442 }
443
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000444 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000445 if (match != IIF_MATCH && iif != 0) {
446 throw new ServiceSpecificException(EINVAL,
447 "Non-interface match must have zero interface index");
448 }
449
450 try {
451 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000452 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000453
454 final UidOwnerValue newMatch;
455 if (oldMatch != null) {
456 newMatch = new UidOwnerValue(
457 (match == IIF_MATCH) ? iif : oldMatch.iif,
458 oldMatch.rule | match
459 );
460 } else {
461 newMatch = new UidOwnerValue(
462 iif,
463 match
464 );
465 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000466 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000467 }
468 } catch (ErrnoException e) {
469 throw new ServiceSpecificException(e.errno,
470 caller + " failed to add rule: " + Os.strerror(e.errno));
471 }
472 }
473
474 private void addRule(final int uid, final long match, final String caller) {
475 addRule(uid, match, 0 /* iif */, caller);
476 }
477
Ken Chenf5f51332022-01-28 10:08:16 +0800478 /**
479 * Add naughty app bandwidth rule for specific app
480 *
481 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800482 * @throws ServiceSpecificException in case of failure, with an error code indicating the
483 * cause of the failure.
484 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900485 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000486 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000487
488 if (sEnableJavaBpfMap) {
489 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
490 } else {
491 final int err = native_addNaughtyApp(uid);
492 maybeThrow(err, "Unable to add naughty app");
493 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800494 }
495
Ken Chenf5f51332022-01-28 10:08:16 +0800496 /**
497 * Remove naughty app bandwidth rule for specific app
498 *
499 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800500 * @throws ServiceSpecificException in case of failure, with an error code indicating the
501 * cause of the failure.
502 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900503 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000504 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000505
506 if (sEnableJavaBpfMap) {
507 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
508 } else {
509 final int err = native_removeNaughtyApp(uid);
510 maybeThrow(err, "Unable to remove naughty app");
511 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800512 }
513
Ken Chenf5f51332022-01-28 10:08:16 +0800514 /**
515 * Add nice app bandwidth rule for specific app
516 *
517 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800518 * @throws ServiceSpecificException in case of failure, with an error code indicating the
519 * cause of the failure.
520 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900521 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000522 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000523
524 if (sEnableJavaBpfMap) {
525 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
526 } else {
527 final int err = native_addNiceApp(uid);
528 maybeThrow(err, "Unable to add nice app");
529 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800530 }
531
Ken Chenf5f51332022-01-28 10:08:16 +0800532 /**
533 * Remove nice app bandwidth rule for specific app
534 *
535 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800536 * @throws ServiceSpecificException in case of failure, with an error code indicating the
537 * cause of the failure.
538 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900539 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000540 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000541
542 if (sEnableJavaBpfMap) {
543 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
544 } else {
545 final int err = native_removeNiceApp(uid);
546 maybeThrow(err, "Unable to remove nice app");
547 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800548 }
549
Ken Chenf5f51332022-01-28 10:08:16 +0800550 /**
551 * Set target firewall child chain
552 *
553 * @param childChain target chain to enable
554 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000555 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800556 * @throws ServiceSpecificException in case of failure, with an error code indicating the
557 * cause of the failure.
558 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900559 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000560 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000561
Motomu Utsumie057dd42022-08-03 01:23:49 +0000562 if (sEnableJavaBpfMap) {
563 final long match = getMatchByFirewallChain(childChain);
564 try {
565 synchronized (sUidRulesConfigBpfMapLock) {
566 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
567 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
568 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
569 }
570 } catch (ErrnoException e) {
571 throw new ServiceSpecificException(e.errno,
572 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000573 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000574 } else {
575 final int err = native_setChildChain(childChain, enable);
576 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000577 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800578 }
579
580 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000581 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000582 *
583 * @param childChain target chain
584 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
585 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000586 * @throws ServiceSpecificException in case of failure, with an error code indicating the
587 * cause of the failure.
588 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000589 public boolean isChainEnabled(final int childChain) {
590 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000591
592 final long match = getMatchByFirewallChain(childChain);
593 try {
594 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000595 return (config.val & match) != 0;
596 } catch (ErrnoException e) {
597 throw new ServiceSpecificException(e.errno,
598 "Unable to get firewall chain status: " + Os.strerror(e.errno));
599 }
600 }
601
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900602 private Set<Integer> asSet(final int[] uids) {
603 final Set<Integer> uidSet = new ArraySet<>();
604 for (final int uid: uids) {
605 uidSet.add(uid);
606 }
607 return uidSet;
608 }
609
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000610 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800611 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000612 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800613 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000614 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800615 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000616 * @throws UnsupportedOperationException if called on pre-T devices.
617 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800618 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000619 public void replaceUidChain(final int chain, final int[] uids) {
620 throwIfPreT("replaceUidChain is not available on pre-T devices");
621
Motomu Utsumic7c16852022-08-03 06:51:41 +0000622 if (sEnableJavaBpfMap) {
623 final long match;
624 try {
625 match = getMatchByFirewallChain(chain);
626 } catch (ServiceSpecificException e) {
627 // Throws IllegalArgumentException to keep the behavior of
628 // ConnectivityManager#replaceFirewallChain API
629 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000630 }
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900631 final Set<Integer> uidSet = asSet(uids);
632 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
Motomu Utsumic7c16852022-08-03 06:51:41 +0000633 try {
634 synchronized (sUidOwnerMap) {
635 sUidOwnerMap.forEach((uid, config) -> {
636 // config could be null if there is a concurrent entry deletion.
Motomu Utsumi8e420ea2022-08-24 18:03:30 +0900637 // http://b/220084230. But sUidOwnerMap update must be done while holding a
638 // lock, so this should not happen.
639 if (config == null) {
640 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
641 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
Motomu Utsumic7c16852022-08-03 06:51:41 +0000642 uidSetToRemoveRule.add((int) uid.val);
643 }
644 });
645
646 for (final int uid : uidSetToRemoveRule) {
647 removeRule(uid, match, "replaceUidChain");
648 }
649 for (final int uid : uids) {
650 addRule(uid, match, "replaceUidChain");
651 }
652 }
653 } catch (ErrnoException | ServiceSpecificException e) {
654 Log.e(TAG, "replaceUidChain failed: " + e);
655 }
656 } else {
657 final int err;
658 switch (chain) {
659 case FIREWALL_CHAIN_DOZABLE:
660 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
661 break;
662 case FIREWALL_CHAIN_STANDBY:
663 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
664 break;
665 case FIREWALL_CHAIN_POWERSAVE:
666 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
667 break;
668 case FIREWALL_CHAIN_RESTRICTED:
669 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
670 break;
671 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
672 err = native_replaceUidChain(
673 "fw_low_power_standby", true /* isAllowList */, uids);
674 break;
675 case FIREWALL_CHAIN_OEM_DENY_1:
676 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
677 break;
678 case FIREWALL_CHAIN_OEM_DENY_2:
679 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
680 break;
681 case FIREWALL_CHAIN_OEM_DENY_3:
682 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
683 break;
684 default:
685 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
686 + chain);
687 }
688 if (err != 0) {
689 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
690 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800691 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800692 }
693
Ken Chenf5f51332022-01-28 10:08:16 +0800694 /**
695 * Set firewall rule for uid
696 *
697 * @param childChain target chain
698 * @param uid uid to allow/deny
699 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800700 * @throws ServiceSpecificException in case of failure, with an error code indicating the
701 * cause of the failure.
702 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900703 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000704 throwIfPreT("setUidRule is not available on pre-T devices");
705
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000706 if (sEnableJavaBpfMap) {
707 final long match = getMatchByFirewallChain(childChain);
708 final boolean isAllowList = isFirewallAllowList(childChain);
709 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
710 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000711
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000712 if (add) {
713 addRule(uid, match, "setUidRule");
714 } else {
715 removeRule(uid, match, "setUidRule");
716 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000717 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000718 final int err = native_setUidRule(childChain, uid, firewallRule);
719 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000720 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800721 }
722
723 /**
724 * Add ingress interface filtering rules to a list of UIDs
725 *
726 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
727 * allowed interface and loopback to be sent to the list of UIDs.
728 *
729 * Calling this method on one or more UIDs with an existing filtering rule but a different
730 * interface name will result in the filtering rule being updated to allow the new interface
731 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
732 *
733 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800734 * be received.
735 * @param uids an array of UIDs which the filtering rules will be set
736 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800737 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800738 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800739 */
Ken Chenf5f51332022-01-28 10:08:16 +0800740 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000741 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800742 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800743 return;
744 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000745
746 if (sEnableJavaBpfMap) {
747 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
748 // ifIndex is set to 0.
749 final int ifIndex;
750 if (ifName == null) {
751 ifIndex = 0;
752 } else {
753 ifIndex = mDeps.getIfIndex(ifName);
754 if (ifIndex == 0) {
755 throw new ServiceSpecificException(ENODEV,
756 "Failed to get index of interface " + ifName);
757 }
758 }
759 for (final int uid : uids) {
760 try {
761 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
762 } catch (ServiceSpecificException e) {
763 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
764 }
765 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000766 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000767 final int err = native_addUidInterfaceRules(ifName, uids);
768 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000769 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800770 }
771
772 /**
773 * Remove ingress interface filtering rules from a list of UIDs
774 *
775 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
776 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
777 *
778 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800779 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800780 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800781 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800782 */
Ken Chenf5f51332022-01-28 10:08:16 +0800783 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000784 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800785 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800786 return;
787 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000788
789 if (sEnableJavaBpfMap) {
790 for (final int uid : uids) {
791 try {
792 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
793 } catch (ServiceSpecificException e) {
794 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
795 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000796 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000797 } else {
798 final int err = native_removeUidInterfaceRules(uids);
799 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000800 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800801 }
802
Ken Chenf5f51332022-01-28 10:08:16 +0800803 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000804 * Update lockdown rule for uid
805 *
806 * @param uid target uid to add/remove the rule
807 * @param add {@code true} to add the rule, {@code false} to remove the rule.
808 * @throws ServiceSpecificException in case of failure, with an error code indicating the
809 * cause of the failure.
810 */
811 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000812 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000813
814 if (sEnableJavaBpfMap) {
815 if (add) {
816 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
817 } else {
818 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
819 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000820 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000821 final int err = native_updateUidLockdownRule(uid, add);
822 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000823 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000824 }
825
826 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800827 * Request netd to change the current active network stats map.
828 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000829 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800830 * @throws ServiceSpecificException in case of failure, with an error code indicating the
831 * cause of the failure.
832 */
markchien49e944c2022-03-01 15:22:20 +0800833 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000834 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
835
836 if (sEnableJavaBpfMap) {
837 try {
838 synchronized (sCurrentStatsMapConfigLock) {
839 final long config = sConfigurationMap.getValue(
840 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
841 final long newConfig = (config == STATS_SELECT_MAP_A)
842 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
843 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
844 new U32(newConfig));
845 }
846 } catch (ErrnoException e) {
847 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
848 }
849
850 // After changing the config, it's needed to make sure all the current running eBPF
851 // programs are finished and all the CPUs are aware of this config change before the old
852 // map is modified. So special hack is needed here to wait for the kernel to do a
853 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
854 // be available to all cores and the next eBPF programs triggered inside the kernel will
855 // use the new map configuration. So once this function returns it is safe to modify the
856 // old stats map without concerning about race between the kernel and userspace.
857 final int err = mDeps.synchronizeKernelRCU();
858 maybeThrow(err, "synchronizeKernelRCU failed");
859 } else {
860 final int err = native_swapActiveStatsMap();
861 maybeThrow(err, "Unable to swap active stats map");
862 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800863 }
864
Ken Chenf5f51332022-01-28 10:08:16 +0800865 /**
866 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
867 * specified. Or remove all permissions from the uids.
868 *
869 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
870 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
871 * revoke all permissions for the uids.
872 * @param uids uid of users to grant permission
873 * @throws RemoteException when netd has crashed.
874 */
875 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000876 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800877 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800878 return;
879 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000880
881 if (sEnableJavaBpfMap) {
882 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
883 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
884 for (final int uid : uids) {
885 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000886 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000887 } catch (ErrnoException e) {
888 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
889 }
890 }
891 return;
892 }
893
894 for (final int uid : uids) {
895 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000896 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
Motomu Utsumi65271202022-07-05 08:21:41 +0000897 } catch (ErrnoException e) {
898 Log.e(TAG, "Failed to set permission "
899 + permissions + " to uid " + uid + ": " + e);
900 }
901 }
902 } else {
903 native_setPermissionForUids(permissions, uids);
904 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800905 }
906
Motomu Utsumi166f9662022-09-01 10:35:29 +0900907 /** Register callback for statsd to pull atom. */
908 public void setPullAtomCallback(final Context context) {
909 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
910
911 final StatsManager statsManager = context.getSystemService(StatsManager.class);
912 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
913 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
914 }
915
916 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
917 throws ErrnoException {
918 // forEach could restart iteration from the beginning if there is a concurrent entry
919 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
920 // So using Set to count the number of entry in the map.
921 Set<K> keySet = new ArraySet<>();
922 map.forEach((k, v) -> keySet.add(k));
923 return keySet.size();
924 }
925
926 /** Callback for StatsManager#setPullAtomCallback */
927 @VisibleForTesting
928 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
929 if (atomTag != NETWORK_BPF_MAP_INFO) {
930 Log.e(TAG, "Unexpected atom tag: " + atomTag);
931 return StatsManager.PULL_SKIP;
932 }
933
934 try {
935 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
936 getMapSize(sUidPermissionMap)));
937 } catch (ErrnoException e) {
938 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
939 return StatsManager.PULL_SKIP;
940 }
941 return StatsManager.PULL_SUCCESS;
942 }
943
Motomu Utsumi310850f2022-09-02 12:48:20 +0900944 private String permissionToString(int permissionMask) {
945 if (permissionMask == PERMISSION_NONE) {
946 return "PERMISSION_NONE";
947 }
948 if (permissionMask == PERMISSION_UNINSTALLED) {
949 // PERMISSION_UNINSTALLED should never appear in the map
950 return "PERMISSION_UNINSTALLED error!";
951 }
952
953 final StringJoiner sj = new StringJoiner(" ");
954 for (Pair<Integer, String> permission: PERMISSION_LIST) {
955 final int permissionFlag = permission.first;
956 final String permissionName = permission.second;
957 if ((permissionMask & permissionFlag) != 0) {
958 sj.add(permissionName);
959 permissionMask &= ~permissionFlag;
960 }
961 }
962 if (permissionMask != 0) {
963 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
964 }
965 return sj.toString();
966 }
967
Motomu Utsumi956d86c2022-09-02 17:01:25 +0900968 private String matchToString(long matchMask) {
969 if (matchMask == NO_MATCH) {
970 return "NO_MATCH";
971 }
972
973 final StringJoiner sj = new StringJoiner(" ");
974 for (Pair<Long, String> match: MATCH_LIST) {
975 final long matchFlag = match.first;
976 final String matchName = match.second;
977 if ((matchMask & matchFlag) != 0) {
978 sj.add(matchName);
979 matchMask &= ~matchFlag;
980 }
981 }
982 if (matchMask != 0) {
983 sj.add("UNKNOWN_MATCH(" + matchMask + ")");
984 }
985 return sj.toString();
986 }
987
Motomu Utsumi372c9b42022-09-02 19:02:56 +0900988 private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
989 try {
990 final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
991 pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
992 } catch (ErrnoException e) {
993 pw.println("Failed to read ownerMatch configuration: " + e);
994 }
995 }
996
Motomu Utsumic675d6f2022-09-02 18:15:25 +0900997 private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
998 try {
999 final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
1000 final String currentStatsMap =
1001 (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
1002 pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
1003 } catch (ErrnoException e) {
1004 pw.println("Falied to read current statsMap configuration: " + e);
1005 }
1006 }
1007
Ken Chene6d511f2022-01-25 11:10:42 +08001008 /**
1009 * Dump BPF maps
1010 *
Motomu Utsumi310850f2022-09-02 12:48:20 +09001011 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +08001012 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +09001013 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +08001014 * @throws IOException when file descriptor is invalid.
1015 * @throws ServiceSpecificException when the method is called on an unsupported device.
1016 */
Motomu Utsumi310850f2022-09-02 12:48:20 +09001017 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +08001018 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00001019 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +08001020 throw new ServiceSpecificException(
1021 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
1022 + " devices, use dumpsys netd trafficcontroller instead.");
1023 }
Motomu Utsumidf8d2992022-09-01 17:08:27 +09001024 mDeps.nativeDump(fd, verbose);
Motomu Utsumi310850f2022-09-02 12:48:20 +09001025
Motomu Utsumi316d0572022-09-15 13:24:48 +09001026 pw.println();
1027 pw.println("sEnableJavaBpfMap: " + sEnableJavaBpfMap);
Motomu Utsumi310850f2022-09-02 12:48:20 +09001028 if (verbose) {
Motomu Utsumief546a92022-10-05 16:42:29 +09001029 pw.println();
1030 pw.println("BPF map content:");
1031 pw.increaseIndent();
1032
Motomu Utsumi372c9b42022-09-02 19:02:56 +09001033 dumpOwnerMatchConfig(pw);
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001034 dumpCurrentStatsMapConfig(pw);
1035 pw.println();
1036
Motomu Utsumief546a92022-10-05 16:42:29 +09001037 // TODO: Remove CookieTagMap content dump
1038 // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
1039 // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
1040 // need to be updated before remove the dump from BpfNetMaps.
1041 BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
1042 (key, value) -> "cookie=" + key.socketCookie
1043 + " tag=0x" + Long.toHexString(value.tag)
1044 + " uid=" + value.uid);
Motomu Utsumi956d86c2022-09-02 17:01:25 +09001045 BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
1046 (uid, match) -> {
1047 if ((match.rule & IIF_MATCH) != 0) {
1048 // TODO: convert interface index to interface name by IfaceIndexNameMap
1049 return uid.val + " " + matchToString(match.rule) + " " + match.iif;
1050 } else {
1051 return uid.val + " " + matchToString(match.rule);
1052 }
1053 });
Motomu Utsumi310850f2022-09-02 12:48:20 +09001054 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
1055 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
Motomu Utsumief546a92022-10-05 16:42:29 +09001056 pw.decreaseIndent();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001057 }
Ken Chene6d511f2022-01-25 11:10:42 +08001058 }
1059
Motomu Utsumi3af8f0e2022-09-02 23:42:13 +09001060 private static native void native_init(boolean startSkDestroyListener);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001061 private native int native_addNaughtyApp(int uid);
1062 private native int native_removeNaughtyApp(int uid);
1063 private native int native_addNiceApp(int uid);
1064 private native int native_removeNiceApp(int uid);
Motomu Utsumi114cd9c2022-08-01 02:08:35 +00001065 private native int native_setChildChain(int childChain, boolean enable);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001066 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
1067 private native int native_setUidRule(int childChain, int uid, int firewallRule);
1068 private native int native_addUidInterfaceRules(String ifName, int[] uids);
1069 private native int native_removeUidInterfaceRules(int[] uids);
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +00001070 private native int native_updateUidLockdownRule(int uid, boolean add);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001071 private native int native_swapActiveStatsMap();
Wayne Ma2fde98c2022-01-17 18:04:05 +08001072 private native void native_setPermissionForUids(int permissions, int[] uids);
Motomu Utsumidf8d2992022-09-01 17:08:27 +09001073 private static native void native_dump(FileDescriptor fd, boolean verbose);
Motomu Utsumi7abeaa42022-07-20 07:54:18 +00001074 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001075}