blob: 62520dc79730333a8bffd7edb9d6183d0822a94e [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 Utsumi7628ea32023-08-14 11:09:02 +0900257 DeviceConfigUtils.isTetheringFeatureNotChickenedOut(
258 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 Utsumidf8d2992022-09-01 17:08:27 +0900298
299 /**
300 * Call native_dump
301 */
302 public void nativeDump(final FileDescriptor fd, final boolean verbose) {
303 native_dump(fd, verbose);
304 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000305 }
306
markchien49e944c2022-03-01 15:22:20 +0800307 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000308 public BpfNetMaps(final Context context) {
309 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800310
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000311 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800312 }
313
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000314 public BpfNetMaps(final Context context, final INetd netd) {
315 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000316 }
317
318 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000319 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000320 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000321 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000322 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800323 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000324 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800325 }
326
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000327 /**
Motomu Utsumi40230be2022-07-05 03:27:35 +0000328 * Get if the chain is allow list or not.
329 *
330 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
331 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
332 */
Motomu Utsumi40230be2022-07-05 03:27:35 +0000333 public boolean isFirewallAllowList(final int chain) {
334 switch (chain) {
335 case FIREWALL_CHAIN_DOZABLE:
336 case FIREWALL_CHAIN_POWERSAVE:
337 case FIREWALL_CHAIN_RESTRICTED:
338 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
339 return true;
340 case FIREWALL_CHAIN_STANDBY:
341 case FIREWALL_CHAIN_OEM_DENY_1:
342 case FIREWALL_CHAIN_OEM_DENY_2:
343 case FIREWALL_CHAIN_OEM_DENY_3:
344 return false;
345 default:
346 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
347 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000348 }
349
Ken Chenf5f51332022-01-28 10:08:16 +0800350 private void maybeThrow(final int err, final String msg) {
351 if (err != 0) {
352 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
353 }
354 }
355
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000356 private void throwIfPreT(final String msg) {
357 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000358 throw new UnsupportedOperationException(msg);
359 }
360 }
361
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000362 private void removeRule(final int uid, final long match, final String caller) {
363 try {
364 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000365 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000366
367 if (oldMatch == null) {
368 throw new ServiceSpecificException(ENOENT,
369 "sUidOwnerMap does not have entry for uid: " + uid);
370 }
371
372 final UidOwnerValue newMatch = new UidOwnerValue(
373 (match == IIF_MATCH) ? 0 : oldMatch.iif,
374 oldMatch.rule & ~match
375 );
376
377 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000378 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000379 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000380 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000381 }
382 }
383 } catch (ErrnoException e) {
384 throw new ServiceSpecificException(e.errno,
385 caller + " failed to remove rule: " + Os.strerror(e.errno));
386 }
387 }
388
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000389 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000390 if (match != IIF_MATCH && iif != 0) {
391 throw new ServiceSpecificException(EINVAL,
392 "Non-interface match must have zero interface index");
393 }
394
395 try {
396 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000397 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000398
399 final UidOwnerValue newMatch;
400 if (oldMatch != null) {
401 newMatch = new UidOwnerValue(
402 (match == IIF_MATCH) ? iif : oldMatch.iif,
403 oldMatch.rule | match
404 );
405 } else {
406 newMatch = new UidOwnerValue(
407 iif,
408 match
409 );
410 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000411 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000412 }
413 } catch (ErrnoException e) {
414 throw new ServiceSpecificException(e.errno,
415 caller + " failed to add rule: " + Os.strerror(e.errno));
416 }
417 }
418
419 private void addRule(final int uid, final long match, final String caller) {
420 addRule(uid, match, 0 /* iif */, caller);
421 }
422
Ken Chenf5f51332022-01-28 10:08:16 +0800423 /**
424 * Add naughty app bandwidth rule for specific app
425 *
426 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800427 * @throws ServiceSpecificException in case of failure, with an error code indicating the
428 * cause of the failure.
429 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900430 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000431 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000432
433 if (sEnableJavaBpfMap) {
434 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
435 } else {
436 final int err = native_addNaughtyApp(uid);
437 maybeThrow(err, "Unable to add naughty app");
438 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800439 }
440
Ken Chenf5f51332022-01-28 10:08:16 +0800441 /**
442 * Remove naughty app bandwidth rule for specific app
443 *
444 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800445 * @throws ServiceSpecificException in case of failure, with an error code indicating the
446 * cause of the failure.
447 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900448 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000449 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000450
451 if (sEnableJavaBpfMap) {
452 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
453 } else {
454 final int err = native_removeNaughtyApp(uid);
455 maybeThrow(err, "Unable to remove naughty app");
456 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800457 }
458
Ken Chenf5f51332022-01-28 10:08:16 +0800459 /**
460 * Add nice app bandwidth rule for specific app
461 *
462 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800463 * @throws ServiceSpecificException in case of failure, with an error code indicating the
464 * cause of the failure.
465 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900466 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000467 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000468
469 if (sEnableJavaBpfMap) {
470 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
471 } else {
472 final int err = native_addNiceApp(uid);
473 maybeThrow(err, "Unable to add nice app");
474 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800475 }
476
Ken Chenf5f51332022-01-28 10:08:16 +0800477 /**
478 * Remove nice app bandwidth rule for specific app
479 *
480 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800481 * @throws ServiceSpecificException in case of failure, with an error code indicating the
482 * cause of the failure.
483 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900484 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000485 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000486
487 if (sEnableJavaBpfMap) {
488 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
489 } else {
490 final int err = native_removeNiceApp(uid);
491 maybeThrow(err, "Unable to remove nice app");
492 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800493 }
494
Ken Chenf5f51332022-01-28 10:08:16 +0800495 /**
496 * Set target firewall child chain
497 *
498 * @param childChain target chain to enable
499 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000500 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800501 * @throws ServiceSpecificException in case of failure, with an error code indicating the
502 * cause of the failure.
503 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900504 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000505 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000506
Motomu Utsumie057dd42022-08-03 01:23:49 +0000507 if (sEnableJavaBpfMap) {
508 final long match = getMatchByFirewallChain(childChain);
509 try {
510 synchronized (sUidRulesConfigBpfMapLock) {
511 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
512 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
513 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
514 }
515 } catch (ErrnoException e) {
516 throw new ServiceSpecificException(e.errno,
517 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000518 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000519 } else {
520 final int err = native_setChildChain(childChain, enable);
521 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000522 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800523 }
524
525 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000526 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000527 *
528 * @param childChain target chain
529 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
530 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000531 * @throws ServiceSpecificException in case of failure, with an error code indicating the
532 * cause of the failure.
533 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000534 public boolean isChainEnabled(final int childChain) {
535 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000536
537 final long match = getMatchByFirewallChain(childChain);
538 try {
539 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000540 return (config.val & match) != 0;
541 } catch (ErrnoException e) {
542 throw new ServiceSpecificException(e.errno,
543 "Unable to get firewall chain status: " + Os.strerror(e.errno));
544 }
545 }
546
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900547 private Set<Integer> asSet(final int[] uids) {
548 final Set<Integer> uidSet = new ArraySet<>();
549 for (final int uid: uids) {
550 uidSet.add(uid);
551 }
552 return uidSet;
553 }
554
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000555 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800556 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000557 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800558 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000559 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800560 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000561 * @throws UnsupportedOperationException if called on pre-T devices.
562 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800563 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000564 public void replaceUidChain(final int chain, final int[] uids) {
565 throwIfPreT("replaceUidChain is not available on pre-T devices");
566
Motomu Utsumic7c16852022-08-03 06:51:41 +0000567 if (sEnableJavaBpfMap) {
568 final long match;
569 try {
570 match = getMatchByFirewallChain(chain);
571 } catch (ServiceSpecificException e) {
572 // Throws IllegalArgumentException to keep the behavior of
573 // ConnectivityManager#replaceFirewallChain API
574 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000575 }
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900576 final Set<Integer> uidSet = asSet(uids);
577 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
Motomu Utsumic7c16852022-08-03 06:51:41 +0000578 try {
579 synchronized (sUidOwnerMap) {
580 sUidOwnerMap.forEach((uid, config) -> {
581 // config could be null if there is a concurrent entry deletion.
Motomu Utsumi8e420ea2022-08-24 18:03:30 +0900582 // http://b/220084230. But sUidOwnerMap update must be done while holding a
583 // lock, so this should not happen.
584 if (config == null) {
585 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
586 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
Motomu Utsumic7c16852022-08-03 06:51:41 +0000587 uidSetToRemoveRule.add((int) uid.val);
588 }
589 });
590
591 for (final int uid : uidSetToRemoveRule) {
592 removeRule(uid, match, "replaceUidChain");
593 }
594 for (final int uid : uids) {
595 addRule(uid, match, "replaceUidChain");
596 }
597 }
598 } catch (ErrnoException | ServiceSpecificException e) {
599 Log.e(TAG, "replaceUidChain failed: " + e);
600 }
601 } else {
602 final int err;
603 switch (chain) {
604 case FIREWALL_CHAIN_DOZABLE:
605 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
606 break;
607 case FIREWALL_CHAIN_STANDBY:
608 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
609 break;
610 case FIREWALL_CHAIN_POWERSAVE:
611 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
612 break;
613 case FIREWALL_CHAIN_RESTRICTED:
614 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
615 break;
616 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
617 err = native_replaceUidChain(
618 "fw_low_power_standby", true /* isAllowList */, uids);
619 break;
620 case FIREWALL_CHAIN_OEM_DENY_1:
621 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
622 break;
623 case FIREWALL_CHAIN_OEM_DENY_2:
624 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
625 break;
626 case FIREWALL_CHAIN_OEM_DENY_3:
627 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
628 break;
629 default:
630 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
631 + chain);
632 }
633 if (err != 0) {
634 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
635 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800636 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800637 }
638
Ken Chenf5f51332022-01-28 10:08:16 +0800639 /**
640 * Set firewall rule for uid
641 *
642 * @param childChain target chain
643 * @param uid uid to allow/deny
644 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800645 * @throws ServiceSpecificException in case of failure, with an error code indicating the
646 * cause of the failure.
647 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900648 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000649 throwIfPreT("setUidRule is not available on pre-T devices");
650
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000651 if (sEnableJavaBpfMap) {
652 final long match = getMatchByFirewallChain(childChain);
653 final boolean isAllowList = isFirewallAllowList(childChain);
654 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
655 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000656
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000657 if (add) {
658 addRule(uid, match, "setUidRule");
659 } else {
660 removeRule(uid, match, "setUidRule");
661 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000662 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000663 final int err = native_setUidRule(childChain, uid, firewallRule);
664 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000665 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800666 }
667
668 /**
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900669 * Get firewall rule of specified firewall chain on specified uid.
670 *
671 * @param childChain target chain
672 * @param uid target uid
673 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
674 * @throws UnsupportedOperationException if called on pre-T devices.
675 * @throws ServiceSpecificException in case of failure, with an error code indicating the
676 * cause of the failure.
677 */
678 public int getUidRule(final int childChain, final int uid) {
679 throwIfPreT("isUidChainEnabled is not available on pre-T devices");
680
681 final long match = getMatchByFirewallChain(childChain);
682 final boolean isAllowList = isFirewallAllowList(childChain);
683 try {
684 final UidOwnerValue uidMatch = sUidOwnerMap.getValue(new S32(uid));
685 final boolean isMatchEnabled = uidMatch != null && (uidMatch.rule & match) != 0;
686 return isMatchEnabled == isAllowList ? FIREWALL_RULE_ALLOW : FIREWALL_RULE_DENY;
687 } catch (ErrnoException e) {
688 throw new ServiceSpecificException(e.errno,
689 "Unable to get uid rule status: " + Os.strerror(e.errno));
690 }
691 }
692
Motomu Utsumid44a33a2023-03-28 18:08:12 +0900693 private Set<Integer> getUidsMatchEnabled(final int childChain) throws ErrnoException {
694 final long match = getMatchByFirewallChain(childChain);
695 Set<Integer> uids = new ArraySet<>();
696 synchronized (sUidOwnerMap) {
697 sUidOwnerMap.forEach((uid, val) -> {
698 if (val == null) {
699 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
700 } else {
701 if ((val.rule & match) != 0) {
702 uids.add(uid.val);
703 }
704 }
705 });
706 }
707 return uids;
708 }
709
710 /**
711 * Get uids that has FIREWALL_RULE_ALLOW on allowlist chain.
712 * Allowlist means the firewall denies all by default, uids must be explicitly allowed.
713 *
714 * Note that uids that has FIREWALL_RULE_DENY on allowlist chain can not be computed from the
715 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_ALLOW rule in bpf map
716 * are determined to have FIREWALL_RULE_DENY.
717 *
718 * @param childChain target chain
719 * @return Set of uids
720 */
721 public Set<Integer> getUidsWithAllowRuleOnAllowListChain(final int childChain)
722 throws ErrnoException {
723 if (!isFirewallAllowList(childChain)) {
724 throw new IllegalArgumentException("getUidsWithAllowRuleOnAllowListChain is called with"
725 + " denylist chain:" + childChain);
726 }
727 // Corresponding match is enabled for uids that has FIREWALL_RULE_ALLOW on allowlist chain.
728 return getUidsMatchEnabled(childChain);
729 }
730
731 /**
732 * Get uids that has FIREWALL_RULE_DENY on denylist chain.
733 * Denylist means the firewall allows all by default, uids must be explicitly denyed
734 *
735 * Note that uids that has FIREWALL_RULE_ALLOW on denylist chain can not be computed from the
736 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_DENY rule in bpf map
737 * are determined to have the FIREWALL_RULE_ALLOW.
738 *
739 * @param childChain target chain
740 * @return Set of uids
741 */
742 public Set<Integer> getUidsWithDenyRuleOnDenyListChain(final int childChain)
743 throws ErrnoException {
744 if (isFirewallAllowList(childChain)) {
745 throw new IllegalArgumentException("getUidsWithDenyRuleOnDenyListChain is called with"
746 + " allowlist chain:" + childChain);
747 }
748 // Corresponding match is enabled for uids that has FIREWALL_RULE_DENY on denylist chain.
749 return getUidsMatchEnabled(childChain);
750 }
751
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900752 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800753 * Add ingress interface filtering rules to a list of UIDs
754 *
755 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
756 * allowed interface and loopback to be sent to the list of UIDs.
757 *
758 * Calling this method on one or more UIDs with an existing filtering rule but a different
759 * interface name will result in the filtering rule being updated to allow the new interface
760 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
761 *
762 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800763 * be received.
764 * @param uids an array of UIDs which the filtering rules will be set
765 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800766 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800767 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800768 */
Ken Chenf5f51332022-01-28 10:08:16 +0800769 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000770 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800771 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800772 return;
773 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000774
775 if (sEnableJavaBpfMap) {
776 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
777 // ifIndex is set to 0.
778 final int ifIndex;
779 if (ifName == null) {
780 ifIndex = 0;
781 } else {
782 ifIndex = mDeps.getIfIndex(ifName);
783 if (ifIndex == 0) {
784 throw new ServiceSpecificException(ENODEV,
785 "Failed to get index of interface " + ifName);
786 }
787 }
788 for (final int uid : uids) {
789 try {
790 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
791 } catch (ServiceSpecificException e) {
792 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
793 }
794 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000795 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000796 final int err = native_addUidInterfaceRules(ifName, uids);
797 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000798 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800799 }
800
801 /**
802 * Remove ingress interface filtering rules from a list of UIDs
803 *
804 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
805 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
806 *
807 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800808 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800809 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800810 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800811 */
Ken Chenf5f51332022-01-28 10:08:16 +0800812 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000813 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800814 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800815 return;
816 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000817
818 if (sEnableJavaBpfMap) {
819 for (final int uid : uids) {
820 try {
821 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
822 } catch (ServiceSpecificException e) {
823 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
824 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000825 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000826 } else {
827 final int err = native_removeUidInterfaceRules(uids);
828 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000829 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800830 }
831
Ken Chenf5f51332022-01-28 10:08:16 +0800832 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000833 * Update lockdown rule for uid
834 *
835 * @param uid target uid to add/remove the rule
836 * @param add {@code true} to add the rule, {@code false} to remove the rule.
837 * @throws ServiceSpecificException in case of failure, with an error code indicating the
838 * cause of the failure.
839 */
840 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000841 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000842
843 if (sEnableJavaBpfMap) {
844 if (add) {
845 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
846 } else {
847 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
848 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000849 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000850 final int err = native_updateUidLockdownRule(uid, add);
851 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000852 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000853 }
854
855 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800856 * Request netd to change the current active network stats map.
857 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000858 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800859 * @throws ServiceSpecificException in case of failure, with an error code indicating the
860 * cause of the failure.
861 */
markchien49e944c2022-03-01 15:22:20 +0800862 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000863 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
864
865 if (sEnableJavaBpfMap) {
866 try {
867 synchronized (sCurrentStatsMapConfigLock) {
868 final long config = sConfigurationMap.getValue(
869 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
870 final long newConfig = (config == STATS_SELECT_MAP_A)
871 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
872 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
873 new U32(newConfig));
874 }
875 } catch (ErrnoException e) {
876 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
877 }
878
879 // After changing the config, it's needed to make sure all the current running eBPF
880 // programs are finished and all the CPUs are aware of this config change before the old
881 // map is modified. So special hack is needed here to wait for the kernel to do a
882 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
883 // be available to all cores and the next eBPF programs triggered inside the kernel will
884 // use the new map configuration. So once this function returns it is safe to modify the
885 // old stats map without concerning about race between the kernel and userspace.
886 final int err = mDeps.synchronizeKernelRCU();
887 maybeThrow(err, "synchronizeKernelRCU failed");
888 } else {
889 final int err = native_swapActiveStatsMap();
890 maybeThrow(err, "Unable to swap active stats map");
891 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800892 }
893
Ken Chenf5f51332022-01-28 10:08:16 +0800894 /**
895 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
896 * specified. Or remove all permissions from the uids.
897 *
898 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
899 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
900 * revoke all permissions for the uids.
901 * @param uids uid of users to grant permission
902 * @throws RemoteException when netd has crashed.
903 */
904 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000905 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800906 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800907 return;
908 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000909
910 if (sEnableJavaBpfMap) {
911 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
912 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
913 for (final int uid : uids) {
914 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000915 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000916 } catch (ErrnoException e) {
917 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
918 }
919 }
920 return;
921 }
922
923 for (final int uid : uids) {
924 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000925 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
Motomu Utsumi65271202022-07-05 08:21:41 +0000926 } catch (ErrnoException e) {
927 Log.e(TAG, "Failed to set permission "
928 + permissions + " to uid " + uid + ": " + e);
929 }
930 }
931 } else {
932 native_setPermissionForUids(permissions, uids);
933 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800934 }
935
Motomu Utsumi166f9662022-09-01 10:35:29 +0900936 /** Register callback for statsd to pull atom. */
937 public void setPullAtomCallback(final Context context) {
938 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
939
940 final StatsManager statsManager = context.getSystemService(StatsManager.class);
941 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
942 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
943 }
944
945 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
946 throws ErrnoException {
947 // forEach could restart iteration from the beginning if there is a concurrent entry
948 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
949 // So using Set to count the number of entry in the map.
950 Set<K> keySet = new ArraySet<>();
951 map.forEach((k, v) -> keySet.add(k));
952 return keySet.size();
953 }
954
955 /** Callback for StatsManager#setPullAtomCallback */
956 @VisibleForTesting
957 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
958 if (atomTag != NETWORK_BPF_MAP_INFO) {
959 Log.e(TAG, "Unexpected atom tag: " + atomTag);
960 return StatsManager.PULL_SKIP;
961 }
962
963 try {
964 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
965 getMapSize(sUidPermissionMap)));
966 } catch (ErrnoException e) {
967 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
968 return StatsManager.PULL_SKIP;
969 }
970 return StatsManager.PULL_SUCCESS;
971 }
972
Motomu Utsumi310850f2022-09-02 12:48:20 +0900973 private String permissionToString(int permissionMask) {
974 if (permissionMask == PERMISSION_NONE) {
975 return "PERMISSION_NONE";
976 }
977 if (permissionMask == PERMISSION_UNINSTALLED) {
978 // PERMISSION_UNINSTALLED should never appear in the map
979 return "PERMISSION_UNINSTALLED error!";
980 }
981
982 final StringJoiner sj = new StringJoiner(" ");
983 for (Pair<Integer, String> permission: PERMISSION_LIST) {
984 final int permissionFlag = permission.first;
985 final String permissionName = permission.second;
986 if ((permissionMask & permissionFlag) != 0) {
987 sj.add(permissionName);
988 permissionMask &= ~permissionFlag;
989 }
990 }
991 if (permissionMask != 0) {
992 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
993 }
994 return sj.toString();
995 }
996
Motomu Utsumi372c9b42022-09-02 19:02:56 +0900997 private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
998 try {
999 final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
1000 pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
1001 } catch (ErrnoException e) {
1002 pw.println("Failed to read ownerMatch configuration: " + e);
1003 }
1004 }
1005
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001006 private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
1007 try {
1008 final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
1009 final String currentStatsMap =
1010 (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
1011 pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
1012 } catch (ErrnoException e) {
1013 pw.println("Falied to read current statsMap configuration: " + e);
1014 }
1015 }
1016
Ken Chene6d511f2022-01-25 11:10:42 +08001017 /**
1018 * Dump BPF maps
1019 *
Motomu Utsumi310850f2022-09-02 12:48:20 +09001020 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +08001021 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +09001022 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +08001023 * @throws IOException when file descriptor is invalid.
1024 * @throws ServiceSpecificException when the method is called on an unsupported device.
1025 */
Motomu Utsumi310850f2022-09-02 12:48:20 +09001026 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +08001027 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00001028 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +08001029 throw new ServiceSpecificException(
1030 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
1031 + " devices, use dumpsys netd trafficcontroller instead.");
1032 }
Motomu Utsumidf8d2992022-09-01 17:08:27 +09001033 mDeps.nativeDump(fd, verbose);
Motomu Utsumi310850f2022-09-02 12:48:20 +09001034
Motomu Utsumi316d0572022-09-15 13:24:48 +09001035 pw.println();
1036 pw.println("sEnableJavaBpfMap: " + sEnableJavaBpfMap);
Motomu Utsumi310850f2022-09-02 12:48:20 +09001037 if (verbose) {
Motomu Utsumief546a92022-10-05 16:42:29 +09001038 pw.println();
1039 pw.println("BPF map content:");
1040 pw.increaseIndent();
1041
Motomu Utsumi372c9b42022-09-02 19:02:56 +09001042 dumpOwnerMatchConfig(pw);
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001043 dumpCurrentStatsMapConfig(pw);
1044 pw.println();
1045
Motomu Utsumief546a92022-10-05 16:42:29 +09001046 // TODO: Remove CookieTagMap content dump
1047 // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
1048 // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
1049 // need to be updated before remove the dump from BpfNetMaps.
1050 BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
1051 (key, value) -> "cookie=" + key.socketCookie
1052 + " tag=0x" + Long.toHexString(value.tag)
1053 + " uid=" + value.uid);
Motomu Utsumi956d86c2022-09-02 17:01:25 +09001054 BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
1055 (uid, match) -> {
1056 if ((match.rule & IIF_MATCH) != 0) {
1057 // TODO: convert interface index to interface name by IfaceIndexNameMap
1058 return uid.val + " " + matchToString(match.rule) + " " + match.iif;
1059 } else {
1060 return uid.val + " " + matchToString(match.rule);
1061 }
1062 });
Motomu Utsumi310850f2022-09-02 12:48:20 +09001063 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
1064 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
Motomu Utsumief546a92022-10-05 16:42:29 +09001065 pw.decreaseIndent();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001066 }
Ken Chene6d511f2022-01-25 11:10:42 +08001067 }
1068
Maciej Żenczykowski70fbfa42023-07-18 20:14:38 +00001069 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi3af8f0e2022-09-02 23:42:13 +09001070 private static native void native_init(boolean startSkDestroyListener);
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_addNaughtyApp(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_removeNaughtyApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001077
1078 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001079 private native int native_addNiceApp(int uid);
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_removeNiceApp(int uid);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001083
1084 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi114cd9c2022-08-01 02:08:35 +00001085 private native int native_setChildChain(int childChain, boolean enable);
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_replaceUidChain(String name, boolean isAllowlist, 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_setUidRule(int childChain, int uid, int firewallRule);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001092
1093 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001094 private native int native_addUidInterfaceRules(String ifName, int[] uids);
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_removeUidInterfaceRules(int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001098
1099 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +00001100 private native int native_updateUidLockdownRule(int uid, boolean add);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001101
1102 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001103 private native int native_swapActiveStatsMap();
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001104
1105 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Wayne Ma2fde98c2022-01-17 18:04:05 +08001106 private native void native_setPermissionForUids(int permissions, int[] uids);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001107
1108 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumidf8d2992022-09-01 17:08:27 +09001109 private static native void native_dump(FileDescriptor fd, boolean verbose);
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +00001110
1111 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi7abeaa42022-07-20 07:54:18 +00001112 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001113}