blob: 6a34a242ad60e695ff3db291a738c6b97530b196 [file] [log] [blame]
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001/*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Junyu Lai29b7b632023-08-23 17:35:17 +080019import static android.net.BpfNetMapsConstants.CONFIGURATION_MAP_PATH;
20import static android.net.BpfNetMapsConstants.COOKIE_TAG_MAP_PATH;
21import static android.net.BpfNetMapsConstants.CURRENT_STATS_MAP_CONFIGURATION_KEY;
22import static android.net.BpfNetMapsConstants.HAPPY_BOX_MATCH;
23import static android.net.BpfNetMapsConstants.IIF_MATCH;
24import static android.net.BpfNetMapsConstants.LOCKDOWN_VPN_MATCH;
25import static android.net.BpfNetMapsConstants.PENALTY_BOX_MATCH;
26import static android.net.BpfNetMapsConstants.UID_OWNER_MAP_PATH;
27import static android.net.BpfNetMapsConstants.UID_PERMISSION_MAP_PATH;
28import static android.net.BpfNetMapsConstants.UID_RULES_CONFIGURATION_KEY;
29import static android.net.BpfNetMapsUtils.getMatchByFirewallChain;
30import static android.net.BpfNetMapsUtils.matchToString;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000031import static android.net.ConnectivityManager.FIREWALL_CHAIN_DOZABLE;
32import static android.net.ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY;
33import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1;
34import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2;
35import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3;
36import static android.net.ConnectivityManager.FIREWALL_CHAIN_POWERSAVE;
37import static android.net.ConnectivityManager.FIREWALL_CHAIN_RESTRICTED;
38import static android.net.ConnectivityManager.FIREWALL_CHAIN_STANDBY;
Motomu Utsumi40230be2022-07-05 03:27:35 +000039import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
40import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Motomu Utsumi65271202022-07-05 08:21:41 +000041import static android.net.INetd.PERMISSION_INTERNET;
Motomu Utsumi310850f2022-09-02 12:48:20 +090042import static android.net.INetd.PERMISSION_NONE;
Motomu Utsumi65271202022-07-05 08:21:41 +000043import static android.net.INetd.PERMISSION_UNINSTALLED;
Motomu Utsumi310850f2022-09-02 12:48:20 +090044import static android.net.INetd.PERMISSION_UPDATE_DEVICE_STATS;
Motomu Utsumi18b287d2022-06-19 10:45:30 +000045import static android.system.OsConstants.EINVAL;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000046import static android.system.OsConstants.ENODEV;
Motomu Utsumi60ed3be2022-06-24 10:38:57 +000047import static android.system.OsConstants.ENOENT;
Ken Chene6d511f2022-01-25 11:10:42 +080048import static android.system.OsConstants.EOPNOTSUPP;
49
Motomu Utsumi166f9662022-09-01 10:35:29 +090050import static com.android.server.ConnectivityStatsLog.NETWORK_BPF_MAP_INFO;
51
52import android.app.StatsManager;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000053import android.content.Context;
Wayne Ma2fde98c2022-01-17 18:04:05 +080054import android.net.INetd;
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +000055import android.os.Build;
Wayne Ma2fde98c2022-01-17 18:04:05 +080056import android.os.RemoteException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080057import android.os.ServiceSpecificException;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000058import android.system.ErrnoException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080059import android.system.Os;
Motomu Utsumi1a477b02022-08-23 15:14:56 +090060import android.util.ArraySet;
Motomu Utsumi310850f2022-09-02 12:48:20 +090061import android.util.IndentingPrintWriter;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080062import android.util.Log;
Motomu Utsumi310850f2022-09-02 12:48:20 +090063import android.util.Pair;
Motomu Utsumi166f9662022-09-01 10:35:29 +090064import android.util.StatsEvent;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080065
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +000066import androidx.annotation.RequiresApi;
67
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000068import com.android.internal.annotations.VisibleForTesting;
Motomu Utsumi166f9662022-09-01 10:35:29 +090069import com.android.modules.utils.BackgroundThread;
Ken Chenf5f51332022-01-28 10:08:16 +080070import com.android.modules.utils.build.SdkLevel;
Motomu Utsumi310850f2022-09-02 12:48:20 +090071import com.android.net.module.util.BpfDump;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000072import com.android.net.module.util.BpfMap;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000073import com.android.net.module.util.DeviceConfigUtils;
Motomu Utsumi73599a52022-08-24 11:59:21 +090074import com.android.net.module.util.IBpfMap;
Motomu Utsumi166f9662022-09-01 10:35:29 +090075import com.android.net.module.util.Struct;
Maciej Żenczykowski785793f2022-09-17 02:35:20 +000076import com.android.net.module.util.Struct.S32;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000077import com.android.net.module.util.Struct.U32;
Motomu Utsumi65271202022-07-05 08:21:41 +000078import com.android.net.module.util.Struct.U8;
Motomu Utsumib9548862022-09-06 16:30:05 +090079import com.android.net.module.util.bpf.CookieTagMapKey;
80import com.android.net.module.util.bpf.CookieTagMapValue;
Ken Chenf5f51332022-01-28 10:08:16 +080081
Ken Chene6d511f2022-01-25 11:10:42 +080082import java.io.FileDescriptor;
83import java.io.IOException;
Motomu Utsumi310850f2022-09-02 12:48:20 +090084import java.util.Arrays;
Motomu Utsumi166f9662022-09-01 10:35:29 +090085import java.util.List;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000086import java.util.Set;
Motomu Utsumi310850f2022-09-02 12:48:20 +090087import java.util.StringJoiner;
Ken Chene6d511f2022-01-25 11:10:42 +080088
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080089/**
90 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
91 *
92 * {@hide}
93 */
94public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000095 private static final boolean PRE_T = !SdkLevel.isAtLeastT();
96 static {
97 if (!PRE_T) {
98 System.loadLibrary("service-connectivity");
99 }
100 }
101
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800102 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +0800103 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000104 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +0800105 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +0800106 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800107
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000108 private static Boolean sEnableJavaBpfMap = null;
Motomu Utsumi7628ea32023-08-14 11:09:02 +0900109 private static final String BPF_NET_MAPS_FORCE_DISABLE_JAVA_BPF_MAP =
110 "bpf_net_maps_force_disable_java_bpf_map";
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000111
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000112 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
113 // This entry is not accessed by others.
114 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
115 private static final Object sUidRulesConfigBpfMapLock = new Object();
116
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000117 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
118 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
119 // BpfNetMaps is an only writer of this entry.
120 private static final Object sCurrentStatsMapConfigLock = new Object();
121
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000122 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
123 private static final long STATS_SELECT_MAP_A = 0;
124 private static final long STATS_SELECT_MAP_B = 1;
125
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000126 private static IBpfMap<S32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000127 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000128 private static IBpfMap<S32, UidOwnerValue> sUidOwnerMap = null;
129 private static IBpfMap<S32, U8> sUidPermissionMap = null;
Motomu Utsumib9548862022-09-06 16:30:05 +0900130 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> sCookieTagMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000131
Motomu Utsumi310850f2022-09-02 12:48:20 +0900132 private static final List<Pair<Integer, String>> PERMISSION_LIST = Arrays.asList(
133 Pair.create(PERMISSION_INTERNET, "PERMISSION_INTERNET"),
134 Pair.create(PERMISSION_UPDATE_DEVICE_STATS, "PERMISSION_UPDATE_DEVICE_STATS")
135 );
136
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000137 /**
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000138 * Set sEnableJavaBpfMap for test.
139 */
140 @VisibleForTesting
141 public static void setEnableJavaBpfMapForTest(boolean enable) {
142 sEnableJavaBpfMap = enable;
143 }
144
145 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000146 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000147 */
148 @VisibleForTesting
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000149 public static void setConfigurationMapForTest(IBpfMap<S32, U32> configurationMap) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000150 sConfigurationMap = configurationMap;
151 }
152
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000153 /**
154 * Set uidOwnerMap for test.
155 */
156 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000157 public static void setUidOwnerMapForTest(IBpfMap<S32, UidOwnerValue> uidOwnerMap) {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000158 sUidOwnerMap = uidOwnerMap;
159 }
160
Motomu Utsumi65271202022-07-05 08:21:41 +0000161 /**
162 * Set uidPermissionMap for test.
163 */
164 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000165 public static void setUidPermissionMapForTest(IBpfMap<S32, U8> uidPermissionMap) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000166 sUidPermissionMap = uidPermissionMap;
167 }
168
Motomu Utsumib9548862022-09-06 16:30:05 +0900169 /**
170 * Set cookieTagMap for test.
171 */
172 @VisibleForTesting
173 public static void setCookieTagMapForTest(
174 IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap) {
175 sCookieTagMap = cookieTagMap;
176 }
177
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000178 private static IBpfMap<S32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000179 try {
180 return new BpfMap<>(
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000181 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U32.class);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000182 } catch (ErrnoException e) {
183 throw new IllegalStateException("Cannot open netd configuration map", e);
184 }
185 }
186
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000187 private static IBpfMap<S32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000188 try {
189 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000190 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, UidOwnerValue.class);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000191 } catch (ErrnoException e) {
192 throw new IllegalStateException("Cannot open uid owner map", e);
193 }
194 }
195
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000196 private static IBpfMap<S32, U8> getUidPermissionMap() {
Motomu Utsumi65271202022-07-05 08:21:41 +0000197 try {
198 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000199 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
Motomu Utsumi65271202022-07-05 08:21:41 +0000200 } catch (ErrnoException e) {
201 throw new IllegalStateException("Cannot open uid permission map", e);
202 }
203 }
204
Motomu Utsumib9548862022-09-06 16:30:05 +0900205 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
206 try {
207 return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,
208 CookieTagMapKey.class, CookieTagMapValue.class);
209 } catch (ErrnoException e) {
210 throw new IllegalStateException("Cannot open cookie tag map", e);
211 }
212 }
213
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000214 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000215 if (sConfigurationMap == null) {
216 sConfigurationMap = getConfigurationMap();
217 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000218 try {
219 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
220 new U32(UID_RULES_DEFAULT_CONFIGURATION));
221 } catch (ErrnoException e) {
222 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
223 }
224 try {
225 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
226 new U32(STATS_SELECT_MAP_A));
227 } catch (ErrnoException e) {
228 throw new IllegalStateException("Failed to initialize current stats configuration", e);
229 }
230
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000231 if (sUidOwnerMap == null) {
232 sUidOwnerMap = getUidOwnerMap();
233 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000234 try {
235 sUidOwnerMap.clear();
236 } catch (ErrnoException e) {
237 throw new IllegalStateException("Failed to initialize uid owner map", e);
238 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000239
240 if (sUidPermissionMap == null) {
241 sUidPermissionMap = getUidPermissionMap();
242 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900243
244 if (sCookieTagMap == null) {
245 sCookieTagMap = getCookieTagMap();
246 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000247 }
248
Ken Chenf5f51332022-01-28 10:08:16 +0800249 /**
250 * Initializes the class if it is not already initialized. This method will open maps but not
251 * cause any other effects. This method may be called multiple times on any thread.
252 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000253 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800254 if (sInitialized) return;
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000255 if (sEnableJavaBpfMap == null) {
Maciej Żenczykowskie7ebb152022-12-27 10:57:38 +0000256 sEnableJavaBpfMap = SdkLevel.isAtLeastU() ||
Motomu Utsumied4e7ec2023-09-13 14:58:32 +0900257 DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context,
Motomu Utsumi7628ea32023-08-14 11:09:02 +0900258 BPF_NET_MAPS_FORCE_DISABLE_JAVA_BPF_MAP);
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000259 }
260 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
261
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000262 initBpfMaps();
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900263 native_init(!sEnableJavaBpfMap /* startSkDestroyListener */);
Ken Chenf5f51332022-01-28 10:08:16 +0800264 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800265 }
266
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900267 public boolean isSkDestroyListenerRunning() {
268 return !sEnableJavaBpfMap;
269 }
270
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000271 /**
272 * Dependencies of BpfNetMaps, for injection in tests.
273 */
274 @VisibleForTesting
275 public static class Dependencies {
276 /**
277 * Get interface index.
278 */
279 public int getIfIndex(final String ifName) {
280 return Os.if_nametoindex(ifName);
281 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000282
283 /**
284 * Call synchronize_rcu()
285 */
286 public int synchronizeKernelRCU() {
287 return native_synchronizeKernelRCU();
288 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900289
290 /**
291 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
292 */
293 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
294 final int uidPermissionMapSize) {
295 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
296 uidOwnerMapSize, uidPermissionMapSize);
297 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000298 }
299
markchien49e944c2022-03-01 15:22:20 +0800300 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000301 public BpfNetMaps(final Context context) {
302 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800303
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000304 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800305 }
306
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000307 public BpfNetMaps(final Context context, final INetd netd) {
308 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000309 }
310
311 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000312 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000313 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000314 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000315 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800316 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000317 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800318 }
319
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000320 /**
Motomu Utsumi40230be2022-07-05 03:27:35 +0000321 * Get if the chain is allow list or not.
322 *
323 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
324 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
325 */
Motomu Utsumi40230be2022-07-05 03:27:35 +0000326 public boolean isFirewallAllowList(final int chain) {
327 switch (chain) {
328 case FIREWALL_CHAIN_DOZABLE:
329 case FIREWALL_CHAIN_POWERSAVE:
330 case FIREWALL_CHAIN_RESTRICTED:
331 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
332 return true;
333 case FIREWALL_CHAIN_STANDBY:
334 case FIREWALL_CHAIN_OEM_DENY_1:
335 case FIREWALL_CHAIN_OEM_DENY_2:
336 case FIREWALL_CHAIN_OEM_DENY_3:
337 return false;
338 default:
339 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
340 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000341 }
342
Ken Chenf5f51332022-01-28 10:08:16 +0800343 private void maybeThrow(final int err, final String msg) {
344 if (err != 0) {
345 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
346 }
347 }
348
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000349 private void throwIfPreT(final String msg) {
350 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000351 throw new UnsupportedOperationException(msg);
352 }
353 }
354
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000355 private void removeRule(final int uid, final long match, final String caller) {
356 try {
357 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000358 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000359
360 if (oldMatch == null) {
361 throw new ServiceSpecificException(ENOENT,
362 "sUidOwnerMap does not have entry for uid: " + uid);
363 }
364
365 final UidOwnerValue newMatch = new UidOwnerValue(
366 (match == IIF_MATCH) ? 0 : oldMatch.iif,
367 oldMatch.rule & ~match
368 );
369
370 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000371 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000372 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000373 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000374 }
375 }
376 } catch (ErrnoException e) {
377 throw new ServiceSpecificException(e.errno,
378 caller + " failed to remove rule: " + Os.strerror(e.errno));
379 }
380 }
381
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000382 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000383 if (match != IIF_MATCH && iif != 0) {
384 throw new ServiceSpecificException(EINVAL,
385 "Non-interface match must have zero interface index");
386 }
387
388 try {
389 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000390 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000391
392 final UidOwnerValue newMatch;
393 if (oldMatch != null) {
394 newMatch = new UidOwnerValue(
395 (match == IIF_MATCH) ? iif : oldMatch.iif,
396 oldMatch.rule | match
397 );
398 } else {
399 newMatch = new UidOwnerValue(
400 iif,
401 match
402 );
403 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000404 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000405 }
406 } catch (ErrnoException e) {
407 throw new ServiceSpecificException(e.errno,
408 caller + " failed to add rule: " + Os.strerror(e.errno));
409 }
410 }
411
412 private void addRule(final int uid, final long match, final String caller) {
413 addRule(uid, match, 0 /* iif */, caller);
414 }
415
Ken Chenf5f51332022-01-28 10:08:16 +0800416 /**
417 * Add naughty app bandwidth rule for specific app
418 *
419 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800420 * @throws ServiceSpecificException in case of failure, with an error code indicating the
421 * cause of the failure.
422 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900423 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000424 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000425
426 if (sEnableJavaBpfMap) {
427 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
428 } else {
429 final int err = native_addNaughtyApp(uid);
430 maybeThrow(err, "Unable to add naughty app");
431 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800432 }
433
Ken Chenf5f51332022-01-28 10:08:16 +0800434 /**
435 * Remove naughty app bandwidth rule for specific app
436 *
437 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800438 * @throws ServiceSpecificException in case of failure, with an error code indicating the
439 * cause of the failure.
440 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900441 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000442 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000443
444 if (sEnableJavaBpfMap) {
445 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
446 } else {
447 final int err = native_removeNaughtyApp(uid);
448 maybeThrow(err, "Unable to remove naughty app");
449 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800450 }
451
Ken Chenf5f51332022-01-28 10:08:16 +0800452 /**
453 * Add nice app bandwidth rule for specific app
454 *
455 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800456 * @throws ServiceSpecificException in case of failure, with an error code indicating the
457 * cause of the failure.
458 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900459 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000460 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000461
462 if (sEnableJavaBpfMap) {
463 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
464 } else {
465 final int err = native_addNiceApp(uid);
466 maybeThrow(err, "Unable to add nice app");
467 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800468 }
469
Ken Chenf5f51332022-01-28 10:08:16 +0800470 /**
471 * Remove nice app bandwidth rule for specific app
472 *
473 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800474 * @throws ServiceSpecificException in case of failure, with an error code indicating the
475 * cause of the failure.
476 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900477 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000478 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000479
480 if (sEnableJavaBpfMap) {
481 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
482 } else {
483 final int err = native_removeNiceApp(uid);
484 maybeThrow(err, "Unable to remove nice app");
485 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800486 }
487
Ken Chenf5f51332022-01-28 10:08:16 +0800488 /**
489 * Set target firewall child chain
490 *
491 * @param childChain target chain to enable
492 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000493 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800494 * @throws ServiceSpecificException in case of failure, with an error code indicating the
495 * cause of the failure.
496 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900497 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000498 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000499
Motomu Utsumie057dd42022-08-03 01:23:49 +0000500 if (sEnableJavaBpfMap) {
501 final long match = getMatchByFirewallChain(childChain);
502 try {
503 synchronized (sUidRulesConfigBpfMapLock) {
504 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
505 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
506 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
507 }
508 } catch (ErrnoException e) {
509 throw new ServiceSpecificException(e.errno,
510 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000511 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000512 } else {
513 final int err = native_setChildChain(childChain, enable);
514 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000515 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800516 }
517
518 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000519 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000520 *
521 * @param childChain target chain
522 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
523 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000524 * @throws ServiceSpecificException in case of failure, with an error code indicating the
525 * cause of the failure.
526 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000527 public boolean isChainEnabled(final int childChain) {
528 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000529
530 final long match = getMatchByFirewallChain(childChain);
531 try {
532 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000533 return (config.val & match) != 0;
534 } catch (ErrnoException e) {
535 throw new ServiceSpecificException(e.errno,
536 "Unable to get firewall chain status: " + Os.strerror(e.errno));
537 }
538 }
539
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900540 private Set<Integer> asSet(final int[] uids) {
541 final Set<Integer> uidSet = new ArraySet<>();
542 for (final int uid: uids) {
543 uidSet.add(uid);
544 }
545 return uidSet;
546 }
547
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000548 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800549 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000550 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800551 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000552 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800553 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000554 * @throws UnsupportedOperationException if called on pre-T devices.
555 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800556 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000557 public void replaceUidChain(final int chain, final int[] uids) {
558 throwIfPreT("replaceUidChain is not available on pre-T devices");
559
Motomu Utsumic7c16852022-08-03 06:51:41 +0000560 if (sEnableJavaBpfMap) {
561 final long match;
562 try {
563 match = getMatchByFirewallChain(chain);
564 } catch (ServiceSpecificException e) {
565 // Throws IllegalArgumentException to keep the behavior of
566 // ConnectivityManager#replaceFirewallChain API
567 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000568 }
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900569 final Set<Integer> uidSet = asSet(uids);
570 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
Motomu Utsumic7c16852022-08-03 06:51:41 +0000571 try {
572 synchronized (sUidOwnerMap) {
573 sUidOwnerMap.forEach((uid, config) -> {
574 // config could be null if there is a concurrent entry deletion.
Motomu Utsumi8e420ea2022-08-24 18:03:30 +0900575 // http://b/220084230. But sUidOwnerMap update must be done while holding a
576 // lock, so this should not happen.
577 if (config == null) {
578 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
579 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
Motomu Utsumic7c16852022-08-03 06:51:41 +0000580 uidSetToRemoveRule.add((int) uid.val);
581 }
582 });
583
584 for (final int uid : uidSetToRemoveRule) {
585 removeRule(uid, match, "replaceUidChain");
586 }
587 for (final int uid : uids) {
588 addRule(uid, match, "replaceUidChain");
589 }
590 }
591 } catch (ErrnoException | ServiceSpecificException e) {
592 Log.e(TAG, "replaceUidChain failed: " + e);
593 }
594 } else {
595 final int err;
596 switch (chain) {
597 case FIREWALL_CHAIN_DOZABLE:
598 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
599 break;
600 case FIREWALL_CHAIN_STANDBY:
601 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
602 break;
603 case FIREWALL_CHAIN_POWERSAVE:
604 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
605 break;
606 case FIREWALL_CHAIN_RESTRICTED:
607 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
608 break;
609 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
610 err = native_replaceUidChain(
611 "fw_low_power_standby", true /* isAllowList */, uids);
612 break;
613 case FIREWALL_CHAIN_OEM_DENY_1:
614 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
615 break;
616 case FIREWALL_CHAIN_OEM_DENY_2:
617 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
618 break;
619 case FIREWALL_CHAIN_OEM_DENY_3:
620 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
621 break;
622 default:
623 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
624 + chain);
625 }
626 if (err != 0) {
627 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
628 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800629 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800630 }
631
Ken Chenf5f51332022-01-28 10:08:16 +0800632 /**
633 * Set firewall rule for uid
634 *
635 * @param childChain target chain
636 * @param uid uid to allow/deny
637 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800638 * @throws ServiceSpecificException in case of failure, with an error code indicating the
639 * cause of the failure.
640 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900641 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000642 throwIfPreT("setUidRule is not available on pre-T devices");
643
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000644 if (sEnableJavaBpfMap) {
645 final long match = getMatchByFirewallChain(childChain);
646 final boolean isAllowList = isFirewallAllowList(childChain);
647 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
648 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000649
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000650 if (add) {
651 addRule(uid, match, "setUidRule");
652 } else {
653 removeRule(uid, match, "setUidRule");
654 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000655 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000656 final int err = native_setUidRule(childChain, uid, firewallRule);
657 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000658 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800659 }
660
661 /**
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900662 * Get firewall rule of specified firewall chain on specified uid.
663 *
664 * @param childChain target chain
665 * @param uid target uid
666 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
667 * @throws UnsupportedOperationException if called on pre-T devices.
668 * @throws ServiceSpecificException in case of failure, with an error code indicating the
669 * cause of the failure.
670 */
671 public int getUidRule(final int childChain, final int uid) {
672 throwIfPreT("isUidChainEnabled is not available on pre-T devices");
673
674 final long match = getMatchByFirewallChain(childChain);
675 final boolean isAllowList = isFirewallAllowList(childChain);
676 try {
677 final UidOwnerValue uidMatch = sUidOwnerMap.getValue(new S32(uid));
678 final boolean isMatchEnabled = uidMatch != null && (uidMatch.rule & match) != 0;
679 return isMatchEnabled == isAllowList ? FIREWALL_RULE_ALLOW : FIREWALL_RULE_DENY;
680 } catch (ErrnoException e) {
681 throw new ServiceSpecificException(e.errno,
682 "Unable to get uid rule status: " + Os.strerror(e.errno));
683 }
684 }
685
Motomu Utsumid44a33a2023-03-28 18:08:12 +0900686 private Set<Integer> getUidsMatchEnabled(final int childChain) throws ErrnoException {
687 final long match = getMatchByFirewallChain(childChain);
688 Set<Integer> uids = new ArraySet<>();
689 synchronized (sUidOwnerMap) {
690 sUidOwnerMap.forEach((uid, val) -> {
691 if (val == null) {
692 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
693 } else {
694 if ((val.rule & match) != 0) {
695 uids.add(uid.val);
696 }
697 }
698 });
699 }
700 return uids;
701 }
702
703 /**
704 * Get uids that has FIREWALL_RULE_ALLOW on allowlist chain.
705 * Allowlist means the firewall denies all by default, uids must be explicitly allowed.
706 *
707 * Note that uids that has FIREWALL_RULE_DENY on allowlist chain can not be computed from the
708 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_ALLOW rule in bpf map
709 * are determined to have FIREWALL_RULE_DENY.
710 *
711 * @param childChain target chain
712 * @return Set of uids
713 */
714 public Set<Integer> getUidsWithAllowRuleOnAllowListChain(final int childChain)
715 throws ErrnoException {
716 if (!isFirewallAllowList(childChain)) {
717 throw new IllegalArgumentException("getUidsWithAllowRuleOnAllowListChain is called with"
718 + " denylist chain:" + childChain);
719 }
720 // Corresponding match is enabled for uids that has FIREWALL_RULE_ALLOW on allowlist chain.
721 return getUidsMatchEnabled(childChain);
722 }
723
724 /**
725 * Get uids that has FIREWALL_RULE_DENY on denylist chain.
726 * Denylist means the firewall allows all by default, uids must be explicitly denyed
727 *
728 * Note that uids that has FIREWALL_RULE_ALLOW on denylist chain can not be computed from the
729 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_DENY rule in bpf map
730 * are determined to have the FIREWALL_RULE_ALLOW.
731 *
732 * @param childChain target chain
733 * @return Set of uids
734 */
735 public Set<Integer> getUidsWithDenyRuleOnDenyListChain(final int childChain)
736 throws ErrnoException {
737 if (isFirewallAllowList(childChain)) {
738 throw new IllegalArgumentException("getUidsWithDenyRuleOnDenyListChain is called with"
739 + " allowlist chain:" + childChain);
740 }
741 // Corresponding match is enabled for uids that has FIREWALL_RULE_DENY on denylist chain.
742 return getUidsMatchEnabled(childChain);
743 }
744
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900745 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800746 * Add ingress interface filtering rules to a list of UIDs
747 *
748 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
749 * allowed interface and loopback to be sent to the list of UIDs.
750 *
751 * Calling this method on one or more UIDs with an existing filtering rule but a different
752 * interface name will result in the filtering rule being updated to allow the new interface
753 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
754 *
755 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800756 * be received.
757 * @param uids an array of UIDs which the filtering rules will be set
758 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800759 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800760 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800761 */
Ken Chenf5f51332022-01-28 10:08:16 +0800762 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000763 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800764 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800765 return;
766 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000767
768 if (sEnableJavaBpfMap) {
769 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
770 // ifIndex is set to 0.
771 final int ifIndex;
772 if (ifName == null) {
773 ifIndex = 0;
774 } else {
775 ifIndex = mDeps.getIfIndex(ifName);
776 if (ifIndex == 0) {
777 throw new ServiceSpecificException(ENODEV,
778 "Failed to get index of interface " + ifName);
779 }
780 }
781 for (final int uid : uids) {
782 try {
783 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
784 } catch (ServiceSpecificException e) {
785 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
786 }
787 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000788 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000789 final int err = native_addUidInterfaceRules(ifName, uids);
790 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000791 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800792 }
793
794 /**
795 * Remove ingress interface filtering rules from a list of UIDs
796 *
797 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
798 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
799 *
800 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800801 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800802 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800803 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800804 */
Ken Chenf5f51332022-01-28 10:08:16 +0800805 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000806 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800807 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800808 return;
809 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000810
811 if (sEnableJavaBpfMap) {
812 for (final int uid : uids) {
813 try {
814 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
815 } catch (ServiceSpecificException e) {
816 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
817 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000818 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000819 } else {
820 final int err = native_removeUidInterfaceRules(uids);
821 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000822 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800823 }
824
Ken Chenf5f51332022-01-28 10:08:16 +0800825 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000826 * Update lockdown rule for uid
827 *
828 * @param uid target uid to add/remove the rule
829 * @param add {@code true} to add the rule, {@code false} to remove the rule.
830 * @throws ServiceSpecificException in case of failure, with an error code indicating the
831 * cause of the failure.
832 */
833 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000834 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000835
836 if (sEnableJavaBpfMap) {
837 if (add) {
838 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
839 } else {
840 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
841 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000842 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000843 final int err = native_updateUidLockdownRule(uid, add);
844 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000845 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000846 }
847
848 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800849 * Request netd to change the current active network stats map.
850 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000851 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800852 * @throws ServiceSpecificException in case of failure, with an error code indicating the
853 * cause of the failure.
854 */
markchien49e944c2022-03-01 15:22:20 +0800855 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000856 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
857
858 if (sEnableJavaBpfMap) {
859 try {
860 synchronized (sCurrentStatsMapConfigLock) {
861 final long config = sConfigurationMap.getValue(
862 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
863 final long newConfig = (config == STATS_SELECT_MAP_A)
864 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
865 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
866 new U32(newConfig));
867 }
868 } catch (ErrnoException e) {
869 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
870 }
871
872 // After changing the config, it's needed to make sure all the current running eBPF
873 // programs are finished and all the CPUs are aware of this config change before the old
874 // map is modified. So special hack is needed here to wait for the kernel to do a
875 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
876 // be available to all cores and the next eBPF programs triggered inside the kernel will
877 // use the new map configuration. So once this function returns it is safe to modify the
878 // old stats map without concerning about race between the kernel and userspace.
879 final int err = mDeps.synchronizeKernelRCU();
880 maybeThrow(err, "synchronizeKernelRCU failed");
881 } else {
882 final int err = native_swapActiveStatsMap();
883 maybeThrow(err, "Unable to swap active stats map");
884 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800885 }
886
Ken Chenf5f51332022-01-28 10:08:16 +0800887 /**
888 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
889 * specified. Or remove all permissions from the uids.
890 *
891 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
892 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
893 * revoke all permissions for the uids.
894 * @param uids uid of users to grant permission
895 * @throws RemoteException when netd has crashed.
896 */
897 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000898 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800899 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800900 return;
901 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000902
903 if (sEnableJavaBpfMap) {
904 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
905 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
906 for (final int uid : uids) {
907 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000908 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000909 } catch (ErrnoException e) {
910 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
911 }
912 }
913 return;
914 }
915
916 for (final int uid : uids) {
917 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000918 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
Motomu Utsumi65271202022-07-05 08:21:41 +0000919 } catch (ErrnoException e) {
920 Log.e(TAG, "Failed to set permission "
921 + permissions + " to uid " + uid + ": " + e);
922 }
923 }
924 } else {
925 native_setPermissionForUids(permissions, uids);
926 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800927 }
928
Motomu Utsumi166f9662022-09-01 10:35:29 +0900929 /** Register callback for statsd to pull atom. */
930 public void setPullAtomCallback(final Context context) {
931 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
932
933 final StatsManager statsManager = context.getSystemService(StatsManager.class);
934 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
935 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
936 }
937
938 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
939 throws ErrnoException {
940 // forEach could restart iteration from the beginning if there is a concurrent entry
941 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
942 // So using Set to count the number of entry in the map.
943 Set<K> keySet = new ArraySet<>();
944 map.forEach((k, v) -> keySet.add(k));
945 return keySet.size();
946 }
947
948 /** Callback for StatsManager#setPullAtomCallback */
949 @VisibleForTesting
950 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
951 if (atomTag != NETWORK_BPF_MAP_INFO) {
952 Log.e(TAG, "Unexpected atom tag: " + atomTag);
953 return StatsManager.PULL_SKIP;
954 }
955
956 try {
957 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
958 getMapSize(sUidPermissionMap)));
959 } catch (ErrnoException e) {
960 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
961 return StatsManager.PULL_SKIP;
962 }
963 return StatsManager.PULL_SUCCESS;
964 }
965
Motomu Utsumi310850f2022-09-02 12:48:20 +0900966 private String permissionToString(int permissionMask) {
967 if (permissionMask == PERMISSION_NONE) {
968 return "PERMISSION_NONE";
969 }
970 if (permissionMask == PERMISSION_UNINSTALLED) {
971 // PERMISSION_UNINSTALLED should never appear in the map
972 return "PERMISSION_UNINSTALLED error!";
973 }
974
975 final StringJoiner sj = new StringJoiner(" ");
976 for (Pair<Integer, String> permission: PERMISSION_LIST) {
977 final int permissionFlag = permission.first;
978 final String permissionName = permission.second;
979 if ((permissionMask & permissionFlag) != 0) {
980 sj.add(permissionName);
981 permissionMask &= ~permissionFlag;
982 }
983 }
984 if (permissionMask != 0) {
985 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
986 }
987 return sj.toString();
988 }
989
Motomu Utsumi372c9b42022-09-02 19:02:56 +0900990 private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
991 try {
992 final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
993 pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
994 } catch (ErrnoException e) {
995 pw.println("Failed to read ownerMatch configuration: " + e);
996 }
997 }
998
Motomu Utsumic675d6f2022-09-02 18:15:25 +0900999 private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
1000 try {
1001 final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
1002 final String currentStatsMap =
1003 (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
1004 pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
1005 } catch (ErrnoException e) {
1006 pw.println("Falied to read current statsMap configuration: " + e);
1007 }
1008 }
1009
Ken Chene6d511f2022-01-25 11:10:42 +08001010 /**
1011 * Dump BPF maps
1012 *
Motomu Utsumi310850f2022-09-02 12:48:20 +09001013 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +08001014 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +09001015 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +08001016 * @throws IOException when file descriptor is invalid.
1017 * @throws ServiceSpecificException when the method is called on an unsupported device.
1018 */
Motomu Utsumi310850f2022-09-02 12:48:20 +09001019 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +08001020 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00001021 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +08001022 throw new ServiceSpecificException(
1023 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
1024 + " devices, use dumpsys netd trafficcontroller instead.");
1025 }
Maciej Żenczykowskid70a3302023-09-06 16:45:25 +00001026
1027 pw.println("TrafficController"); // required by CTS testDumpBpfNetMaps
Motomu Utsumi310850f2022-09-02 12:48:20 +09001028
Motomu Utsumi316d0572022-09-15 13:24:48 +09001029 pw.println();
1030 pw.println("sEnableJavaBpfMap: " + sEnableJavaBpfMap);
Motomu Utsumi310850f2022-09-02 12:48:20 +09001031 if (verbose) {
Motomu Utsumief546a92022-10-05 16:42:29 +09001032 pw.println();
1033 pw.println("BPF map content:");
1034 pw.increaseIndent();
1035
Motomu Utsumi372c9b42022-09-02 19:02:56 +09001036 dumpOwnerMatchConfig(pw);
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001037 dumpCurrentStatsMapConfig(pw);
1038 pw.println();
1039
Motomu Utsumief546a92022-10-05 16:42:29 +09001040 // TODO: Remove CookieTagMap content dump
1041 // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
1042 // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
1043 // need to be updated before remove the dump from BpfNetMaps.
1044 BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
1045 (key, value) -> "cookie=" + key.socketCookie
1046 + " tag=0x" + Long.toHexString(value.tag)
1047 + " uid=" + value.uid);
Motomu Utsumi956d86c2022-09-02 17:01:25 +09001048 BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
1049 (uid, match) -> {
1050 if ((match.rule & IIF_MATCH) != 0) {
1051 // TODO: convert interface index to interface name by IfaceIndexNameMap
1052 return uid.val + " " + matchToString(match.rule) + " " + match.iif;
1053 } else {
1054 return uid.val + " " + matchToString(match.rule);
1055 }
1056 });
Motomu Utsumi310850f2022-09-02 12:48:20 +09001057 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
1058 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
Motomu Utsumief546a92022-10-05 16:42:29 +09001059 pw.decreaseIndent();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001060 }
Ken Chene6d511f2022-01-25 11:10:42 +08001061 }
1062
Maciej Żenczykowski70fbfa42023-07-18 20:14:38 +00001063 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi3af8f0e2022-09-02 23:42:13 +09001064 private static native void native_init(boolean startSkDestroyListener);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001065
1066 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001067 private native int native_addNaughtyApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001068
1069 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001070 private native int native_removeNaughtyApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001071
1072 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001073 private native int native_addNiceApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001074
1075 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001076 private native int native_removeNiceApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001077
1078 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi114cd9c2022-08-01 02:08:35 +00001079 private native int native_setChildChain(int childChain, boolean enable);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001080
1081 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001082 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001083
1084 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001085 private native int native_setUidRule(int childChain, int uid, int firewallRule);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001086
1087 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001088 private native int native_addUidInterfaceRules(String ifName, int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001089
1090 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001091 private native int native_removeUidInterfaceRules(int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001092
1093 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +00001094 private native int native_updateUidLockdownRule(int uid, boolean add);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001095
1096 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001097 private native int native_swapActiveStatsMap();
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001098
1099 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma2fde98c2022-01-17 18:04:05 +08001100 private native void native_setPermissionForUids(int permissions, int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001101
1102 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi7abeaa42022-07-20 07:54:18 +00001103 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001104}