blob: b7e928d016db42d50fb2b5bebb68559693896d3a [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 Utsumi7628ea32023-08-14 11:09:02 +0900109 private static final String BPF_NET_MAPS_FORCE_DISABLE_JAVA_BPF_MAP =
110 "bpf_net_maps_force_disable_java_bpf_map";
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000111
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000112 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
113 // This entry is not accessed by others.
114 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
115 private static final Object sUidRulesConfigBpfMapLock = new Object();
116
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000117 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
118 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
119 // BpfNetMaps is an only writer of this entry.
120 private static final Object sCurrentStatsMapConfigLock = new Object();
121
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000122 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
123 private static final long STATS_SELECT_MAP_A = 0;
124 private static final long STATS_SELECT_MAP_B = 1;
125
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000126 private static IBpfMap<S32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000127 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000128 private static IBpfMap<S32, UidOwnerValue> sUidOwnerMap = null;
129 private static IBpfMap<S32, U8> sUidPermissionMap = null;
Motomu Utsumib9548862022-09-06 16:30:05 +0900130 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> sCookieTagMap = null;
Ken Chen24330172023-10-20 13:02:14 +0800131 // TODO: Add BOOL class and replace U8?
132 private static IBpfMap<S32, U8> sDataSaverEnabledMap = null;
Motomu Utsumi77b49992023-10-23 17:06:12 +0900133 private static IBpfMap<IngressDiscardKey, IngressDiscardValue> sIngressDiscardMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000134
Motomu Utsumi310850f2022-09-02 12:48:20 +0900135 private static final List<Pair<Integer, String>> PERMISSION_LIST = Arrays.asList(
136 Pair.create(PERMISSION_INTERNET, "PERMISSION_INTERNET"),
137 Pair.create(PERMISSION_UPDATE_DEVICE_STATS, "PERMISSION_UPDATE_DEVICE_STATS")
138 );
139
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000140 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000141 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000142 */
143 @VisibleForTesting
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000144 public static void setConfigurationMapForTest(IBpfMap<S32, U32> configurationMap) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000145 sConfigurationMap = configurationMap;
146 }
147
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000148 /**
149 * Set uidOwnerMap for test.
150 */
151 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000152 public static void setUidOwnerMapForTest(IBpfMap<S32, UidOwnerValue> uidOwnerMap) {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000153 sUidOwnerMap = uidOwnerMap;
154 }
155
Motomu Utsumi65271202022-07-05 08:21:41 +0000156 /**
157 * Set uidPermissionMap for test.
158 */
159 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000160 public static void setUidPermissionMapForTest(IBpfMap<S32, U8> uidPermissionMap) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000161 sUidPermissionMap = uidPermissionMap;
162 }
163
Motomu Utsumib9548862022-09-06 16:30:05 +0900164 /**
165 * Set cookieTagMap for test.
166 */
167 @VisibleForTesting
168 public static void setCookieTagMapForTest(
169 IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap) {
170 sCookieTagMap = cookieTagMap;
171 }
172
Ken Chen24330172023-10-20 13:02:14 +0800173 /**
174 * Set dataSaverEnabledMap for test.
175 */
176 @VisibleForTesting
177 public static void setDataSaverEnabledMapForTest(IBpfMap<S32, U8> dataSaverEnabledMap) {
178 sDataSaverEnabledMap = dataSaverEnabledMap;
179 }
180
Motomu Utsumi77b49992023-10-23 17:06:12 +0900181 /**
182 * Set ingressDiscardMap for test.
183 */
184 @VisibleForTesting
185 public static void setIngressDiscardMapForTest(
186 IBpfMap<IngressDiscardKey, IngressDiscardValue> ingressDiscardMap) {
187 sIngressDiscardMap = ingressDiscardMap;
188 }
189
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000190 private static IBpfMap<S32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000191 try {
192 return new BpfMap<>(
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000193 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U32.class);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000194 } catch (ErrnoException e) {
195 throw new IllegalStateException("Cannot open netd configuration map", e);
196 }
197 }
198
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000199 private static IBpfMap<S32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000200 try {
201 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000202 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, UidOwnerValue.class);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000203 } catch (ErrnoException e) {
204 throw new IllegalStateException("Cannot open uid owner map", e);
205 }
206 }
207
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 Żenczykowski785793f2022-09-17 02:35:20 +0000211 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, 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
Motomu Utsumib9548862022-09-06 16:30:05 +0900217 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
218 try {
219 return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,
220 CookieTagMapKey.class, CookieTagMapValue.class);
221 } catch (ErrnoException e) {
222 throw new IllegalStateException("Cannot open cookie tag map", e);
223 }
224 }
225
Ken Chen24330172023-10-20 13:02:14 +0800226 private static IBpfMap<S32, U8> getDataSaverEnabledMap() {
227 try {
228 return new BpfMap<>(
229 DATA_SAVER_ENABLED_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
230 } catch (ErrnoException e) {
231 throw new IllegalStateException("Cannot open data saver enabled map", e);
232 }
233 }
234
Motomu Utsumi77b49992023-10-23 17:06:12 +0900235 private static IBpfMap<IngressDiscardKey, IngressDiscardValue> getIngressDiscardMap() {
236 try {
237 return new BpfMap<>(INGRESS_DISCARD_MAP_PATH, BpfMap.BPF_F_RDWR,
238 IngressDiscardKey.class, IngressDiscardValue.class);
239 } catch (ErrnoException e) {
240 throw new IllegalStateException("Cannot open ingress discard map", e);
241 }
242 }
243
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000244 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000245 if (sConfigurationMap == null) {
246 sConfigurationMap = getConfigurationMap();
247 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000248 try {
249 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
250 new U32(UID_RULES_DEFAULT_CONFIGURATION));
251 } catch (ErrnoException e) {
252 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
253 }
254 try {
255 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
256 new U32(STATS_SELECT_MAP_A));
257 } catch (ErrnoException e) {
258 throw new IllegalStateException("Failed to initialize current stats configuration", e);
259 }
260
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000261 if (sUidOwnerMap == null) {
262 sUidOwnerMap = getUidOwnerMap();
263 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000264 try {
265 sUidOwnerMap.clear();
266 } catch (ErrnoException e) {
267 throw new IllegalStateException("Failed to initialize uid owner map", e);
268 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000269
270 if (sUidPermissionMap == null) {
271 sUidPermissionMap = getUidPermissionMap();
272 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900273
274 if (sCookieTagMap == null) {
275 sCookieTagMap = getCookieTagMap();
276 }
Ken Chen24330172023-10-20 13:02:14 +0800277
278 if (sDataSaverEnabledMap == null) {
279 sDataSaverEnabledMap = getDataSaverEnabledMap();
280 }
281 try {
282 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(DATA_SAVER_DISABLED));
283 } catch (ErrnoException e) {
284 throw new IllegalStateException("Failed to initialize data saver configuration", e);
285 }
Motomu Utsumi77b49992023-10-23 17:06:12 +0900286
287 if (sIngressDiscardMap == null) {
288 sIngressDiscardMap = getIngressDiscardMap();
289 }
290 try {
291 sIngressDiscardMap.clear();
292 } catch (ErrnoException e) {
293 throw new IllegalStateException("Failed to initialize ingress discard map", e);
294 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000295 }
296
Ken Chenf5f51332022-01-28 10:08:16 +0800297 /**
298 * Initializes the class if it is not already initialized. This method will open maps but not
299 * cause any other effects. This method may be called multiple times on any thread.
300 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000301 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800302 if (sInitialized) return;
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000303 initBpfMaps();
Ken Chenf5f51332022-01-28 10:08:16 +0800304 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800305 }
306
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000307 /**
308 * Dependencies of BpfNetMaps, for injection in tests.
309 */
310 @VisibleForTesting
311 public static class Dependencies {
312 /**
313 * Get interface index.
314 */
315 public int getIfIndex(final String ifName) {
316 return Os.if_nametoindex(ifName);
317 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000318
319 /**
Motomu Utsumi77b49992023-10-23 17:06:12 +0900320 * Get interface name
321 */
322 public String getIfName(final int ifIndex) {
323 return Os.if_indextoname(ifIndex);
324 }
325
326 /**
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000327 * Call synchronize_rcu()
328 */
329 public int synchronizeKernelRCU() {
330 return native_synchronizeKernelRCU();
331 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900332
333 /**
334 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
335 */
336 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
337 final int uidPermissionMapSize) {
338 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
339 uidOwnerMapSize, uidPermissionMapSize);
340 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000341 }
342
markchien49e944c2022-03-01 15:22:20 +0800343 /** Constructor used after T that doesn't need to use netd anymore. */
Junyu Lai626045a2023-08-28 18:49:44 +0800344 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000345 public BpfNetMaps(final Context context) {
346 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800347
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000348 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800349 }
350
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000351 public BpfNetMaps(final Context context, final INetd netd) {
352 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000353 }
354
355 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000356 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000357 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000358 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000359 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800360 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000361 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800362 }
363
Ken Chenf5f51332022-01-28 10:08:16 +0800364 private void maybeThrow(final int err, final String msg) {
365 if (err != 0) {
366 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
367 }
368 }
369
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000370 private void throwIfPreT(final String msg) {
371 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000372 throw new UnsupportedOperationException(msg);
373 }
374 }
375
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000376 private void removeRule(final int uid, final long match, final String caller) {
377 try {
378 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000379 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000380
381 if (oldMatch == null) {
382 throw new ServiceSpecificException(ENOENT,
383 "sUidOwnerMap does not have entry for uid: " + uid);
384 }
385
386 final UidOwnerValue newMatch = new UidOwnerValue(
387 (match == IIF_MATCH) ? 0 : oldMatch.iif,
388 oldMatch.rule & ~match
389 );
390
391 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000392 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000393 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000394 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000395 }
396 }
397 } catch (ErrnoException e) {
398 throw new ServiceSpecificException(e.errno,
399 caller + " failed to remove rule: " + Os.strerror(e.errno));
400 }
401 }
402
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000403 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000404 if (match != IIF_MATCH && iif != 0) {
405 throw new ServiceSpecificException(EINVAL,
406 "Non-interface match must have zero interface index");
407 }
408
409 try {
410 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000411 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000412
413 final UidOwnerValue newMatch;
414 if (oldMatch != null) {
415 newMatch = new UidOwnerValue(
416 (match == IIF_MATCH) ? iif : oldMatch.iif,
417 oldMatch.rule | match
418 );
419 } else {
420 newMatch = new UidOwnerValue(
421 iif,
422 match
423 );
424 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000425 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000426 }
427 } catch (ErrnoException e) {
428 throw new ServiceSpecificException(e.errno,
429 caller + " failed to add rule: " + Os.strerror(e.errno));
430 }
431 }
432
433 private void addRule(final int uid, final long match, final String caller) {
434 addRule(uid, match, 0 /* iif */, caller);
435 }
436
Ken Chenf5f51332022-01-28 10:08:16 +0800437 /**
438 * Add naughty app bandwidth rule for specific app
439 *
440 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800441 * @throws ServiceSpecificException in case of failure, with an error code indicating the
442 * cause of the failure.
443 */
Junyu Lai626045a2023-08-28 18:49:44 +0800444 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900445 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000446 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000447
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900448 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800449 }
450
Ken Chenf5f51332022-01-28 10:08:16 +0800451 /**
452 * Remove naughty app bandwidth rule for specific app
453 *
454 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800455 * @throws ServiceSpecificException in case of failure, with an error code indicating the
456 * cause of the failure.
457 */
Junyu Lai626045a2023-08-28 18:49:44 +0800458 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900459 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000460 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000461
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900462 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800463 }
464
Ken Chenf5f51332022-01-28 10:08:16 +0800465 /**
466 * Add nice app bandwidth rule for specific app
467 *
468 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800469 * @throws ServiceSpecificException in case of failure, with an error code indicating the
470 * cause of the failure.
471 */
Junyu Lai626045a2023-08-28 18:49:44 +0800472 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900473 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000474 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000475
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900476 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800477 }
478
Ken Chenf5f51332022-01-28 10:08:16 +0800479 /**
480 * Remove nice app bandwidth rule for specific app
481 *
482 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800483 * @throws ServiceSpecificException in case of failure, with an error code indicating the
484 * cause of the failure.
485 */
Junyu Lai626045a2023-08-28 18:49:44 +0800486 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900487 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000488 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000489
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900490 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800491 }
492
Ken Chenf5f51332022-01-28 10:08:16 +0800493 /**
494 * Set target firewall child chain
495 *
496 * @param childChain target chain to enable
497 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000498 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800499 * @throws ServiceSpecificException in case of failure, with an error code indicating the
500 * cause of the failure.
501 */
Junyu Lai626045a2023-08-28 18:49:44 +0800502 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900503 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000504 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000505
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900506 final long match = getMatchByFirewallChain(childChain);
507 try {
508 synchronized (sUidRulesConfigBpfMapLock) {
509 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
510 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
511 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000512 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900513 } catch (ErrnoException e) {
514 throw new ServiceSpecificException(e.errno,
515 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000516 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800517 }
518
519 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000520 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000521 *
522 * @param childChain target chain
523 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
524 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000525 * @throws ServiceSpecificException in case of failure, with an error code indicating the
526 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800527 *
528 * @deprecated Use {@link BpfNetMapsReader#isChainEnabled} instead.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000529 */
Junyu Lai626045a2023-08-28 18:49:44 +0800530 // TODO: Migrate the callers to use {@link BpfNetMapsReader#isChainEnabled} instead.
531 @Deprecated
532 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000533 public boolean isChainEnabled(final int childChain) {
Junyu Lai626045a2023-08-28 18:49:44 +0800534 return BpfNetMapsReader.isChainEnabled(sConfigurationMap, childChain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000535 }
536
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900537 private Set<Integer> asSet(final int[] uids) {
538 final Set<Integer> uidSet = new ArraySet<>();
Motomu Utsumi77b49992023-10-23 17:06:12 +0900539 for (final int uid : uids) {
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900540 uidSet.add(uid);
541 }
542 return uidSet;
543 }
544
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000545 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800546 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000547 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800548 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000549 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800550 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000551 * @throws UnsupportedOperationException if called on pre-T devices.
552 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800553 */
Junyu Lai626045a2023-08-28 18:49:44 +0800554 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000555 public void replaceUidChain(final int chain, final int[] uids) {
556 throwIfPreT("replaceUidChain is not available on pre-T devices");
557
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900558 final long match;
559 try {
560 match = getMatchByFirewallChain(chain);
561 } catch (ServiceSpecificException e) {
562 // Throws IllegalArgumentException to keep the behavior of
563 // ConnectivityManager#replaceFirewallChain API
564 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
565 }
566 final Set<Integer> uidSet = asSet(uids);
567 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
568 try {
569 synchronized (sUidOwnerMap) {
570 sUidOwnerMap.forEach((uid, config) -> {
571 // config could be null if there is a concurrent entry deletion.
572 // http://b/220084230. But sUidOwnerMap update must be done while holding a
573 // lock, so this should not happen.
574 if (config == null) {
575 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
576 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
577 uidSetToRemoveRule.add((int) uid.val);
578 }
579 });
Motomu Utsumic7c16852022-08-03 06:51:41 +0000580
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900581 for (final int uid : uidSetToRemoveRule) {
582 removeRule(uid, match, "replaceUidChain");
Motomu Utsumic7c16852022-08-03 06:51:41 +0000583 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900584 for (final int uid : uids) {
585 addRule(uid, match, "replaceUidChain");
586 }
Motomu Utsumic7c16852022-08-03 06:51:41 +0000587 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900588 } catch (ErrnoException | ServiceSpecificException e) {
589 Log.e(TAG, "replaceUidChain failed: " + e);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800590 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800591 }
592
Ken Chenf5f51332022-01-28 10:08:16 +0800593 /**
594 * Set firewall rule for uid
595 *
596 * @param childChain target chain
597 * @param uid uid to allow/deny
598 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800599 * @throws ServiceSpecificException in case of failure, with an error code indicating the
600 * cause of the failure.
601 */
Junyu Lai626045a2023-08-28 18:49:44 +0800602 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900603 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000604 throwIfPreT("setUidRule is not available on pre-T devices");
605
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900606 final long match = getMatchByFirewallChain(childChain);
607 final boolean isAllowList = isFirewallAllowList(childChain);
608 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
609 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000610
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900611 if (add) {
612 addRule(uid, match, "setUidRule");
Motomu Utsumi40230be2022-07-05 03:27:35 +0000613 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900614 removeRule(uid, match, "setUidRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000615 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800616 }
617
618 /**
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900619 * Get firewall rule of specified firewall chain on specified uid.
620 *
621 * @param childChain target chain
622 * @param uid target uid
623 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
624 * @throws UnsupportedOperationException if called on pre-T devices.
625 * @throws ServiceSpecificException in case of failure, with an error code indicating the
626 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800627 *
628 * @deprecated use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900629 */
Junyu Lai626045a2023-08-28 18:49:44 +0800630 // TODO: Migrate the callers to use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900631 public int getUidRule(final int childChain, final int uid) {
Junyu Lai626045a2023-08-28 18:49:44 +0800632 return BpfNetMapsReader.getUidRule(sUidOwnerMap, childChain, uid);
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900633 }
634
Motomu Utsumid44a33a2023-03-28 18:08:12 +0900635 private Set<Integer> getUidsMatchEnabled(final int childChain) throws ErrnoException {
636 final long match = getMatchByFirewallChain(childChain);
637 Set<Integer> uids = new ArraySet<>();
638 synchronized (sUidOwnerMap) {
639 sUidOwnerMap.forEach((uid, val) -> {
640 if (val == null) {
641 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
642 } else {
643 if ((val.rule & match) != 0) {
644 uids.add(uid.val);
645 }
646 }
647 });
648 }
649 return uids;
650 }
651
652 /**
653 * Get uids that has FIREWALL_RULE_ALLOW on allowlist chain.
654 * Allowlist means the firewall denies all by default, uids must be explicitly allowed.
655 *
656 * Note that uids that has FIREWALL_RULE_DENY on allowlist chain can not be computed from the
657 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_ALLOW rule in bpf map
658 * are determined to have FIREWALL_RULE_DENY.
659 *
660 * @param childChain target chain
661 * @return Set of uids
662 */
663 public Set<Integer> getUidsWithAllowRuleOnAllowListChain(final int childChain)
664 throws ErrnoException {
665 if (!isFirewallAllowList(childChain)) {
666 throw new IllegalArgumentException("getUidsWithAllowRuleOnAllowListChain is called with"
667 + " denylist chain:" + childChain);
668 }
669 // Corresponding match is enabled for uids that has FIREWALL_RULE_ALLOW on allowlist chain.
670 return getUidsMatchEnabled(childChain);
671 }
672
673 /**
674 * Get uids that has FIREWALL_RULE_DENY on denylist chain.
675 * Denylist means the firewall allows all by default, uids must be explicitly denyed
676 *
677 * Note that uids that has FIREWALL_RULE_ALLOW on denylist chain can not be computed from the
678 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_DENY rule in bpf map
679 * are determined to have the FIREWALL_RULE_ALLOW.
680 *
681 * @param childChain target chain
682 * @return Set of uids
683 */
684 public Set<Integer> getUidsWithDenyRuleOnDenyListChain(final int childChain)
685 throws ErrnoException {
686 if (isFirewallAllowList(childChain)) {
687 throw new IllegalArgumentException("getUidsWithDenyRuleOnDenyListChain is called with"
688 + " allowlist chain:" + childChain);
689 }
690 // Corresponding match is enabled for uids that has FIREWALL_RULE_DENY on denylist chain.
691 return getUidsMatchEnabled(childChain);
692 }
693
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900694 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800695 * Add ingress interface filtering rules to a list of UIDs
696 *
697 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
698 * allowed interface and loopback to be sent to the list of UIDs.
699 *
700 * Calling this method on one or more UIDs with an existing filtering rule but a different
701 * interface name will result in the filtering rule being updated to allow the new interface
702 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
703 *
704 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800705 * be received.
706 * @param uids an array of UIDs which the filtering rules will be set
707 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800708 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800709 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800710 */
Ken Chenf5f51332022-01-28 10:08:16 +0800711 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000712 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800713 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800714 return;
715 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000716
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900717 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
718 // ifIndex is set to 0.
719 final int ifIndex;
720 if (ifName == null) {
721 ifIndex = 0;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000722 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900723 ifIndex = mDeps.getIfIndex(ifName);
724 if (ifIndex == 0) {
725 throw new ServiceSpecificException(ENODEV,
726 "Failed to get index of interface " + ifName);
727 }
728 }
729 for (final int uid : uids) {
730 try {
731 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
732 } catch (ServiceSpecificException e) {
733 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
734 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000735 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800736 }
737
738 /**
739 * Remove ingress interface filtering rules from a list of UIDs
740 *
741 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
742 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
743 *
744 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800745 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800746 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800747 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800748 */
Ken Chenf5f51332022-01-28 10:08:16 +0800749 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000750 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800751 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800752 return;
753 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000754
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900755 for (final int uid : uids) {
756 try {
757 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
758 } catch (ServiceSpecificException e) {
759 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000760 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000761 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800762 }
763
Ken Chenf5f51332022-01-28 10:08:16 +0800764 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000765 * Update lockdown rule for uid
766 *
767 * @param uid target uid to add/remove the rule
768 * @param add {@code true} to add the rule, {@code false} to remove the rule.
769 * @throws ServiceSpecificException in case of failure, with an error code indicating the
770 * cause of the failure.
771 */
Junyu Lai626045a2023-08-28 18:49:44 +0800772 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000773 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000774 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000775
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900776 if (add) {
777 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi697b2992022-06-30 02:25:29 +0000778 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900779 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000780 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000781 }
782
783 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800784 * Request netd to change the current active network stats map.
785 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000786 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800787 * @throws ServiceSpecificException in case of failure, with an error code indicating the
788 * cause of the failure.
789 */
Junyu Lai626045a2023-08-28 18:49:44 +0800790 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien49e944c2022-03-01 15:22:20 +0800791 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000792 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
793
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900794 try {
795 synchronized (sCurrentStatsMapConfigLock) {
796 final long config = sConfigurationMap.getValue(
797 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
798 final long newConfig = (config == STATS_SELECT_MAP_A)
799 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
800 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
801 new U32(newConfig));
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000802 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900803 } catch (ErrnoException e) {
804 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000805 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900806
807 // After changing the config, it's needed to make sure all the current running eBPF
808 // programs are finished and all the CPUs are aware of this config change before the old
809 // map is modified. So special hack is needed here to wait for the kernel to do a
810 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
811 // be available to all cores and the next eBPF programs triggered inside the kernel will
812 // use the new map configuration. So once this function returns it is safe to modify the
813 // old stats map without concerning about race between the kernel and userspace.
814 final int err = mDeps.synchronizeKernelRCU();
815 maybeThrow(err, "synchronizeKernelRCU failed");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800816 }
817
Ken Chenf5f51332022-01-28 10:08:16 +0800818 /**
819 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
820 * specified. Or remove all permissions from the uids.
821 *
822 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
823 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
824 * revoke all permissions for the uids.
825 * @param uids uid of users to grant permission
826 * @throws RemoteException when netd has crashed.
827 */
828 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000829 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800830 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800831 return;
832 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000833
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900834 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
835 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000836 for (final int uid : uids) {
837 try {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900838 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000839 } catch (ErrnoException e) {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900840 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
Motomu Utsumi65271202022-07-05 08:21:41 +0000841 }
842 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900843 return;
844 }
845
846 for (final int uid : uids) {
847 try {
848 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
849 } catch (ErrnoException e) {
850 Log.e(TAG, "Failed to set permission "
851 + permissions + " to uid " + uid + ": " + e);
852 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000853 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800854 }
855
Ken Chen24330172023-10-20 13:02:14 +0800856 /**
857 * Set Data Saver enabled or disabled
858 *
859 * @param enable whether Data Saver is enabled or disabled.
860 * @throws UnsupportedOperationException if called on pre-T devices.
861 * @throws ServiceSpecificException in case of failure, with an error code indicating the
862 * cause of the failure.
863 */
864 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
865 public void setDataSaverEnabled(boolean enable) {
866 throwIfPreT("setDataSaverEnabled is not available on pre-T devices");
867
868 try {
869 final short config = enable ? DATA_SAVER_ENABLED : DATA_SAVER_DISABLED;
870 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(config));
871 } catch (ErrnoException e) {
872 throw new ServiceSpecificException(e.errno, "Unable to set data saver: "
873 + Os.strerror(e.errno));
874 }
875 }
876
Motomu Utsumi77b49992023-10-23 17:06:12 +0900877 /**
878 * Set ingress discard rule
879 *
880 * @param address target address to set the ingress discard rule
881 * @param iface allowed interface
882 */
883 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
884 public void setIngressDiscardRule(final InetAddress address, final String iface) {
885 throwIfPreT("setIngressDiscardRule is not available on pre-T devices");
886 final int ifIndex = mDeps.getIfIndex(iface);
887 if (ifIndex == 0) {
888 Log.e(TAG, "Failed to get if index, skip setting ingress discard rule for " + address
889 + "(" + iface + ")");
890 return;
891 }
892 try {
893 sIngressDiscardMap.updateEntry(new IngressDiscardKey(address),
894 new IngressDiscardValue(ifIndex, ifIndex));
895 } catch (ErrnoException e) {
896 Log.e(TAG, "Failed to set ingress discard rule for " + address + "("
897 + iface + "), " + e);
898 }
899 }
900
901 /**
902 * Remove ingress discard rule
903 *
904 * @param address target address to remove the ingress discard rule
905 */
906 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
907 public void removeIngressDiscardRule(final InetAddress address) {
908 throwIfPreT("removeIngressDiscardRule is not available on pre-T devices");
909 try {
910 sIngressDiscardMap.deleteEntry(new IngressDiscardKey(address));
911 } catch (ErrnoException e) {
912 Log.e(TAG, "Failed to remove ingress discard rule for " + address + ", " + e);
913 }
914 }
915
Motomu Utsumi166f9662022-09-01 10:35:29 +0900916 /** Register callback for statsd to pull atom. */
Junyu Lai626045a2023-08-28 18:49:44 +0800917 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi166f9662022-09-01 10:35:29 +0900918 public void setPullAtomCallback(final Context context) {
919 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
920
921 final StatsManager statsManager = context.getSystemService(StatsManager.class);
922 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
923 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
924 }
925
926 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
927 throws ErrnoException {
928 // forEach could restart iteration from the beginning if there is a concurrent entry
929 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
930 // So using Set to count the number of entry in the map.
931 Set<K> keySet = new ArraySet<>();
932 map.forEach((k, v) -> keySet.add(k));
933 return keySet.size();
934 }
935
936 /** Callback for StatsManager#setPullAtomCallback */
937 @VisibleForTesting
938 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
939 if (atomTag != NETWORK_BPF_MAP_INFO) {
940 Log.e(TAG, "Unexpected atom tag: " + atomTag);
941 return StatsManager.PULL_SKIP;
942 }
943
944 try {
945 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
946 getMapSize(sUidPermissionMap)));
947 } catch (ErrnoException e) {
948 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
949 return StatsManager.PULL_SKIP;
950 }
951 return StatsManager.PULL_SUCCESS;
952 }
953
Motomu Utsumi310850f2022-09-02 12:48:20 +0900954 private String permissionToString(int permissionMask) {
955 if (permissionMask == PERMISSION_NONE) {
956 return "PERMISSION_NONE";
957 }
958 if (permissionMask == PERMISSION_UNINSTALLED) {
959 // PERMISSION_UNINSTALLED should never appear in the map
960 return "PERMISSION_UNINSTALLED error!";
961 }
962
963 final StringJoiner sj = new StringJoiner(" ");
964 for (Pair<Integer, String> permission: PERMISSION_LIST) {
965 final int permissionFlag = permission.first;
966 final String permissionName = permission.second;
967 if ((permissionMask & permissionFlag) != 0) {
968 sj.add(permissionName);
969 permissionMask &= ~permissionFlag;
970 }
971 }
972 if (permissionMask != 0) {
973 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
974 }
975 return sj.toString();
976 }
977
Motomu Utsumi372c9b42022-09-02 19:02:56 +0900978 private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
979 try {
980 final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
981 pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
982 } catch (ErrnoException e) {
983 pw.println("Failed to read ownerMatch configuration: " + e);
984 }
985 }
986
Motomu Utsumic675d6f2022-09-02 18:15:25 +0900987 private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
988 try {
989 final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
990 final String currentStatsMap =
991 (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
992 pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
993 } catch (ErrnoException e) {
994 pw.println("Falied to read current statsMap configuration: " + e);
995 }
996 }
997
Ken Chen24330172023-10-20 13:02:14 +0800998 private void dumpDataSaverConfig(final IndentingPrintWriter pw) {
999 try {
1000 final short config = sDataSaverEnabledMap.getValue(DATA_SAVER_ENABLED_KEY).val;
1001 // Any non-zero value converted from short to boolean is true by convention.
1002 pw.println("sDataSaverEnabledMap: " + (config != DATA_SAVER_DISABLED));
1003 } catch (ErrnoException e) {
1004 pw.println("Failed to read data saver configuration: " + e);
1005 }
1006 }
Ken Chene6d511f2022-01-25 11:10:42 +08001007 /**
1008 * Dump BPF maps
1009 *
Motomu Utsumi310850f2022-09-02 12:48:20 +09001010 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +08001011 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +09001012 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +08001013 * @throws IOException when file descriptor is invalid.
1014 * @throws ServiceSpecificException when the method is called on an unsupported device.
1015 */
Junyu Lai626045a2023-08-28 18:49:44 +08001016 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi310850f2022-09-02 12:48:20 +09001017 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +08001018 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00001019 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +08001020 throw new ServiceSpecificException(
1021 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
1022 + " devices, use dumpsys netd trafficcontroller instead.");
1023 }
Maciej Żenczykowskid70a3302023-09-06 16:45:25 +00001024
1025 pw.println("TrafficController"); // required by CTS testDumpBpfNetMaps
Motomu Utsumi310850f2022-09-02 12:48:20 +09001026
Motomu Utsumi316d0572022-09-15 13:24:48 +09001027 pw.println();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001028 if (verbose) {
Motomu Utsumief546a92022-10-05 16:42:29 +09001029 pw.println();
1030 pw.println("BPF map content:");
1031 pw.increaseIndent();
1032
Motomu Utsumi372c9b42022-09-02 19:02:56 +09001033 dumpOwnerMatchConfig(pw);
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001034 dumpCurrentStatsMapConfig(pw);
1035 pw.println();
1036
Motomu Utsumief546a92022-10-05 16:42:29 +09001037 // TODO: Remove CookieTagMap content dump
1038 // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
1039 // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
1040 // need to be updated before remove the dump from BpfNetMaps.
1041 BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
1042 (key, value) -> "cookie=" + key.socketCookie
1043 + " tag=0x" + Long.toHexString(value.tag)
1044 + " uid=" + value.uid);
Motomu Utsumi956d86c2022-09-02 17:01:25 +09001045 BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
1046 (uid, match) -> {
1047 if ((match.rule & IIF_MATCH) != 0) {
1048 // TODO: convert interface index to interface name by IfaceIndexNameMap
1049 return uid.val + " " + matchToString(match.rule) + " " + match.iif;
1050 } else {
1051 return uid.val + " " + matchToString(match.rule);
1052 }
1053 });
Motomu Utsumi310850f2022-09-02 12:48:20 +09001054 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
1055 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
Motomu Utsumi77b49992023-10-23 17:06:12 +09001056 BpfDump.dumpMap(sIngressDiscardMap, pw, "sIngressDiscardMap",
1057 (key, value) -> "[" + key.dstAddr + "]: "
1058 + value.iif1 + "(" + mDeps.getIfName(value.iif1) + "), "
1059 + value.iif2 + "(" + mDeps.getIfName(value.iif2) + ")");
Ken Chen24330172023-10-20 13:02:14 +08001060 dumpDataSaverConfig(pw);
Motomu Utsumief546a92022-10-05 16:42:29 +09001061 pw.decreaseIndent();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001062 }
Ken Chene6d511f2022-01-25 11:10:42 +08001063 }
1064
Maciej Żenczykowski70fbfa42023-07-18 20:14:38 +00001065 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi7abeaa42022-07-20 07:54:18 +00001066 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001067}