blob: a76d594a9fb11a8b5761f41bed5af29c15b68f84 [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;
Motomu Utsumi77b49992023-10-23 17:06:12 +090028import static android.net.BpfNetMapsConstants.INGRESS_DISCARD_MAP_PATH;
Junyu Lai29b7b632023-08-23 17:35:17 +080029import static android.net.BpfNetMapsConstants.LOCKDOWN_VPN_MATCH;
30import static android.net.BpfNetMapsConstants.PENALTY_BOX_MATCH;
31import static android.net.BpfNetMapsConstants.UID_OWNER_MAP_PATH;
32import static android.net.BpfNetMapsConstants.UID_PERMISSION_MAP_PATH;
33import static android.net.BpfNetMapsConstants.UID_RULES_CONFIGURATION_KEY;
Junyu Lai626045a2023-08-28 18:49:44 +080034import static android.net.BpfNetMapsUtils.PRE_T;
Junyu Lai29b7b632023-08-23 17:35:17 +080035import static android.net.BpfNetMapsUtils.getMatchByFirewallChain;
Junyu Laie0031522023-08-29 18:32:57 +080036import static android.net.BpfNetMapsUtils.isFirewallAllowList;
Junyu Lai29b7b632023-08-23 17:35:17 +080037import static android.net.BpfNetMapsUtils.matchToString;
Motomu Utsumi40230be2022-07-05 03:27:35 +000038import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
39import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Motomu Utsumi65271202022-07-05 08:21:41 +000040import static android.net.INetd.PERMISSION_INTERNET;
Motomu Utsumi310850f2022-09-02 12:48:20 +090041import static android.net.INetd.PERMISSION_NONE;
Motomu Utsumi65271202022-07-05 08:21:41 +000042import static android.net.INetd.PERMISSION_UNINSTALLED;
Motomu Utsumi310850f2022-09-02 12:48:20 +090043import static android.net.INetd.PERMISSION_UPDATE_DEVICE_STATS;
Motomu Utsumi18b287d2022-06-19 10:45:30 +000044import static android.system.OsConstants.EINVAL;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000045import static android.system.OsConstants.ENODEV;
Motomu Utsumi60ed3be2022-06-24 10:38:57 +000046import static android.system.OsConstants.ENOENT;
Ken Chene6d511f2022-01-25 11:10:42 +080047import static android.system.OsConstants.EOPNOTSUPP;
48
Motomu Utsumi166f9662022-09-01 10:35:29 +090049import static com.android.server.ConnectivityStatsLog.NETWORK_BPF_MAP_INFO;
50
51import android.app.StatsManager;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000052import android.content.Context;
Junyu Lai626045a2023-08-28 18:49:44 +080053import android.net.BpfNetMapsReader;
Wayne Ma2fde98c2022-01-17 18:04:05 +080054import android.net.INetd;
Junyu Lai626045a2023-08-28 18:49:44 +080055import android.net.UidOwnerValue;
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +000056import android.os.Build;
Wayne Ma2fde98c2022-01-17 18:04:05 +080057import android.os.RemoteException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080058import android.os.ServiceSpecificException;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000059import android.system.ErrnoException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080060import android.system.Os;
Motomu Utsumi1a477b02022-08-23 15:14:56 +090061import android.util.ArraySet;
Motomu Utsumi310850f2022-09-02 12:48:20 +090062import android.util.IndentingPrintWriter;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080063import android.util.Log;
Motomu Utsumi310850f2022-09-02 12:48:20 +090064import android.util.Pair;
Motomu Utsumi166f9662022-09-01 10:35:29 +090065import android.util.StatsEvent;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080066
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +000067import androidx.annotation.RequiresApi;
68
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000069import com.android.internal.annotations.VisibleForTesting;
Motomu Utsumi166f9662022-09-01 10:35:29 +090070import com.android.modules.utils.BackgroundThread;
Motomu Utsumi310850f2022-09-02 12:48:20 +090071import com.android.net.module.util.BpfDump;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000072import com.android.net.module.util.BpfMap;
Motomu Utsumi73599a52022-08-24 11:59:21 +090073import com.android.net.module.util.IBpfMap;
Motomu Utsumi166f9662022-09-01 10:35:29 +090074import com.android.net.module.util.Struct;
Maciej Żenczykowski785793f2022-09-17 02:35:20 +000075import com.android.net.module.util.Struct.S32;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000076import com.android.net.module.util.Struct.U32;
Motomu Utsumi65271202022-07-05 08:21:41 +000077import com.android.net.module.util.Struct.U8;
Motomu Utsumib9548862022-09-06 16:30:05 +090078import com.android.net.module.util.bpf.CookieTagMapKey;
79import com.android.net.module.util.bpf.CookieTagMapValue;
Motomu Utsumi77b49992023-10-23 17:06:12 +090080import com.android.net.module.util.bpf.IngressDiscardKey;
81import com.android.net.module.util.bpf.IngressDiscardValue;
Ken Chenf5f51332022-01-28 10:08:16 +080082
Ken Chene6d511f2022-01-25 11:10:42 +080083import java.io.FileDescriptor;
84import java.io.IOException;
Motomu Utsumi77b49992023-10-23 17:06:12 +090085import java.net.InetAddress;
Motomu Utsumi310850f2022-09-02 12:48:20 +090086import java.util.Arrays;
Motomu Utsumi166f9662022-09-01 10:35:29 +090087import java.util.List;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000088import java.util.Set;
Motomu Utsumi310850f2022-09-02 12:48:20 +090089import java.util.StringJoiner;
Ken Chene6d511f2022-01-25 11:10:42 +080090
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080091/**
92 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
93 *
94 * {@hide}
95 */
96public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000097 static {
98 if (!PRE_T) {
99 System.loadLibrary("service-connectivity");
100 }
101 }
102
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800103 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +0800104 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000105 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +0800106 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +0800107 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800108
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000109 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
110 // This entry is not accessed by others.
111 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
112 private static final Object sUidRulesConfigBpfMapLock = new Object();
113
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000114 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
115 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
116 // BpfNetMaps is an only writer of this entry.
117 private static final Object sCurrentStatsMapConfigLock = new Object();
118
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000119 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
120 private static final long STATS_SELECT_MAP_A = 0;
121 private static final long STATS_SELECT_MAP_B = 1;
122
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000123 private static IBpfMap<S32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000124 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000125 private static IBpfMap<S32, UidOwnerValue> sUidOwnerMap = null;
126 private static IBpfMap<S32, U8> sUidPermissionMap = null;
Motomu Utsumib9548862022-09-06 16:30:05 +0900127 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> sCookieTagMap = null;
Ken Chen24330172023-10-20 13:02:14 +0800128 // TODO: Add BOOL class and replace U8?
129 private static IBpfMap<S32, U8> sDataSaverEnabledMap = null;
Motomu Utsumi77b49992023-10-23 17:06:12 +0900130 private static IBpfMap<IngressDiscardKey, IngressDiscardValue> sIngressDiscardMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000131
Motomu Utsumi310850f2022-09-02 12:48:20 +0900132 private static final List<Pair<Integer, String>> PERMISSION_LIST = Arrays.asList(
133 Pair.create(PERMISSION_INTERNET, "PERMISSION_INTERNET"),
134 Pair.create(PERMISSION_UPDATE_DEVICE_STATS, "PERMISSION_UPDATE_DEVICE_STATS")
135 );
136
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000137 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000138 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000139 */
140 @VisibleForTesting
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000141 public static void setConfigurationMapForTest(IBpfMap<S32, U32> configurationMap) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000142 sConfigurationMap = configurationMap;
143 }
144
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000145 /**
146 * Set uidOwnerMap for test.
147 */
148 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000149 public static void setUidOwnerMapForTest(IBpfMap<S32, UidOwnerValue> uidOwnerMap) {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000150 sUidOwnerMap = uidOwnerMap;
151 }
152
Motomu Utsumi65271202022-07-05 08:21:41 +0000153 /**
154 * Set uidPermissionMap for test.
155 */
156 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000157 public static void setUidPermissionMapForTest(IBpfMap<S32, U8> uidPermissionMap) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000158 sUidPermissionMap = uidPermissionMap;
159 }
160
Motomu Utsumib9548862022-09-06 16:30:05 +0900161 /**
162 * Set cookieTagMap for test.
163 */
164 @VisibleForTesting
165 public static void setCookieTagMapForTest(
166 IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap) {
167 sCookieTagMap = cookieTagMap;
168 }
169
Ken Chen24330172023-10-20 13:02:14 +0800170 /**
171 * Set dataSaverEnabledMap for test.
172 */
173 @VisibleForTesting
174 public static void setDataSaverEnabledMapForTest(IBpfMap<S32, U8> dataSaverEnabledMap) {
175 sDataSaverEnabledMap = dataSaverEnabledMap;
176 }
177
Motomu Utsumi77b49992023-10-23 17:06:12 +0900178 /**
179 * Set ingressDiscardMap for test.
180 */
181 @VisibleForTesting
182 public static void setIngressDiscardMapForTest(
183 IBpfMap<IngressDiscardKey, IngressDiscardValue> ingressDiscardMap) {
184 sIngressDiscardMap = ingressDiscardMap;
185 }
186
Maciej Żenczykowski6b9d9212024-01-25 15:07:05 -0800187 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000188 private static IBpfMap<S32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000189 try {
190 return new BpfMap<>(
Maciej Żenczykowski06155c82023-11-16 22:41:08 -0800191 CONFIGURATION_MAP_PATH, S32.class, U32.class);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000192 } catch (ErrnoException e) {
193 throw new IllegalStateException("Cannot open netd configuration map", e);
194 }
195 }
196
Maciej Żenczykowski6b9d9212024-01-25 15:07:05 -0800197 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000198 private static IBpfMap<S32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000199 try {
200 return new BpfMap<>(
Maciej Żenczykowski06155c82023-11-16 22:41:08 -0800201 UID_OWNER_MAP_PATH, S32.class, UidOwnerValue.class);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000202 } catch (ErrnoException e) {
203 throw new IllegalStateException("Cannot open uid owner map", e);
204 }
205 }
206
Maciej Żenczykowski6b9d9212024-01-25 15:07:05 -0800207 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000208 private static IBpfMap<S32, U8> getUidPermissionMap() {
Motomu Utsumi65271202022-07-05 08:21:41 +0000209 try {
210 return new BpfMap<>(
Maciej Żenczykowski06155c82023-11-16 22:41:08 -0800211 UID_PERMISSION_MAP_PATH, S32.class, U8.class);
Motomu Utsumi65271202022-07-05 08:21:41 +0000212 } catch (ErrnoException e) {
213 throw new IllegalStateException("Cannot open uid permission map", e);
214 }
215 }
216
Maciej Żenczykowski6b9d9212024-01-25 15:07:05 -0800217 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumib9548862022-09-06 16:30:05 +0900218 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
219 try {
Maciej Żenczykowski06155c82023-11-16 22:41:08 -0800220 return new BpfMap<>(COOKIE_TAG_MAP_PATH,
Motomu Utsumib9548862022-09-06 16:30:05 +0900221 CookieTagMapKey.class, CookieTagMapValue.class);
222 } catch (ErrnoException e) {
223 throw new IllegalStateException("Cannot open cookie tag map", e);
224 }
225 }
226
Maciej Żenczykowski6b9d9212024-01-25 15:07:05 -0800227 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Ken Chen24330172023-10-20 13:02:14 +0800228 private static IBpfMap<S32, U8> getDataSaverEnabledMap() {
229 try {
230 return new BpfMap<>(
Maciej Żenczykowski06155c82023-11-16 22:41:08 -0800231 DATA_SAVER_ENABLED_MAP_PATH, S32.class, U8.class);
Ken Chen24330172023-10-20 13:02:14 +0800232 } catch (ErrnoException e) {
233 throw new IllegalStateException("Cannot open data saver enabled map", e);
234 }
235 }
236
Maciej Żenczykowski6b9d9212024-01-25 15:07:05 -0800237 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi77b49992023-10-23 17:06:12 +0900238 private static IBpfMap<IngressDiscardKey, IngressDiscardValue> getIngressDiscardMap() {
239 try {
Maciej Żenczykowski06155c82023-11-16 22:41:08 -0800240 return new BpfMap<>(INGRESS_DISCARD_MAP_PATH,
Motomu Utsumi77b49992023-10-23 17:06:12 +0900241 IngressDiscardKey.class, IngressDiscardValue.class);
242 } catch (ErrnoException e) {
243 throw new IllegalStateException("Cannot open ingress discard map", e);
244 }
245 }
246
Maciej Żenczykowski6b9d9212024-01-25 15:07:05 -0800247 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000248 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000249 if (sConfigurationMap == null) {
250 sConfigurationMap = getConfigurationMap();
251 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000252 try {
253 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
254 new U32(UID_RULES_DEFAULT_CONFIGURATION));
255 } catch (ErrnoException e) {
256 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
257 }
258 try {
259 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
260 new U32(STATS_SELECT_MAP_A));
261 } catch (ErrnoException e) {
262 throw new IllegalStateException("Failed to initialize current stats configuration", e);
263 }
264
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000265 if (sUidOwnerMap == null) {
266 sUidOwnerMap = getUidOwnerMap();
267 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000268 try {
269 sUidOwnerMap.clear();
270 } catch (ErrnoException e) {
271 throw new IllegalStateException("Failed to initialize uid owner map", e);
272 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000273
274 if (sUidPermissionMap == null) {
275 sUidPermissionMap = getUidPermissionMap();
276 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900277
278 if (sCookieTagMap == null) {
279 sCookieTagMap = getCookieTagMap();
280 }
Ken Chen24330172023-10-20 13:02:14 +0800281
282 if (sDataSaverEnabledMap == null) {
283 sDataSaverEnabledMap = getDataSaverEnabledMap();
284 }
285 try {
286 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(DATA_SAVER_DISABLED));
287 } catch (ErrnoException e) {
288 throw new IllegalStateException("Failed to initialize data saver configuration", e);
289 }
Motomu Utsumi77b49992023-10-23 17:06:12 +0900290
291 if (sIngressDiscardMap == null) {
292 sIngressDiscardMap = getIngressDiscardMap();
293 }
294 try {
295 sIngressDiscardMap.clear();
296 } catch (ErrnoException e) {
297 throw new IllegalStateException("Failed to initialize ingress discard map", e);
298 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000299 }
300
Ken Chenf5f51332022-01-28 10:08:16 +0800301 /**
302 * Initializes the class if it is not already initialized. This method will open maps but not
303 * cause any other effects. This method may be called multiple times on any thread.
304 */
Maciej Żenczykowski6b9d9212024-01-25 15:07:05 -0800305 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000306 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800307 if (sInitialized) return;
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000308 initBpfMaps();
Ken Chenf5f51332022-01-28 10:08:16 +0800309 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800310 }
311
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000312 /**
313 * Dependencies of BpfNetMaps, for injection in tests.
314 */
315 @VisibleForTesting
316 public static class Dependencies {
317 /**
318 * Get interface index.
319 */
320 public int getIfIndex(final String ifName) {
321 return Os.if_nametoindex(ifName);
322 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000323
324 /**
Motomu Utsumi77b49992023-10-23 17:06:12 +0900325 * Get interface name
326 */
327 public String getIfName(final int ifIndex) {
328 return Os.if_indextoname(ifIndex);
329 }
330
331 /**
Maciej Żenczykowski7b8f4752023-11-07 17:04:15 -0800332 * Synchronously call in to kernel to synchronize_rcu()
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000333 */
Maciej Żenczykowski7b8f4752023-11-07 17:04:15 -0800334 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000335 public int synchronizeKernelRCU() {
Maciej Żenczykowski7b8f4752023-11-07 17:04:15 -0800336 try {
Maciej Żenczykowskic350db72023-11-08 23:40:50 -0800337 BpfMap.synchronizeKernelRCU();
Maciej Żenczykowski7b8f4752023-11-07 17:04:15 -0800338 } catch (ErrnoException e) {
Maciej Żenczykowski7b8f4752023-11-07 17:04:15 -0800339 return -e.errno;
340 }
341 return 0;
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000342 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900343
344 /**
345 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
346 */
347 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
348 final int uidPermissionMapSize) {
349 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
350 uidOwnerMapSize, uidPermissionMapSize);
351 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000352 }
353
markchien49e944c2022-03-01 15:22:20 +0800354 /** Constructor used after T that doesn't need to use netd anymore. */
Junyu Lai626045a2023-08-28 18:49:44 +0800355 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000356 public BpfNetMaps(final Context context) {
357 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800358
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000359 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800360 }
361
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000362 public BpfNetMaps(final Context context, final INetd netd) {
363 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000364 }
365
366 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000367 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000368 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000369 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000370 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800371 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000372 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800373 }
374
Ken Chenf5f51332022-01-28 10:08:16 +0800375 private void maybeThrow(final int err, final String msg) {
376 if (err != 0) {
377 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
378 }
379 }
380
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000381 private void throwIfPreT(final String msg) {
382 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000383 throw new UnsupportedOperationException(msg);
384 }
385 }
386
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000387 private void removeRule(final int uid, final long match, final String caller) {
388 try {
389 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000390 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000391
392 if (oldMatch == null) {
393 throw new ServiceSpecificException(ENOENT,
394 "sUidOwnerMap does not have entry for uid: " + uid);
395 }
396
397 final UidOwnerValue newMatch = new UidOwnerValue(
398 (match == IIF_MATCH) ? 0 : oldMatch.iif,
399 oldMatch.rule & ~match
400 );
401
402 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000403 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000404 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000405 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000406 }
407 }
408 } catch (ErrnoException e) {
409 throw new ServiceSpecificException(e.errno,
410 caller + " failed to remove rule: " + Os.strerror(e.errno));
411 }
412 }
413
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000414 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000415 if (match != IIF_MATCH && iif != 0) {
416 throw new ServiceSpecificException(EINVAL,
417 "Non-interface match must have zero interface index");
418 }
419
420 try {
421 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000422 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000423
424 final UidOwnerValue newMatch;
425 if (oldMatch != null) {
426 newMatch = new UidOwnerValue(
427 (match == IIF_MATCH) ? iif : oldMatch.iif,
428 oldMatch.rule | match
429 );
430 } else {
431 newMatch = new UidOwnerValue(
432 iif,
433 match
434 );
435 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000436 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000437 }
438 } catch (ErrnoException e) {
439 throw new ServiceSpecificException(e.errno,
440 caller + " failed to add rule: " + Os.strerror(e.errno));
441 }
442 }
443
444 private void addRule(final int uid, final long match, final String caller) {
445 addRule(uid, match, 0 /* iif */, caller);
446 }
447
Ken Chenf5f51332022-01-28 10:08:16 +0800448 /**
449 * Add naughty app bandwidth rule for specific app
450 *
451 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800452 * @throws ServiceSpecificException in case of failure, with an error code indicating the
453 * cause of the failure.
454 */
Junyu Lai626045a2023-08-28 18:49:44 +0800455 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900456 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000457 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000458
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900459 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800460 }
461
Ken Chenf5f51332022-01-28 10:08:16 +0800462 /**
463 * Remove naughty app bandwidth rule for specific app
464 *
465 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800466 * @throws ServiceSpecificException in case of failure, with an error code indicating the
467 * cause of the failure.
468 */
Junyu Lai626045a2023-08-28 18:49:44 +0800469 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900470 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000471 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000472
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900473 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800474 }
475
Ken Chenf5f51332022-01-28 10:08:16 +0800476 /**
477 * Add nice app bandwidth rule for specific app
478 *
479 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800480 * @throws ServiceSpecificException in case of failure, with an error code indicating the
481 * cause of the failure.
482 */
Junyu Lai626045a2023-08-28 18:49:44 +0800483 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900484 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000485 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000486
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900487 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800488 }
489
Ken Chenf5f51332022-01-28 10:08:16 +0800490 /**
491 * Remove nice app bandwidth rule for specific app
492 *
493 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800494 * @throws ServiceSpecificException in case of failure, with an error code indicating the
495 * cause of the failure.
496 */
Junyu Lai626045a2023-08-28 18:49:44 +0800497 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900498 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000499 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000500
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900501 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800502 }
503
Ken Chenf5f51332022-01-28 10:08:16 +0800504 /**
505 * Set target firewall child chain
506 *
507 * @param childChain target chain to enable
508 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000509 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800510 * @throws ServiceSpecificException in case of failure, with an error code indicating the
511 * cause of the failure.
512 */
Junyu Lai626045a2023-08-28 18:49:44 +0800513 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900514 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000515 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000516
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900517 final long match = getMatchByFirewallChain(childChain);
518 try {
519 synchronized (sUidRulesConfigBpfMapLock) {
520 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
521 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
522 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000523 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900524 } catch (ErrnoException e) {
525 throw new ServiceSpecificException(e.errno,
526 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000527 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800528 }
529
530 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000531 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000532 *
533 * @param childChain target chain
534 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
535 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000536 * @throws ServiceSpecificException in case of failure, with an error code indicating the
537 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800538 *
539 * @deprecated Use {@link BpfNetMapsReader#isChainEnabled} instead.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000540 */
Junyu Lai626045a2023-08-28 18:49:44 +0800541 // TODO: Migrate the callers to use {@link BpfNetMapsReader#isChainEnabled} instead.
542 @Deprecated
543 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000544 public boolean isChainEnabled(final int childChain) {
Junyu Lai626045a2023-08-28 18:49:44 +0800545 return BpfNetMapsReader.isChainEnabled(sConfigurationMap, childChain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000546 }
547
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900548 private Set<Integer> asSet(final int[] uids) {
549 final Set<Integer> uidSet = new ArraySet<>();
Motomu Utsumi77b49992023-10-23 17:06:12 +0900550 for (final int uid : uids) {
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900551 uidSet.add(uid);
552 }
553 return uidSet;
554 }
555
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000556 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800557 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000558 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800559 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000560 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800561 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000562 * @throws UnsupportedOperationException if called on pre-T devices.
563 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800564 */
Junyu Lai626045a2023-08-28 18:49:44 +0800565 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000566 public void replaceUidChain(final int chain, final int[] uids) {
567 throwIfPreT("replaceUidChain is not available on pre-T devices");
568
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900569 final long match;
570 try {
571 match = getMatchByFirewallChain(chain);
572 } catch (ServiceSpecificException e) {
573 // Throws IllegalArgumentException to keep the behavior of
574 // ConnectivityManager#replaceFirewallChain API
575 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
576 }
577 final Set<Integer> uidSet = asSet(uids);
578 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
579 try {
580 synchronized (sUidOwnerMap) {
581 sUidOwnerMap.forEach((uid, config) -> {
582 // config could be null if there is a concurrent entry deletion.
583 // http://b/220084230. But sUidOwnerMap update must be done while holding a
584 // lock, so this should not happen.
585 if (config == null) {
586 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
587 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
588 uidSetToRemoveRule.add((int) uid.val);
589 }
590 });
Motomu Utsumic7c16852022-08-03 06:51:41 +0000591
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900592 for (final int uid : uidSetToRemoveRule) {
593 removeRule(uid, match, "replaceUidChain");
Motomu Utsumic7c16852022-08-03 06:51:41 +0000594 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900595 for (final int uid : uids) {
596 addRule(uid, match, "replaceUidChain");
597 }
Motomu Utsumic7c16852022-08-03 06:51:41 +0000598 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900599 } catch (ErrnoException | ServiceSpecificException e) {
600 Log.e(TAG, "replaceUidChain failed: " + e);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800601 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800602 }
603
Ken Chenf5f51332022-01-28 10:08:16 +0800604 /**
605 * Set firewall rule for uid
606 *
607 * @param childChain target chain
608 * @param uid uid to allow/deny
609 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800610 * @throws ServiceSpecificException in case of failure, with an error code indicating the
611 * cause of the failure.
612 */
Junyu Lai626045a2023-08-28 18:49:44 +0800613 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900614 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000615 throwIfPreT("setUidRule is not available on pre-T devices");
616
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900617 final long match = getMatchByFirewallChain(childChain);
618 final boolean isAllowList = isFirewallAllowList(childChain);
619 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
620 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000621
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900622 if (add) {
623 addRule(uid, match, "setUidRule");
Motomu Utsumi40230be2022-07-05 03:27:35 +0000624 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900625 removeRule(uid, match, "setUidRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000626 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800627 }
628
629 /**
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900630 * Get firewall rule of specified firewall chain on specified uid.
631 *
632 * @param childChain target chain
633 * @param uid target uid
634 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
635 * @throws UnsupportedOperationException if called on pre-T devices.
636 * @throws ServiceSpecificException in case of failure, with an error code indicating the
637 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800638 *
639 * @deprecated use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900640 */
Junyu Lai626045a2023-08-28 18:49:44 +0800641 // TODO: Migrate the callers to use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900642 public int getUidRule(final int childChain, final int uid) {
Junyu Lai626045a2023-08-28 18:49:44 +0800643 return BpfNetMapsReader.getUidRule(sUidOwnerMap, childChain, uid);
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900644 }
645
Motomu Utsumid44a33a2023-03-28 18:08:12 +0900646 private Set<Integer> getUidsMatchEnabled(final int childChain) throws ErrnoException {
647 final long match = getMatchByFirewallChain(childChain);
648 Set<Integer> uids = new ArraySet<>();
649 synchronized (sUidOwnerMap) {
650 sUidOwnerMap.forEach((uid, val) -> {
651 if (val == null) {
652 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
653 } else {
654 if ((val.rule & match) != 0) {
655 uids.add(uid.val);
656 }
657 }
658 });
659 }
660 return uids;
661 }
662
663 /**
664 * Get uids that has FIREWALL_RULE_ALLOW on allowlist chain.
665 * Allowlist means the firewall denies all by default, uids must be explicitly allowed.
666 *
667 * Note that uids that has FIREWALL_RULE_DENY on allowlist chain can not be computed from the
668 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_ALLOW rule in bpf map
669 * are determined to have FIREWALL_RULE_DENY.
670 *
671 * @param childChain target chain
672 * @return Set of uids
673 */
674 public Set<Integer> getUidsWithAllowRuleOnAllowListChain(final int childChain)
675 throws ErrnoException {
676 if (!isFirewallAllowList(childChain)) {
677 throw new IllegalArgumentException("getUidsWithAllowRuleOnAllowListChain is called with"
678 + " denylist chain:" + childChain);
679 }
680 // Corresponding match is enabled for uids that has FIREWALL_RULE_ALLOW on allowlist chain.
681 return getUidsMatchEnabled(childChain);
682 }
683
684 /**
685 * Get uids that has FIREWALL_RULE_DENY on denylist chain.
686 * Denylist means the firewall allows all by default, uids must be explicitly denyed
687 *
688 * Note that uids that has FIREWALL_RULE_ALLOW on denylist chain can not be computed from the
689 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_DENY rule in bpf map
690 * are determined to have the FIREWALL_RULE_ALLOW.
691 *
692 * @param childChain target chain
693 * @return Set of uids
694 */
695 public Set<Integer> getUidsWithDenyRuleOnDenyListChain(final int childChain)
696 throws ErrnoException {
697 if (isFirewallAllowList(childChain)) {
698 throw new IllegalArgumentException("getUidsWithDenyRuleOnDenyListChain is called with"
699 + " allowlist chain:" + childChain);
700 }
701 // Corresponding match is enabled for uids that has FIREWALL_RULE_DENY on denylist chain.
702 return getUidsMatchEnabled(childChain);
703 }
704
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900705 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800706 * Add ingress interface filtering rules to a list of UIDs
707 *
708 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
709 * allowed interface and loopback to be sent to the list of UIDs.
710 *
711 * Calling this method on one or more UIDs with an existing filtering rule but a different
712 * interface name will result in the filtering rule being updated to allow the new interface
713 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
714 *
715 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800716 * be received.
717 * @param uids an array of UIDs which the filtering rules will be set
718 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800719 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800720 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800721 */
Ken Chenf5f51332022-01-28 10:08:16 +0800722 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000723 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800724 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800725 return;
726 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000727
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900728 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
729 // ifIndex is set to 0.
730 final int ifIndex;
731 if (ifName == null) {
732 ifIndex = 0;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000733 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900734 ifIndex = mDeps.getIfIndex(ifName);
735 if (ifIndex == 0) {
736 throw new ServiceSpecificException(ENODEV,
737 "Failed to get index of interface " + ifName);
738 }
739 }
740 for (final int uid : uids) {
741 try {
742 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
743 } catch (ServiceSpecificException e) {
744 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
745 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000746 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800747 }
748
749 /**
750 * Remove ingress interface filtering rules from a list of UIDs
751 *
752 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
753 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
754 *
755 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800756 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800757 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800758 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800759 */
Ken Chenf5f51332022-01-28 10:08:16 +0800760 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000761 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800762 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800763 return;
764 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000765
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900766 for (final int uid : uids) {
767 try {
768 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
769 } catch (ServiceSpecificException e) {
770 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000771 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000772 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800773 }
774
Ken Chenf5f51332022-01-28 10:08:16 +0800775 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000776 * Update lockdown rule for uid
777 *
778 * @param uid target uid to add/remove the rule
779 * @param add {@code true} to add the rule, {@code false} to remove the rule.
780 * @throws ServiceSpecificException in case of failure, with an error code indicating the
781 * cause of the failure.
782 */
Junyu Lai626045a2023-08-28 18:49:44 +0800783 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000784 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000785 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000786
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900787 if (add) {
788 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi697b2992022-06-30 02:25:29 +0000789 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900790 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000791 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000792 }
793
794 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800795 * Request netd to change the current active network stats map.
796 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000797 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800798 * @throws ServiceSpecificException in case of failure, with an error code indicating the
799 * cause of the failure.
800 */
Junyu Lai626045a2023-08-28 18:49:44 +0800801 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien49e944c2022-03-01 15:22:20 +0800802 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000803 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
804
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900805 try {
806 synchronized (sCurrentStatsMapConfigLock) {
807 final long config = sConfigurationMap.getValue(
808 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
809 final long newConfig = (config == STATS_SELECT_MAP_A)
810 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
811 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
812 new U32(newConfig));
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000813 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900814 } catch (ErrnoException e) {
815 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000816 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900817
818 // After changing the config, it's needed to make sure all the current running eBPF
819 // programs are finished and all the CPUs are aware of this config change before the old
820 // map is modified. So special hack is needed here to wait for the kernel to do a
821 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
822 // be available to all cores and the next eBPF programs triggered inside the kernel will
823 // use the new map configuration. So once this function returns it is safe to modify the
824 // old stats map without concerning about race between the kernel and userspace.
825 final int err = mDeps.synchronizeKernelRCU();
826 maybeThrow(err, "synchronizeKernelRCU failed");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800827 }
828
Ken Chenf5f51332022-01-28 10:08:16 +0800829 /**
830 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
831 * specified. Or remove all permissions from the uids.
832 *
833 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
834 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
835 * revoke all permissions for the uids.
836 * @param uids uid of users to grant permission
837 * @throws RemoteException when netd has crashed.
838 */
839 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000840 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800841 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800842 return;
843 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000844
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900845 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
846 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000847 for (final int uid : uids) {
848 try {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900849 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000850 } catch (ErrnoException e) {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900851 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
Motomu Utsumi65271202022-07-05 08:21:41 +0000852 }
853 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900854 return;
855 }
856
857 for (final int uid : uids) {
858 try {
859 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
860 } catch (ErrnoException e) {
861 Log.e(TAG, "Failed to set permission "
862 + permissions + " to uid " + uid + ": " + e);
863 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000864 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800865 }
866
Ken Chen24330172023-10-20 13:02:14 +0800867 /**
868 * Set Data Saver enabled or disabled
869 *
870 * @param enable whether Data Saver is enabled or disabled.
871 * @throws UnsupportedOperationException if called on pre-T devices.
872 * @throws ServiceSpecificException in case of failure, with an error code indicating the
873 * cause of the failure.
874 */
875 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
876 public void setDataSaverEnabled(boolean enable) {
877 throwIfPreT("setDataSaverEnabled is not available on pre-T devices");
878
879 try {
880 final short config = enable ? DATA_SAVER_ENABLED : DATA_SAVER_DISABLED;
881 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(config));
882 } catch (ErrnoException e) {
883 throw new ServiceSpecificException(e.errno, "Unable to set data saver: "
884 + Os.strerror(e.errno));
885 }
886 }
887
Motomu Utsumi77b49992023-10-23 17:06:12 +0900888 /**
889 * Set ingress discard rule
890 *
891 * @param address target address to set the ingress discard rule
892 * @param iface allowed interface
893 */
894 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
895 public void setIngressDiscardRule(final InetAddress address, final String iface) {
896 throwIfPreT("setIngressDiscardRule is not available on pre-T devices");
897 final int ifIndex = mDeps.getIfIndex(iface);
898 if (ifIndex == 0) {
899 Log.e(TAG, "Failed to get if index, skip setting ingress discard rule for " + address
900 + "(" + iface + ")");
901 return;
902 }
903 try {
904 sIngressDiscardMap.updateEntry(new IngressDiscardKey(address),
905 new IngressDiscardValue(ifIndex, ifIndex));
906 } catch (ErrnoException e) {
907 Log.e(TAG, "Failed to set ingress discard rule for " + address + "("
908 + iface + "), " + e);
909 }
910 }
911
912 /**
913 * Remove ingress discard rule
914 *
915 * @param address target address to remove the ingress discard rule
916 */
917 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
918 public void removeIngressDiscardRule(final InetAddress address) {
919 throwIfPreT("removeIngressDiscardRule is not available on pre-T devices");
920 try {
921 sIngressDiscardMap.deleteEntry(new IngressDiscardKey(address));
922 } catch (ErrnoException e) {
923 Log.e(TAG, "Failed to remove ingress discard rule for " + address + ", " + e);
924 }
925 }
926
Motomu Utsumi166f9662022-09-01 10:35:29 +0900927 /** Register callback for statsd to pull atom. */
Junyu Lai626045a2023-08-28 18:49:44 +0800928 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi166f9662022-09-01 10:35:29 +0900929 public void setPullAtomCallback(final Context context) {
930 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
931
932 final StatsManager statsManager = context.getSystemService(StatsManager.class);
933 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
934 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
935 }
936
937 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
938 throws ErrnoException {
939 // forEach could restart iteration from the beginning if there is a concurrent entry
940 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
941 // So using Set to count the number of entry in the map.
942 Set<K> keySet = new ArraySet<>();
943 map.forEach((k, v) -> keySet.add(k));
944 return keySet.size();
945 }
946
947 /** Callback for StatsManager#setPullAtomCallback */
948 @VisibleForTesting
949 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
950 if (atomTag != NETWORK_BPF_MAP_INFO) {
951 Log.e(TAG, "Unexpected atom tag: " + atomTag);
952 return StatsManager.PULL_SKIP;
953 }
954
955 try {
956 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
957 getMapSize(sUidPermissionMap)));
958 } catch (ErrnoException e) {
959 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
960 return StatsManager.PULL_SKIP;
961 }
962 return StatsManager.PULL_SUCCESS;
963 }
964
Motomu Utsumi310850f2022-09-02 12:48:20 +0900965 private String permissionToString(int permissionMask) {
966 if (permissionMask == PERMISSION_NONE) {
967 return "PERMISSION_NONE";
968 }
969 if (permissionMask == PERMISSION_UNINSTALLED) {
970 // PERMISSION_UNINSTALLED should never appear in the map
971 return "PERMISSION_UNINSTALLED error!";
972 }
973
974 final StringJoiner sj = new StringJoiner(" ");
975 for (Pair<Integer, String> permission: PERMISSION_LIST) {
976 final int permissionFlag = permission.first;
977 final String permissionName = permission.second;
978 if ((permissionMask & permissionFlag) != 0) {
979 sj.add(permissionName);
980 permissionMask &= ~permissionFlag;
981 }
982 }
983 if (permissionMask != 0) {
984 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
985 }
986 return sj.toString();
987 }
988
Motomu Utsumi372c9b42022-09-02 19:02:56 +0900989 private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
990 try {
991 final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
992 pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
993 } catch (ErrnoException e) {
994 pw.println("Failed to read ownerMatch configuration: " + e);
995 }
996 }
997
Motomu Utsumic675d6f2022-09-02 18:15:25 +0900998 private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
999 try {
1000 final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
1001 final String currentStatsMap =
1002 (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
1003 pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
1004 } catch (ErrnoException e) {
1005 pw.println("Falied to read current statsMap configuration: " + e);
1006 }
1007 }
1008
Ken Chen24330172023-10-20 13:02:14 +08001009 private void dumpDataSaverConfig(final IndentingPrintWriter pw) {
1010 try {
1011 final short config = sDataSaverEnabledMap.getValue(DATA_SAVER_ENABLED_KEY).val;
1012 // Any non-zero value converted from short to boolean is true by convention.
1013 pw.println("sDataSaverEnabledMap: " + (config != DATA_SAVER_DISABLED));
1014 } catch (ErrnoException e) {
1015 pw.println("Failed to read data saver configuration: " + e);
1016 }
1017 }
Ken Chene6d511f2022-01-25 11:10:42 +08001018 /**
1019 * Dump BPF maps
1020 *
Motomu Utsumi310850f2022-09-02 12:48:20 +09001021 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +08001022 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +09001023 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +08001024 * @throws IOException when file descriptor is invalid.
1025 * @throws ServiceSpecificException when the method is called on an unsupported device.
1026 */
Junyu Lai626045a2023-08-28 18:49:44 +08001027 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi310850f2022-09-02 12:48:20 +09001028 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +08001029 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00001030 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +08001031 throw new ServiceSpecificException(
1032 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
1033 + " devices, use dumpsys netd trafficcontroller instead.");
1034 }
Maciej Żenczykowskid70a3302023-09-06 16:45:25 +00001035
1036 pw.println("TrafficController"); // required by CTS testDumpBpfNetMaps
Motomu Utsumi310850f2022-09-02 12:48:20 +09001037
Motomu Utsumi316d0572022-09-15 13:24:48 +09001038 pw.println();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001039 if (verbose) {
Motomu Utsumief546a92022-10-05 16:42:29 +09001040 pw.println();
1041 pw.println("BPF map content:");
1042 pw.increaseIndent();
1043
Motomu Utsumi372c9b42022-09-02 19:02:56 +09001044 dumpOwnerMatchConfig(pw);
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001045 dumpCurrentStatsMapConfig(pw);
1046 pw.println();
1047
Motomu Utsumief546a92022-10-05 16:42:29 +09001048 // TODO: Remove CookieTagMap content dump
1049 // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
1050 // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
1051 // need to be updated before remove the dump from BpfNetMaps.
1052 BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
1053 (key, value) -> "cookie=" + key.socketCookie
1054 + " tag=0x" + Long.toHexString(value.tag)
1055 + " uid=" + value.uid);
Motomu Utsumi956d86c2022-09-02 17:01:25 +09001056 BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
1057 (uid, match) -> {
1058 if ((match.rule & IIF_MATCH) != 0) {
1059 // TODO: convert interface index to interface name by IfaceIndexNameMap
1060 return uid.val + " " + matchToString(match.rule) + " " + match.iif;
1061 } else {
1062 return uid.val + " " + matchToString(match.rule);
1063 }
1064 });
Motomu Utsumi310850f2022-09-02 12:48:20 +09001065 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
1066 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
Motomu Utsumi77b49992023-10-23 17:06:12 +09001067 BpfDump.dumpMap(sIngressDiscardMap, pw, "sIngressDiscardMap",
1068 (key, value) -> "[" + key.dstAddr + "]: "
1069 + value.iif1 + "(" + mDeps.getIfName(value.iif1) + "), "
1070 + value.iif2 + "(" + mDeps.getIfName(value.iif2) + ")");
Ken Chen24330172023-10-20 13:02:14 +08001071 dumpDataSaverConfig(pw);
Motomu Utsumief546a92022-10-05 16:42:29 +09001072 pw.decreaseIndent();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001073 }
Ken Chene6d511f2022-01-25 11:10:42 +08001074 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001075}