blob: d1218a2b753be7f6d5d673637e417dbf8e862e1d [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 Utsumid95a0da2022-09-03 00:40:30 +0900275 public boolean isSkDestroyListenerRunning() {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900276 return false;
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900277 }
278
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000279 /**
280 * Dependencies of BpfNetMaps, for injection in tests.
281 */
282 @VisibleForTesting
283 public static class Dependencies {
284 /**
285 * Get interface index.
286 */
287 public int getIfIndex(final String ifName) {
288 return Os.if_nametoindex(ifName);
289 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000290
291 /**
292 * Call synchronize_rcu()
293 */
294 public int synchronizeKernelRCU() {
295 return native_synchronizeKernelRCU();
296 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900297
298 /**
299 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
300 */
301 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
302 final int uidPermissionMapSize) {
303 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
304 uidOwnerMapSize, uidPermissionMapSize);
305 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000306 }
307
markchien49e944c2022-03-01 15:22:20 +0800308 /** Constructor used after T that doesn't need to use netd anymore. */
Junyu Lai626045a2023-08-28 18:49:44 +0800309 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000310 public BpfNetMaps(final Context context) {
311 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800312
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000313 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800314 }
315
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000316 public BpfNetMaps(final Context context, final INetd netd) {
317 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000318 }
319
320 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000321 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000322 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000323 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000324 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800325 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000326 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800327 }
328
Ken Chenf5f51332022-01-28 10:08:16 +0800329 private void maybeThrow(final int err, final String msg) {
330 if (err != 0) {
331 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
332 }
333 }
334
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000335 private void throwIfPreT(final String msg) {
336 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000337 throw new UnsupportedOperationException(msg);
338 }
339 }
340
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000341 private void removeRule(final int uid, final long match, final String caller) {
342 try {
343 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000344 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000345
346 if (oldMatch == null) {
347 throw new ServiceSpecificException(ENOENT,
348 "sUidOwnerMap does not have entry for uid: " + uid);
349 }
350
351 final UidOwnerValue newMatch = new UidOwnerValue(
352 (match == IIF_MATCH) ? 0 : oldMatch.iif,
353 oldMatch.rule & ~match
354 );
355
356 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000357 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000358 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000359 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000360 }
361 }
362 } catch (ErrnoException e) {
363 throw new ServiceSpecificException(e.errno,
364 caller + " failed to remove rule: " + Os.strerror(e.errno));
365 }
366 }
367
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000368 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000369 if (match != IIF_MATCH && iif != 0) {
370 throw new ServiceSpecificException(EINVAL,
371 "Non-interface match must have zero interface index");
372 }
373
374 try {
375 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000376 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000377
378 final UidOwnerValue newMatch;
379 if (oldMatch != null) {
380 newMatch = new UidOwnerValue(
381 (match == IIF_MATCH) ? iif : oldMatch.iif,
382 oldMatch.rule | match
383 );
384 } else {
385 newMatch = new UidOwnerValue(
386 iif,
387 match
388 );
389 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000390 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000391 }
392 } catch (ErrnoException e) {
393 throw new ServiceSpecificException(e.errno,
394 caller + " failed to add rule: " + Os.strerror(e.errno));
395 }
396 }
397
398 private void addRule(final int uid, final long match, final String caller) {
399 addRule(uid, match, 0 /* iif */, caller);
400 }
401
Ken Chenf5f51332022-01-28 10:08:16 +0800402 /**
403 * Add naughty app bandwidth rule for specific app
404 *
405 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800406 * @throws ServiceSpecificException in case of failure, with an error code indicating the
407 * cause of the failure.
408 */
Junyu Lai626045a2023-08-28 18:49:44 +0800409 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900410 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000411 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000412
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900413 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800414 }
415
Ken Chenf5f51332022-01-28 10:08:16 +0800416 /**
417 * Remove naughty app bandwidth rule for specific app
418 *
419 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800420 * @throws ServiceSpecificException in case of failure, with an error code indicating the
421 * cause of the failure.
422 */
Junyu Lai626045a2023-08-28 18:49:44 +0800423 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900424 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000425 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000426
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900427 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800428 }
429
Ken Chenf5f51332022-01-28 10:08:16 +0800430 /**
431 * Add nice app bandwidth rule for specific app
432 *
433 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800434 * @throws ServiceSpecificException in case of failure, with an error code indicating the
435 * cause of the failure.
436 */
Junyu Lai626045a2023-08-28 18:49:44 +0800437 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900438 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000439 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000440
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900441 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800442 }
443
Ken Chenf5f51332022-01-28 10:08:16 +0800444 /**
445 * Remove nice app bandwidth rule for specific app
446 *
447 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800448 * @throws ServiceSpecificException in case of failure, with an error code indicating the
449 * cause of the failure.
450 */
Junyu Lai626045a2023-08-28 18:49:44 +0800451 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900452 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000453 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000454
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900455 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800456 }
457
Ken Chenf5f51332022-01-28 10:08:16 +0800458 /**
459 * Set target firewall child chain
460 *
461 * @param childChain target chain to enable
462 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000463 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800464 * @throws ServiceSpecificException in case of failure, with an error code indicating the
465 * cause of the failure.
466 */
Junyu Lai626045a2023-08-28 18:49:44 +0800467 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900468 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000469 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000470
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900471 final long match = getMatchByFirewallChain(childChain);
472 try {
473 synchronized (sUidRulesConfigBpfMapLock) {
474 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
475 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
476 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000477 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900478 } catch (ErrnoException e) {
479 throw new ServiceSpecificException(e.errno,
480 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000481 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800482 }
483
484 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000485 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000486 *
487 * @param childChain target chain
488 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
489 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000490 * @throws ServiceSpecificException in case of failure, with an error code indicating the
491 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800492 *
493 * @deprecated Use {@link BpfNetMapsReader#isChainEnabled} instead.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000494 */
Junyu Lai626045a2023-08-28 18:49:44 +0800495 // TODO: Migrate the callers to use {@link BpfNetMapsReader#isChainEnabled} instead.
496 @Deprecated
497 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000498 public boolean isChainEnabled(final int childChain) {
Junyu Lai626045a2023-08-28 18:49:44 +0800499 return BpfNetMapsReader.isChainEnabled(sConfigurationMap, childChain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000500 }
501
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900502 private Set<Integer> asSet(final int[] uids) {
503 final Set<Integer> uidSet = new ArraySet<>();
504 for (final int uid: uids) {
505 uidSet.add(uid);
506 }
507 return uidSet;
508 }
509
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000510 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800511 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000512 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800513 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000514 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800515 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000516 * @throws UnsupportedOperationException if called on pre-T devices.
517 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800518 */
Junyu Lai626045a2023-08-28 18:49:44 +0800519 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000520 public void replaceUidChain(final int chain, final int[] uids) {
521 throwIfPreT("replaceUidChain is not available on pre-T devices");
522
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900523 final long match;
524 try {
525 match = getMatchByFirewallChain(chain);
526 } catch (ServiceSpecificException e) {
527 // Throws IllegalArgumentException to keep the behavior of
528 // ConnectivityManager#replaceFirewallChain API
529 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
530 }
531 final Set<Integer> uidSet = asSet(uids);
532 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
533 try {
534 synchronized (sUidOwnerMap) {
535 sUidOwnerMap.forEach((uid, config) -> {
536 // config could be null if there is a concurrent entry deletion.
537 // http://b/220084230. But sUidOwnerMap update must be done while holding a
538 // lock, so this should not happen.
539 if (config == null) {
540 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
541 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
542 uidSetToRemoveRule.add((int) uid.val);
543 }
544 });
Motomu Utsumic7c16852022-08-03 06:51:41 +0000545
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900546 for (final int uid : uidSetToRemoveRule) {
547 removeRule(uid, match, "replaceUidChain");
Motomu Utsumic7c16852022-08-03 06:51:41 +0000548 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900549 for (final int uid : uids) {
550 addRule(uid, match, "replaceUidChain");
551 }
Motomu Utsumic7c16852022-08-03 06:51:41 +0000552 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900553 } catch (ErrnoException | ServiceSpecificException e) {
554 Log.e(TAG, "replaceUidChain failed: " + e);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800555 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800556 }
557
Ken Chenf5f51332022-01-28 10:08:16 +0800558 /**
559 * Set firewall rule for uid
560 *
561 * @param childChain target chain
562 * @param uid uid to allow/deny
563 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800564 * @throws ServiceSpecificException in case of failure, with an error code indicating the
565 * cause of the failure.
566 */
Junyu Lai626045a2023-08-28 18:49:44 +0800567 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900568 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000569 throwIfPreT("setUidRule is not available on pre-T devices");
570
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900571 final long match = getMatchByFirewallChain(childChain);
572 final boolean isAllowList = isFirewallAllowList(childChain);
573 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
574 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000575
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900576 if (add) {
577 addRule(uid, match, "setUidRule");
Motomu Utsumi40230be2022-07-05 03:27:35 +0000578 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900579 removeRule(uid, match, "setUidRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000580 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800581 }
582
583 /**
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900584 * Get firewall rule of specified firewall chain on specified uid.
585 *
586 * @param childChain target chain
587 * @param uid target uid
588 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
589 * @throws UnsupportedOperationException if called on pre-T devices.
590 * @throws ServiceSpecificException in case of failure, with an error code indicating the
591 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800592 *
593 * @deprecated use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900594 */
Junyu Lai626045a2023-08-28 18:49:44 +0800595 // TODO: Migrate the callers to use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900596 public int getUidRule(final int childChain, final int uid) {
Junyu Lai626045a2023-08-28 18:49:44 +0800597 return BpfNetMapsReader.getUidRule(sUidOwnerMap, childChain, uid);
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900598 }
599
Motomu Utsumid44a33a2023-03-28 18:08:12 +0900600 private Set<Integer> getUidsMatchEnabled(final int childChain) throws ErrnoException {
601 final long match = getMatchByFirewallChain(childChain);
602 Set<Integer> uids = new ArraySet<>();
603 synchronized (sUidOwnerMap) {
604 sUidOwnerMap.forEach((uid, val) -> {
605 if (val == null) {
606 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
607 } else {
608 if ((val.rule & match) != 0) {
609 uids.add(uid.val);
610 }
611 }
612 });
613 }
614 return uids;
615 }
616
617 /**
618 * Get uids that has FIREWALL_RULE_ALLOW on allowlist chain.
619 * Allowlist means the firewall denies all by default, uids must be explicitly allowed.
620 *
621 * Note that uids that has FIREWALL_RULE_DENY on allowlist chain can not be computed from the
622 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_ALLOW rule in bpf map
623 * are determined to have FIREWALL_RULE_DENY.
624 *
625 * @param childChain target chain
626 * @return Set of uids
627 */
628 public Set<Integer> getUidsWithAllowRuleOnAllowListChain(final int childChain)
629 throws ErrnoException {
630 if (!isFirewallAllowList(childChain)) {
631 throw new IllegalArgumentException("getUidsWithAllowRuleOnAllowListChain is called with"
632 + " denylist chain:" + childChain);
633 }
634 // Corresponding match is enabled for uids that has FIREWALL_RULE_ALLOW on allowlist chain.
635 return getUidsMatchEnabled(childChain);
636 }
637
638 /**
639 * Get uids that has FIREWALL_RULE_DENY on denylist chain.
640 * Denylist means the firewall allows all by default, uids must be explicitly denyed
641 *
642 * Note that uids that has FIREWALL_RULE_ALLOW on denylist chain can not be computed from the
643 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_DENY rule in bpf map
644 * are determined to have the FIREWALL_RULE_ALLOW.
645 *
646 * @param childChain target chain
647 * @return Set of uids
648 */
649 public Set<Integer> getUidsWithDenyRuleOnDenyListChain(final int childChain)
650 throws ErrnoException {
651 if (isFirewallAllowList(childChain)) {
652 throw new IllegalArgumentException("getUidsWithDenyRuleOnDenyListChain is called with"
653 + " allowlist chain:" + childChain);
654 }
655 // Corresponding match is enabled for uids that has FIREWALL_RULE_DENY on denylist chain.
656 return getUidsMatchEnabled(childChain);
657 }
658
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900659 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800660 * Add ingress interface filtering rules to a list of UIDs
661 *
662 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
663 * allowed interface and loopback to be sent to the list of UIDs.
664 *
665 * Calling this method on one or more UIDs with an existing filtering rule but a different
666 * interface name will result in the filtering rule being updated to allow the new interface
667 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
668 *
669 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800670 * be received.
671 * @param uids an array of UIDs which the filtering rules will be set
672 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800673 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800674 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800675 */
Ken Chenf5f51332022-01-28 10:08:16 +0800676 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000677 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800678 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800679 return;
680 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000681
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900682 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
683 // ifIndex is set to 0.
684 final int ifIndex;
685 if (ifName == null) {
686 ifIndex = 0;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000687 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900688 ifIndex = mDeps.getIfIndex(ifName);
689 if (ifIndex == 0) {
690 throw new ServiceSpecificException(ENODEV,
691 "Failed to get index of interface " + ifName);
692 }
693 }
694 for (final int uid : uids) {
695 try {
696 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
697 } catch (ServiceSpecificException e) {
698 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
699 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000700 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800701 }
702
703 /**
704 * Remove ingress interface filtering rules from a list of UIDs
705 *
706 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
707 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
708 *
709 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800710 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800711 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800712 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800713 */
Ken Chenf5f51332022-01-28 10:08:16 +0800714 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000715 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800716 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800717 return;
718 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000719
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900720 for (final int uid : uids) {
721 try {
722 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
723 } catch (ServiceSpecificException e) {
724 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000725 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000726 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800727 }
728
Ken Chenf5f51332022-01-28 10:08:16 +0800729 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000730 * Update lockdown rule for uid
731 *
732 * @param uid target uid to add/remove the rule
733 * @param add {@code true} to add the rule, {@code false} to remove the rule.
734 * @throws ServiceSpecificException in case of failure, with an error code indicating the
735 * cause of the failure.
736 */
Junyu Lai626045a2023-08-28 18:49:44 +0800737 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000738 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000739 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000740
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900741 if (add) {
742 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi697b2992022-06-30 02:25:29 +0000743 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900744 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000745 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000746 }
747
748 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800749 * Request netd to change the current active network stats map.
750 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000751 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800752 * @throws ServiceSpecificException in case of failure, with an error code indicating the
753 * cause of the failure.
754 */
Junyu Lai626045a2023-08-28 18:49:44 +0800755 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien49e944c2022-03-01 15:22:20 +0800756 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000757 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
758
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900759 try {
760 synchronized (sCurrentStatsMapConfigLock) {
761 final long config = sConfigurationMap.getValue(
762 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
763 final long newConfig = (config == STATS_SELECT_MAP_A)
764 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
765 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
766 new U32(newConfig));
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000767 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900768 } catch (ErrnoException e) {
769 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000770 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900771
772 // After changing the config, it's needed to make sure all the current running eBPF
773 // programs are finished and all the CPUs are aware of this config change before the old
774 // map is modified. So special hack is needed here to wait for the kernel to do a
775 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
776 // be available to all cores and the next eBPF programs triggered inside the kernel will
777 // use the new map configuration. So once this function returns it is safe to modify the
778 // old stats map without concerning about race between the kernel and userspace.
779 final int err = mDeps.synchronizeKernelRCU();
780 maybeThrow(err, "synchronizeKernelRCU failed");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800781 }
782
Ken Chenf5f51332022-01-28 10:08:16 +0800783 /**
784 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
785 * specified. Or remove all permissions from the uids.
786 *
787 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
788 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
789 * revoke all permissions for the uids.
790 * @param uids uid of users to grant permission
791 * @throws RemoteException when netd has crashed.
792 */
793 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000794 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800795 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800796 return;
797 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000798
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900799 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
800 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000801 for (final int uid : uids) {
802 try {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900803 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000804 } catch (ErrnoException e) {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900805 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
Motomu Utsumi65271202022-07-05 08:21:41 +0000806 }
807 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900808 return;
809 }
810
811 for (final int uid : uids) {
812 try {
813 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
814 } catch (ErrnoException e) {
815 Log.e(TAG, "Failed to set permission "
816 + permissions + " to uid " + uid + ": " + e);
817 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000818 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800819 }
820
Ken Chen24330172023-10-20 13:02:14 +0800821 /**
822 * Set Data Saver enabled or disabled
823 *
824 * @param enable whether Data Saver is enabled or disabled.
825 * @throws UnsupportedOperationException if called on pre-T devices.
826 * @throws ServiceSpecificException in case of failure, with an error code indicating the
827 * cause of the failure.
828 */
829 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
830 public void setDataSaverEnabled(boolean enable) {
831 throwIfPreT("setDataSaverEnabled is not available on pre-T devices");
832
833 try {
834 final short config = enable ? DATA_SAVER_ENABLED : DATA_SAVER_DISABLED;
835 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(config));
836 } catch (ErrnoException e) {
837 throw new ServiceSpecificException(e.errno, "Unable to set data saver: "
838 + Os.strerror(e.errno));
839 }
840 }
841
Motomu Utsumi166f9662022-09-01 10:35:29 +0900842 /** Register callback for statsd to pull atom. */
Junyu Lai626045a2023-08-28 18:49:44 +0800843 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi166f9662022-09-01 10:35:29 +0900844 public void setPullAtomCallback(final Context context) {
845 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
846
847 final StatsManager statsManager = context.getSystemService(StatsManager.class);
848 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
849 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
850 }
851
852 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
853 throws ErrnoException {
854 // forEach could restart iteration from the beginning if there is a concurrent entry
855 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
856 // So using Set to count the number of entry in the map.
857 Set<K> keySet = new ArraySet<>();
858 map.forEach((k, v) -> keySet.add(k));
859 return keySet.size();
860 }
861
862 /** Callback for StatsManager#setPullAtomCallback */
863 @VisibleForTesting
864 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
865 if (atomTag != NETWORK_BPF_MAP_INFO) {
866 Log.e(TAG, "Unexpected atom tag: " + atomTag);
867 return StatsManager.PULL_SKIP;
868 }
869
870 try {
871 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
872 getMapSize(sUidPermissionMap)));
873 } catch (ErrnoException e) {
874 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
875 return StatsManager.PULL_SKIP;
876 }
877 return StatsManager.PULL_SUCCESS;
878 }
879
Motomu Utsumi310850f2022-09-02 12:48:20 +0900880 private String permissionToString(int permissionMask) {
881 if (permissionMask == PERMISSION_NONE) {
882 return "PERMISSION_NONE";
883 }
884 if (permissionMask == PERMISSION_UNINSTALLED) {
885 // PERMISSION_UNINSTALLED should never appear in the map
886 return "PERMISSION_UNINSTALLED error!";
887 }
888
889 final StringJoiner sj = new StringJoiner(" ");
890 for (Pair<Integer, String> permission: PERMISSION_LIST) {
891 final int permissionFlag = permission.first;
892 final String permissionName = permission.second;
893 if ((permissionMask & permissionFlag) != 0) {
894 sj.add(permissionName);
895 permissionMask &= ~permissionFlag;
896 }
897 }
898 if (permissionMask != 0) {
899 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
900 }
901 return sj.toString();
902 }
903
Motomu Utsumi372c9b42022-09-02 19:02:56 +0900904 private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
905 try {
906 final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
907 pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
908 } catch (ErrnoException e) {
909 pw.println("Failed to read ownerMatch configuration: " + e);
910 }
911 }
912
Motomu Utsumic675d6f2022-09-02 18:15:25 +0900913 private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
914 try {
915 final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
916 final String currentStatsMap =
917 (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
918 pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
919 } catch (ErrnoException e) {
920 pw.println("Falied to read current statsMap configuration: " + e);
921 }
922 }
923
Ken Chen24330172023-10-20 13:02:14 +0800924 private void dumpDataSaverConfig(final IndentingPrintWriter pw) {
925 try {
926 final short config = sDataSaverEnabledMap.getValue(DATA_SAVER_ENABLED_KEY).val;
927 // Any non-zero value converted from short to boolean is true by convention.
928 pw.println("sDataSaverEnabledMap: " + (config != DATA_SAVER_DISABLED));
929 } catch (ErrnoException e) {
930 pw.println("Failed to read data saver configuration: " + e);
931 }
932 }
Ken Chene6d511f2022-01-25 11:10:42 +0800933 /**
934 * Dump BPF maps
935 *
Motomu Utsumi310850f2022-09-02 12:48:20 +0900936 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +0800937 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +0900938 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +0800939 * @throws IOException when file descriptor is invalid.
940 * @throws ServiceSpecificException when the method is called on an unsupported device.
941 */
Junyu Lai626045a2023-08-28 18:49:44 +0800942 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi310850f2022-09-02 12:48:20 +0900943 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +0800944 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000945 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +0800946 throw new ServiceSpecificException(
947 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
948 + " devices, use dumpsys netd trafficcontroller instead.");
949 }
Maciej Żenczykowskid70a3302023-09-06 16:45:25 +0000950
951 pw.println("TrafficController"); // required by CTS testDumpBpfNetMaps
Motomu Utsumi310850f2022-09-02 12:48:20 +0900952
Motomu Utsumi316d0572022-09-15 13:24:48 +0900953 pw.println();
Motomu Utsumi310850f2022-09-02 12:48:20 +0900954 if (verbose) {
Motomu Utsumief546a92022-10-05 16:42:29 +0900955 pw.println();
956 pw.println("BPF map content:");
957 pw.increaseIndent();
958
Motomu Utsumi372c9b42022-09-02 19:02:56 +0900959 dumpOwnerMatchConfig(pw);
Motomu Utsumic675d6f2022-09-02 18:15:25 +0900960 dumpCurrentStatsMapConfig(pw);
961 pw.println();
962
Motomu Utsumief546a92022-10-05 16:42:29 +0900963 // TODO: Remove CookieTagMap content dump
964 // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
965 // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
966 // need to be updated before remove the dump from BpfNetMaps.
967 BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
968 (key, value) -> "cookie=" + key.socketCookie
969 + " tag=0x" + Long.toHexString(value.tag)
970 + " uid=" + value.uid);
Motomu Utsumi956d86c2022-09-02 17:01:25 +0900971 BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
972 (uid, match) -> {
973 if ((match.rule & IIF_MATCH) != 0) {
974 // TODO: convert interface index to interface name by IfaceIndexNameMap
975 return uid.val + " " + matchToString(match.rule) + " " + match.iif;
976 } else {
977 return uid.val + " " + matchToString(match.rule);
978 }
979 });
Motomu Utsumi310850f2022-09-02 12:48:20 +0900980 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
981 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
Ken Chen24330172023-10-20 13:02:14 +0800982
983 dumpDataSaverConfig(pw);
Motomu Utsumief546a92022-10-05 16:42:29 +0900984 pw.decreaseIndent();
Motomu Utsumi310850f2022-09-02 12:48:20 +0900985 }
Ken Chene6d511f2022-01-25 11:10:42 +0800986 }
987
Maciej Żenczykowski70fbfa42023-07-18 20:14:38 +0000988 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000989 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800990}