blob: 3dec6cca9323e58919151b1331c8cbfc335d9bcc [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;
Ken Chen24330172023-10-20 13:02:14 +080022import static android.net.BpfNetMapsConstants.DATA_SAVER_DISABLED;
23import static android.net.BpfNetMapsConstants.DATA_SAVER_ENABLED;
24import static android.net.BpfNetMapsConstants.DATA_SAVER_ENABLED_KEY;
25import static android.net.BpfNetMapsConstants.DATA_SAVER_ENABLED_MAP_PATH;
Junyu Lai29b7b632023-08-23 17:35:17 +080026import static android.net.BpfNetMapsConstants.HAPPY_BOX_MATCH;
27import static android.net.BpfNetMapsConstants.IIF_MATCH;
28import static android.net.BpfNetMapsConstants.LOCKDOWN_VPN_MATCH;
29import static android.net.BpfNetMapsConstants.PENALTY_BOX_MATCH;
30import static android.net.BpfNetMapsConstants.UID_OWNER_MAP_PATH;
31import static android.net.BpfNetMapsConstants.UID_PERMISSION_MAP_PATH;
32import static android.net.BpfNetMapsConstants.UID_RULES_CONFIGURATION_KEY;
Junyu Lai626045a2023-08-28 18:49:44 +080033import static android.net.BpfNetMapsUtils.PRE_T;
Junyu Lai29b7b632023-08-23 17:35:17 +080034import static android.net.BpfNetMapsUtils.getMatchByFirewallChain;
Junyu Laie0031522023-08-29 18:32:57 +080035import static android.net.BpfNetMapsUtils.isFirewallAllowList;
Junyu Lai29b7b632023-08-23 17:35:17 +080036import static android.net.BpfNetMapsUtils.matchToString;
Motomu Utsumi40230be2022-07-05 03:27:35 +000037import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
38import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Motomu Utsumi65271202022-07-05 08:21:41 +000039import static android.net.INetd.PERMISSION_INTERNET;
Motomu Utsumi310850f2022-09-02 12:48:20 +090040import static android.net.INetd.PERMISSION_NONE;
Motomu Utsumi65271202022-07-05 08:21:41 +000041import static android.net.INetd.PERMISSION_UNINSTALLED;
Motomu Utsumi310850f2022-09-02 12:48:20 +090042import static android.net.INetd.PERMISSION_UPDATE_DEVICE_STATS;
Motomu Utsumi18b287d2022-06-19 10:45:30 +000043import static android.system.OsConstants.EINVAL;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000044import static android.system.OsConstants.ENODEV;
Motomu Utsumi60ed3be2022-06-24 10:38:57 +000045import static android.system.OsConstants.ENOENT;
Ken Chene6d511f2022-01-25 11:10:42 +080046import static android.system.OsConstants.EOPNOTSUPP;
47
Motomu Utsumi166f9662022-09-01 10:35:29 +090048import static com.android.server.ConnectivityStatsLog.NETWORK_BPF_MAP_INFO;
49
50import android.app.StatsManager;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000051import android.content.Context;
Junyu Lai626045a2023-08-28 18:49:44 +080052import android.net.BpfNetMapsReader;
Wayne Ma2fde98c2022-01-17 18:04:05 +080053import android.net.INetd;
Junyu Lai626045a2023-08-28 18:49:44 +080054import android.net.UidOwnerValue;
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;
Motomu Utsumi310850f2022-09-02 12:48:20 +090070import com.android.net.module.util.BpfDump;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000071import com.android.net.module.util.BpfMap;
Motomu Utsumi73599a52022-08-24 11:59:21 +090072import com.android.net.module.util.IBpfMap;
Motomu Utsumi166f9662022-09-01 10:35:29 +090073import com.android.net.module.util.Struct;
Maciej Żenczykowski785793f2022-09-17 02:35:20 +000074import com.android.net.module.util.Struct.S32;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000075import com.android.net.module.util.Struct.U32;
Motomu Utsumi65271202022-07-05 08:21:41 +000076import com.android.net.module.util.Struct.U8;
Motomu Utsumib9548862022-09-06 16:30:05 +090077import com.android.net.module.util.bpf.CookieTagMapKey;
78import com.android.net.module.util.bpf.CookieTagMapValue;
Ken Chenf5f51332022-01-28 10:08:16 +080079
Ken Chene6d511f2022-01-25 11:10:42 +080080import java.io.FileDescriptor;
81import java.io.IOException;
Motomu Utsumi310850f2022-09-02 12:48:20 +090082import java.util.Arrays;
Motomu Utsumi166f9662022-09-01 10:35:29 +090083import java.util.List;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000084import java.util.Set;
Motomu Utsumi310850f2022-09-02 12:48:20 +090085import java.util.StringJoiner;
Ken Chene6d511f2022-01-25 11:10:42 +080086
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080087/**
88 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
89 *
90 * {@hide}
91 */
92public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000093 static {
94 if (!PRE_T) {
95 System.loadLibrary("service-connectivity");
96 }
97 }
98
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080099 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +0800100 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000101 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +0800102 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +0800103 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800104
Motomu Utsumi7628ea32023-08-14 11:09:02 +0900105 private static final String BPF_NET_MAPS_FORCE_DISABLE_JAVA_BPF_MAP =
106 "bpf_net_maps_force_disable_java_bpf_map";
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000107
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000108 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
109 // This entry is not accessed by others.
110 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
111 private static final Object sUidRulesConfigBpfMapLock = new Object();
112
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000113 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
114 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
115 // BpfNetMaps is an only writer of this entry.
116 private static final Object sCurrentStatsMapConfigLock = new Object();
117
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000118 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
119 private static final long STATS_SELECT_MAP_A = 0;
120 private static final long STATS_SELECT_MAP_B = 1;
121
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000122 private static IBpfMap<S32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000123 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000124 private static IBpfMap<S32, UidOwnerValue> sUidOwnerMap = null;
125 private static IBpfMap<S32, U8> sUidPermissionMap = null;
Motomu Utsumib9548862022-09-06 16:30:05 +0900126 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> sCookieTagMap = null;
Ken Chen24330172023-10-20 13:02:14 +0800127 // TODO: Add BOOL class and replace U8?
128 private static IBpfMap<S32, U8> sDataSaverEnabledMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000129
Motomu Utsumi310850f2022-09-02 12:48:20 +0900130 private static final List<Pair<Integer, String>> PERMISSION_LIST = Arrays.asList(
131 Pair.create(PERMISSION_INTERNET, "PERMISSION_INTERNET"),
132 Pair.create(PERMISSION_UPDATE_DEVICE_STATS, "PERMISSION_UPDATE_DEVICE_STATS")
133 );
134
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000135 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000136 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000137 */
138 @VisibleForTesting
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000139 public static void setConfigurationMapForTest(IBpfMap<S32, U32> configurationMap) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000140 sConfigurationMap = configurationMap;
141 }
142
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000143 /**
144 * Set uidOwnerMap for test.
145 */
146 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000147 public static void setUidOwnerMapForTest(IBpfMap<S32, UidOwnerValue> uidOwnerMap) {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000148 sUidOwnerMap = uidOwnerMap;
149 }
150
Motomu Utsumi65271202022-07-05 08:21:41 +0000151 /**
152 * Set uidPermissionMap for test.
153 */
154 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000155 public static void setUidPermissionMapForTest(IBpfMap<S32, U8> uidPermissionMap) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000156 sUidPermissionMap = uidPermissionMap;
157 }
158
Motomu Utsumib9548862022-09-06 16:30:05 +0900159 /**
160 * Set cookieTagMap for test.
161 */
162 @VisibleForTesting
163 public static void setCookieTagMapForTest(
164 IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap) {
165 sCookieTagMap = cookieTagMap;
166 }
167
Ken Chen24330172023-10-20 13:02:14 +0800168 /**
169 * Set dataSaverEnabledMap for test.
170 */
171 @VisibleForTesting
172 public static void setDataSaverEnabledMapForTest(IBpfMap<S32, U8> dataSaverEnabledMap) {
173 sDataSaverEnabledMap = dataSaverEnabledMap;
174 }
175
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000176 private static IBpfMap<S32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000177 try {
178 return new BpfMap<>(
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000179 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U32.class);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000180 } catch (ErrnoException e) {
181 throw new IllegalStateException("Cannot open netd configuration map", e);
182 }
183 }
184
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000185 private static IBpfMap<S32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000186 try {
187 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000188 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, UidOwnerValue.class);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000189 } catch (ErrnoException e) {
190 throw new IllegalStateException("Cannot open uid owner map", e);
191 }
192 }
193
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000194 private static IBpfMap<S32, U8> getUidPermissionMap() {
Motomu Utsumi65271202022-07-05 08:21:41 +0000195 try {
196 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000197 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
Motomu Utsumi65271202022-07-05 08:21:41 +0000198 } catch (ErrnoException e) {
199 throw new IllegalStateException("Cannot open uid permission map", e);
200 }
201 }
202
Motomu Utsumib9548862022-09-06 16:30:05 +0900203 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
204 try {
205 return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,
206 CookieTagMapKey.class, CookieTagMapValue.class);
207 } catch (ErrnoException e) {
208 throw new IllegalStateException("Cannot open cookie tag map", e);
209 }
210 }
211
Ken Chen24330172023-10-20 13:02:14 +0800212 private static IBpfMap<S32, U8> getDataSaverEnabledMap() {
213 try {
214 return new BpfMap<>(
215 DATA_SAVER_ENABLED_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
216 } catch (ErrnoException e) {
217 throw new IllegalStateException("Cannot open data saver enabled map", e);
218 }
219 }
220
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000221 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000222 if (sConfigurationMap == null) {
223 sConfigurationMap = getConfigurationMap();
224 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000225 try {
226 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
227 new U32(UID_RULES_DEFAULT_CONFIGURATION));
228 } catch (ErrnoException e) {
229 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
230 }
231 try {
232 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
233 new U32(STATS_SELECT_MAP_A));
234 } catch (ErrnoException e) {
235 throw new IllegalStateException("Failed to initialize current stats configuration", e);
236 }
237
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000238 if (sUidOwnerMap == null) {
239 sUidOwnerMap = getUidOwnerMap();
240 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000241 try {
242 sUidOwnerMap.clear();
243 } catch (ErrnoException e) {
244 throw new IllegalStateException("Failed to initialize uid owner map", e);
245 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000246
247 if (sUidPermissionMap == null) {
248 sUidPermissionMap = getUidPermissionMap();
249 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900250
251 if (sCookieTagMap == null) {
252 sCookieTagMap = getCookieTagMap();
253 }
Ken Chen24330172023-10-20 13:02:14 +0800254
255 if (sDataSaverEnabledMap == null) {
256 sDataSaverEnabledMap = getDataSaverEnabledMap();
257 }
258 try {
259 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(DATA_SAVER_DISABLED));
260 } catch (ErrnoException e) {
261 throw new IllegalStateException("Failed to initialize data saver configuration", e);
262 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000263 }
264
Ken Chenf5f51332022-01-28 10:08:16 +0800265 /**
266 * Initializes the class if it is not already initialized. This method will open maps but not
267 * cause any other effects. This method may be called multiple times on any thread.
268 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000269 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800270 if (sInitialized) return;
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000271 initBpfMaps();
Ken Chenf5f51332022-01-28 10:08:16 +0800272 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800273 }
274
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000275 /**
276 * Dependencies of BpfNetMaps, for injection in tests.
277 */
278 @VisibleForTesting
279 public static class Dependencies {
280 /**
281 * Get interface index.
282 */
283 public int getIfIndex(final String ifName) {
284 return Os.if_nametoindex(ifName);
285 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000286
287 /**
288 * Call synchronize_rcu()
289 */
290 public int synchronizeKernelRCU() {
291 return native_synchronizeKernelRCU();
292 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900293
294 /**
295 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
296 */
297 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
298 final int uidPermissionMapSize) {
299 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
300 uidOwnerMapSize, uidPermissionMapSize);
301 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000302 }
303
markchien49e944c2022-03-01 15:22:20 +0800304 /** Constructor used after T that doesn't need to use netd anymore. */
Junyu Lai626045a2023-08-28 18:49:44 +0800305 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000306 public BpfNetMaps(final Context context) {
307 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800308
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000309 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800310 }
311
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000312 public BpfNetMaps(final Context context, final INetd netd) {
313 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000314 }
315
316 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000317 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000318 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000319 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000320 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800321 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000322 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800323 }
324
Ken Chenf5f51332022-01-28 10:08:16 +0800325 private void maybeThrow(final int err, final String msg) {
326 if (err != 0) {
327 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
328 }
329 }
330
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000331 private void throwIfPreT(final String msg) {
332 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000333 throw new UnsupportedOperationException(msg);
334 }
335 }
336
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000337 private void removeRule(final int uid, final long match, final String caller) {
338 try {
339 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000340 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000341
342 if (oldMatch == null) {
343 throw new ServiceSpecificException(ENOENT,
344 "sUidOwnerMap does not have entry for uid: " + uid);
345 }
346
347 final UidOwnerValue newMatch = new UidOwnerValue(
348 (match == IIF_MATCH) ? 0 : oldMatch.iif,
349 oldMatch.rule & ~match
350 );
351
352 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000353 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000354 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000355 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000356 }
357 }
358 } catch (ErrnoException e) {
359 throw new ServiceSpecificException(e.errno,
360 caller + " failed to remove rule: " + Os.strerror(e.errno));
361 }
362 }
363
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000364 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000365 if (match != IIF_MATCH && iif != 0) {
366 throw new ServiceSpecificException(EINVAL,
367 "Non-interface match must have zero interface index");
368 }
369
370 try {
371 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000372 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000373
374 final UidOwnerValue newMatch;
375 if (oldMatch != null) {
376 newMatch = new UidOwnerValue(
377 (match == IIF_MATCH) ? iif : oldMatch.iif,
378 oldMatch.rule | match
379 );
380 } else {
381 newMatch = new UidOwnerValue(
382 iif,
383 match
384 );
385 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000386 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000387 }
388 } catch (ErrnoException e) {
389 throw new ServiceSpecificException(e.errno,
390 caller + " failed to add rule: " + Os.strerror(e.errno));
391 }
392 }
393
394 private void addRule(final int uid, final long match, final String caller) {
395 addRule(uid, match, 0 /* iif */, caller);
396 }
397
Ken Chenf5f51332022-01-28 10:08:16 +0800398 /**
399 * Add naughty app bandwidth rule for specific app
400 *
401 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800402 * @throws ServiceSpecificException in case of failure, with an error code indicating the
403 * cause of the failure.
404 */
Junyu Lai626045a2023-08-28 18:49:44 +0800405 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900406 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000407 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000408
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900409 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800410 }
411
Ken Chenf5f51332022-01-28 10:08:16 +0800412 /**
413 * Remove naughty app bandwidth rule for specific app
414 *
415 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800416 * @throws ServiceSpecificException in case of failure, with an error code indicating the
417 * cause of the failure.
418 */
Junyu Lai626045a2023-08-28 18:49:44 +0800419 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900420 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000421 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000422
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900423 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800424 }
425
Ken Chenf5f51332022-01-28 10:08:16 +0800426 /**
427 * Add nice app bandwidth rule for specific app
428 *
429 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800430 * @throws ServiceSpecificException in case of failure, with an error code indicating the
431 * cause of the failure.
432 */
Junyu Lai626045a2023-08-28 18:49:44 +0800433 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900434 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000435 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000436
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900437 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800438 }
439
Ken Chenf5f51332022-01-28 10:08:16 +0800440 /**
441 * Remove nice app bandwidth rule for specific app
442 *
443 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800444 * @throws ServiceSpecificException in case of failure, with an error code indicating the
445 * cause of the failure.
446 */
Junyu Lai626045a2023-08-28 18:49:44 +0800447 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900448 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000449 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000450
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900451 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800452 }
453
Ken Chenf5f51332022-01-28 10:08:16 +0800454 /**
455 * Set target firewall child chain
456 *
457 * @param childChain target chain to enable
458 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000459 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800460 * @throws ServiceSpecificException in case of failure, with an error code indicating the
461 * cause of the failure.
462 */
Junyu Lai626045a2023-08-28 18:49:44 +0800463 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900464 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000465 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000466
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900467 final long match = getMatchByFirewallChain(childChain);
468 try {
469 synchronized (sUidRulesConfigBpfMapLock) {
470 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
471 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
472 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000473 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900474 } catch (ErrnoException e) {
475 throw new ServiceSpecificException(e.errno,
476 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000477 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800478 }
479
480 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000481 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000482 *
483 * @param childChain target chain
484 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
485 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000486 * @throws ServiceSpecificException in case of failure, with an error code indicating the
487 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800488 *
489 * @deprecated Use {@link BpfNetMapsReader#isChainEnabled} instead.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000490 */
Junyu Lai626045a2023-08-28 18:49:44 +0800491 // TODO: Migrate the callers to use {@link BpfNetMapsReader#isChainEnabled} instead.
492 @Deprecated
493 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000494 public boolean isChainEnabled(final int childChain) {
Junyu Lai626045a2023-08-28 18:49:44 +0800495 return BpfNetMapsReader.isChainEnabled(sConfigurationMap, childChain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000496 }
497
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900498 private Set<Integer> asSet(final int[] uids) {
499 final Set<Integer> uidSet = new ArraySet<>();
500 for (final int uid: uids) {
501 uidSet.add(uid);
502 }
503 return uidSet;
504 }
505
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000506 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800507 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000508 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800509 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000510 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800511 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000512 * @throws UnsupportedOperationException if called on pre-T devices.
513 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800514 */
Junyu Lai626045a2023-08-28 18:49:44 +0800515 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000516 public void replaceUidChain(final int chain, final int[] uids) {
517 throwIfPreT("replaceUidChain is not available on pre-T devices");
518
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900519 final long match;
520 try {
521 match = getMatchByFirewallChain(chain);
522 } catch (ServiceSpecificException e) {
523 // Throws IllegalArgumentException to keep the behavior of
524 // ConnectivityManager#replaceFirewallChain API
525 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
526 }
527 final Set<Integer> uidSet = asSet(uids);
528 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
529 try {
530 synchronized (sUidOwnerMap) {
531 sUidOwnerMap.forEach((uid, config) -> {
532 // config could be null if there is a concurrent entry deletion.
533 // http://b/220084230. But sUidOwnerMap update must be done while holding a
534 // lock, so this should not happen.
535 if (config == null) {
536 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
537 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
538 uidSetToRemoveRule.add((int) uid.val);
539 }
540 });
Motomu Utsumic7c16852022-08-03 06:51:41 +0000541
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900542 for (final int uid : uidSetToRemoveRule) {
543 removeRule(uid, match, "replaceUidChain");
Motomu Utsumic7c16852022-08-03 06:51:41 +0000544 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900545 for (final int uid : uids) {
546 addRule(uid, match, "replaceUidChain");
547 }
Motomu Utsumic7c16852022-08-03 06:51:41 +0000548 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900549 } catch (ErrnoException | ServiceSpecificException e) {
550 Log.e(TAG, "replaceUidChain failed: " + e);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800551 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800552 }
553
Ken Chenf5f51332022-01-28 10:08:16 +0800554 /**
555 * Set firewall rule for uid
556 *
557 * @param childChain target chain
558 * @param uid uid to allow/deny
559 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800560 * @throws ServiceSpecificException in case of failure, with an error code indicating the
561 * cause of the failure.
562 */
Junyu Lai626045a2023-08-28 18:49:44 +0800563 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900564 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000565 throwIfPreT("setUidRule is not available on pre-T devices");
566
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900567 final long match = getMatchByFirewallChain(childChain);
568 final boolean isAllowList = isFirewallAllowList(childChain);
569 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
570 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000571
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900572 if (add) {
573 addRule(uid, match, "setUidRule");
Motomu Utsumi40230be2022-07-05 03:27:35 +0000574 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900575 removeRule(uid, match, "setUidRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000576 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800577 }
578
579 /**
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900580 * Get firewall rule of specified firewall chain on specified uid.
581 *
582 * @param childChain target chain
583 * @param uid target uid
584 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
585 * @throws UnsupportedOperationException if called on pre-T devices.
586 * @throws ServiceSpecificException in case of failure, with an error code indicating the
587 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800588 *
589 * @deprecated use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900590 */
Junyu Lai626045a2023-08-28 18:49:44 +0800591 // TODO: Migrate the callers to use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900592 public int getUidRule(final int childChain, final int uid) {
Junyu Lai626045a2023-08-28 18:49:44 +0800593 return BpfNetMapsReader.getUidRule(sUidOwnerMap, childChain, uid);
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900594 }
595
Motomu Utsumid44a33a2023-03-28 18:08:12 +0900596 private Set<Integer> getUidsMatchEnabled(final int childChain) throws ErrnoException {
597 final long match = getMatchByFirewallChain(childChain);
598 Set<Integer> uids = new ArraySet<>();
599 synchronized (sUidOwnerMap) {
600 sUidOwnerMap.forEach((uid, val) -> {
601 if (val == null) {
602 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
603 } else {
604 if ((val.rule & match) != 0) {
605 uids.add(uid.val);
606 }
607 }
608 });
609 }
610 return uids;
611 }
612
613 /**
614 * Get uids that has FIREWALL_RULE_ALLOW on allowlist chain.
615 * Allowlist means the firewall denies all by default, uids must be explicitly allowed.
616 *
617 * Note that uids that has FIREWALL_RULE_DENY on allowlist chain can not be computed from the
618 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_ALLOW rule in bpf map
619 * are determined to have FIREWALL_RULE_DENY.
620 *
621 * @param childChain target chain
622 * @return Set of uids
623 */
624 public Set<Integer> getUidsWithAllowRuleOnAllowListChain(final int childChain)
625 throws ErrnoException {
626 if (!isFirewallAllowList(childChain)) {
627 throw new IllegalArgumentException("getUidsWithAllowRuleOnAllowListChain is called with"
628 + " denylist chain:" + childChain);
629 }
630 // Corresponding match is enabled for uids that has FIREWALL_RULE_ALLOW on allowlist chain.
631 return getUidsMatchEnabled(childChain);
632 }
633
634 /**
635 * Get uids that has FIREWALL_RULE_DENY on denylist chain.
636 * Denylist means the firewall allows all by default, uids must be explicitly denyed
637 *
638 * Note that uids that has FIREWALL_RULE_ALLOW on denylist chain can not be computed from the
639 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_DENY rule in bpf map
640 * are determined to have the FIREWALL_RULE_ALLOW.
641 *
642 * @param childChain target chain
643 * @return Set of uids
644 */
645 public Set<Integer> getUidsWithDenyRuleOnDenyListChain(final int childChain)
646 throws ErrnoException {
647 if (isFirewallAllowList(childChain)) {
648 throw new IllegalArgumentException("getUidsWithDenyRuleOnDenyListChain is called with"
649 + " allowlist chain:" + childChain);
650 }
651 // Corresponding match is enabled for uids that has FIREWALL_RULE_DENY on denylist chain.
652 return getUidsMatchEnabled(childChain);
653 }
654
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900655 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800656 * Add ingress interface filtering rules to a list of UIDs
657 *
658 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
659 * allowed interface and loopback to be sent to the list of UIDs.
660 *
661 * Calling this method on one or more UIDs with an existing filtering rule but a different
662 * interface name will result in the filtering rule being updated to allow the new interface
663 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
664 *
665 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800666 * be received.
667 * @param uids an array of UIDs which the filtering rules will be set
668 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800669 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800670 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800671 */
Ken Chenf5f51332022-01-28 10:08:16 +0800672 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000673 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800674 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800675 return;
676 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000677
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900678 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
679 // ifIndex is set to 0.
680 final int ifIndex;
681 if (ifName == null) {
682 ifIndex = 0;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000683 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900684 ifIndex = mDeps.getIfIndex(ifName);
685 if (ifIndex == 0) {
686 throw new ServiceSpecificException(ENODEV,
687 "Failed to get index of interface " + ifName);
688 }
689 }
690 for (final int uid : uids) {
691 try {
692 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
693 } catch (ServiceSpecificException e) {
694 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
695 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000696 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800697 }
698
699 /**
700 * Remove ingress interface filtering rules from a list of UIDs
701 *
702 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
703 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
704 *
705 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800706 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800707 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800708 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800709 */
Ken Chenf5f51332022-01-28 10:08:16 +0800710 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000711 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800712 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800713 return;
714 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000715
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900716 for (final int uid : uids) {
717 try {
718 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
719 } catch (ServiceSpecificException e) {
720 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000721 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000722 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800723 }
724
Ken Chenf5f51332022-01-28 10:08:16 +0800725 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000726 * Update lockdown rule for uid
727 *
728 * @param uid target uid to add/remove the rule
729 * @param add {@code true} to add the rule, {@code false} to remove the rule.
730 * @throws ServiceSpecificException in case of failure, with an error code indicating the
731 * cause of the failure.
732 */
Junyu Lai626045a2023-08-28 18:49:44 +0800733 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000734 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000735 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000736
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900737 if (add) {
738 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi697b2992022-06-30 02:25:29 +0000739 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900740 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000741 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000742 }
743
744 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800745 * Request netd to change the current active network stats map.
746 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000747 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800748 * @throws ServiceSpecificException in case of failure, with an error code indicating the
749 * cause of the failure.
750 */
Junyu Lai626045a2023-08-28 18:49:44 +0800751 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien49e944c2022-03-01 15:22:20 +0800752 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000753 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
754
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900755 try {
756 synchronized (sCurrentStatsMapConfigLock) {
757 final long config = sConfigurationMap.getValue(
758 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
759 final long newConfig = (config == STATS_SELECT_MAP_A)
760 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
761 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
762 new U32(newConfig));
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000763 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900764 } catch (ErrnoException e) {
765 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000766 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900767
768 // After changing the config, it's needed to make sure all the current running eBPF
769 // programs are finished and all the CPUs are aware of this config change before the old
770 // map is modified. So special hack is needed here to wait for the kernel to do a
771 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
772 // be available to all cores and the next eBPF programs triggered inside the kernel will
773 // use the new map configuration. So once this function returns it is safe to modify the
774 // old stats map without concerning about race between the kernel and userspace.
775 final int err = mDeps.synchronizeKernelRCU();
776 maybeThrow(err, "synchronizeKernelRCU failed");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800777 }
778
Ken Chenf5f51332022-01-28 10:08:16 +0800779 /**
780 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
781 * specified. Or remove all permissions from the uids.
782 *
783 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
784 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
785 * revoke all permissions for the uids.
786 * @param uids uid of users to grant permission
787 * @throws RemoteException when netd has crashed.
788 */
789 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000790 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800791 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800792 return;
793 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000794
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900795 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
796 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000797 for (final int uid : uids) {
798 try {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900799 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000800 } catch (ErrnoException e) {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900801 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
Motomu Utsumi65271202022-07-05 08:21:41 +0000802 }
803 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900804 return;
805 }
806
807 for (final int uid : uids) {
808 try {
809 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
810 } catch (ErrnoException e) {
811 Log.e(TAG, "Failed to set permission "
812 + permissions + " to uid " + uid + ": " + e);
813 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000814 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800815 }
816
Ken Chen24330172023-10-20 13:02:14 +0800817 /**
818 * Set Data Saver enabled or disabled
819 *
820 * @param enable whether Data Saver is enabled or disabled.
821 * @throws UnsupportedOperationException if called on pre-T devices.
822 * @throws ServiceSpecificException in case of failure, with an error code indicating the
823 * cause of the failure.
824 */
825 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
826 public void setDataSaverEnabled(boolean enable) {
827 throwIfPreT("setDataSaverEnabled is not available on pre-T devices");
828
829 try {
830 final short config = enable ? DATA_SAVER_ENABLED : DATA_SAVER_DISABLED;
831 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(config));
832 } catch (ErrnoException e) {
833 throw new ServiceSpecificException(e.errno, "Unable to set data saver: "
834 + Os.strerror(e.errno));
835 }
836 }
837
Motomu Utsumi166f9662022-09-01 10:35:29 +0900838 /** Register callback for statsd to pull atom. */
Junyu Lai626045a2023-08-28 18:49:44 +0800839 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi166f9662022-09-01 10:35:29 +0900840 public void setPullAtomCallback(final Context context) {
841 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
842
843 final StatsManager statsManager = context.getSystemService(StatsManager.class);
844 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
845 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
846 }
847
848 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
849 throws ErrnoException {
850 // forEach could restart iteration from the beginning if there is a concurrent entry
851 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
852 // So using Set to count the number of entry in the map.
853 Set<K> keySet = new ArraySet<>();
854 map.forEach((k, v) -> keySet.add(k));
855 return keySet.size();
856 }
857
858 /** Callback for StatsManager#setPullAtomCallback */
859 @VisibleForTesting
860 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
861 if (atomTag != NETWORK_BPF_MAP_INFO) {
862 Log.e(TAG, "Unexpected atom tag: " + atomTag);
863 return StatsManager.PULL_SKIP;
864 }
865
866 try {
867 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
868 getMapSize(sUidPermissionMap)));
869 } catch (ErrnoException e) {
870 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
871 return StatsManager.PULL_SKIP;
872 }
873 return StatsManager.PULL_SUCCESS;
874 }
875
Motomu Utsumi310850f2022-09-02 12:48:20 +0900876 private String permissionToString(int permissionMask) {
877 if (permissionMask == PERMISSION_NONE) {
878 return "PERMISSION_NONE";
879 }
880 if (permissionMask == PERMISSION_UNINSTALLED) {
881 // PERMISSION_UNINSTALLED should never appear in the map
882 return "PERMISSION_UNINSTALLED error!";
883 }
884
885 final StringJoiner sj = new StringJoiner(" ");
886 for (Pair<Integer, String> permission: PERMISSION_LIST) {
887 final int permissionFlag = permission.first;
888 final String permissionName = permission.second;
889 if ((permissionMask & permissionFlag) != 0) {
890 sj.add(permissionName);
891 permissionMask &= ~permissionFlag;
892 }
893 }
894 if (permissionMask != 0) {
895 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
896 }
897 return sj.toString();
898 }
899
Motomu Utsumi372c9b42022-09-02 19:02:56 +0900900 private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
901 try {
902 final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
903 pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
904 } catch (ErrnoException e) {
905 pw.println("Failed to read ownerMatch configuration: " + e);
906 }
907 }
908
Motomu Utsumic675d6f2022-09-02 18:15:25 +0900909 private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
910 try {
911 final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
912 final String currentStatsMap =
913 (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
914 pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
915 } catch (ErrnoException e) {
916 pw.println("Falied to read current statsMap configuration: " + e);
917 }
918 }
919
Ken Chen24330172023-10-20 13:02:14 +0800920 private void dumpDataSaverConfig(final IndentingPrintWriter pw) {
921 try {
922 final short config = sDataSaverEnabledMap.getValue(DATA_SAVER_ENABLED_KEY).val;
923 // Any non-zero value converted from short to boolean is true by convention.
924 pw.println("sDataSaverEnabledMap: " + (config != DATA_SAVER_DISABLED));
925 } catch (ErrnoException e) {
926 pw.println("Failed to read data saver configuration: " + e);
927 }
928 }
Ken Chene6d511f2022-01-25 11:10:42 +0800929 /**
930 * Dump BPF maps
931 *
Motomu Utsumi310850f2022-09-02 12:48:20 +0900932 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +0800933 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +0900934 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +0800935 * @throws IOException when file descriptor is invalid.
936 * @throws ServiceSpecificException when the method is called on an unsupported device.
937 */
Junyu Lai626045a2023-08-28 18:49:44 +0800938 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi310850f2022-09-02 12:48:20 +0900939 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +0800940 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000941 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +0800942 throw new ServiceSpecificException(
943 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
944 + " devices, use dumpsys netd trafficcontroller instead.");
945 }
Maciej Żenczykowskid70a3302023-09-06 16:45:25 +0000946
947 pw.println("TrafficController"); // required by CTS testDumpBpfNetMaps
Motomu Utsumi310850f2022-09-02 12:48:20 +0900948
Motomu Utsumi316d0572022-09-15 13:24:48 +0900949 pw.println();
Motomu Utsumi310850f2022-09-02 12:48:20 +0900950 if (verbose) {
Motomu Utsumief546a92022-10-05 16:42:29 +0900951 pw.println();
952 pw.println("BPF map content:");
953 pw.increaseIndent();
954
Motomu Utsumi372c9b42022-09-02 19:02:56 +0900955 dumpOwnerMatchConfig(pw);
Motomu Utsumic675d6f2022-09-02 18:15:25 +0900956 dumpCurrentStatsMapConfig(pw);
957 pw.println();
958
Motomu Utsumief546a92022-10-05 16:42:29 +0900959 // TODO: Remove CookieTagMap content dump
960 // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
961 // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
962 // need to be updated before remove the dump from BpfNetMaps.
963 BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
964 (key, value) -> "cookie=" + key.socketCookie
965 + " tag=0x" + Long.toHexString(value.tag)
966 + " uid=" + value.uid);
Motomu Utsumi956d86c2022-09-02 17:01:25 +0900967 BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
968 (uid, match) -> {
969 if ((match.rule & IIF_MATCH) != 0) {
970 // TODO: convert interface index to interface name by IfaceIndexNameMap
971 return uid.val + " " + matchToString(match.rule) + " " + match.iif;
972 } else {
973 return uid.val + " " + matchToString(match.rule);
974 }
975 });
Motomu Utsumi310850f2022-09-02 12:48:20 +0900976 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
977 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
Ken Chen24330172023-10-20 13:02:14 +0800978
979 dumpDataSaverConfig(pw);
Motomu Utsumief546a92022-10-05 16:42:29 +0900980 pw.decreaseIndent();
Motomu Utsumi310850f2022-09-02 12:48:20 +0900981 }
Ken Chene6d511f2022-01-25 11:10:42 +0800982 }
983
Maciej Żenczykowski70fbfa42023-07-18 20:14:38 +0000984 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000985 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800986}